-
Notifications
You must be signed in to change notification settings - Fork 5
/
Gramadoir.pm.in
1210 lines (1059 loc) · 32.3 KB
/
Gramadoir.pm.in
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package Lingua::@TEANGA@::Gramadoir;
use 5.008;
use strict;
use warnings;
use Carp;
use File::Spec;
use Storable;
use Memoize;
use Encode qw(decode from_to);
use String::Approx qw(amatch adist);
use Lingua::@TEANGA@::Gramadoir::Languages;
our $VERSION = '@PACKAGE_VERSION@';
use vars qw(@FOCAIL @MORPH @PUREMORPH @TOKEN %EILE %EARRAIDI %NOCOMBO %POS %SOP %GRAMS %MESSAGES %IGNORE $lh);
memoize('tag_one_word', TIE => [ 'Memoize::ExpireLRU',
CACHESIZE => 5000,
]);
=head1 NAME
Lingua::@TEANGA@::Gramadoir - Check the grammar of @NAME_ENGLISH@ language text
=head1 SYNOPSIS
use Lingua::@TEANGA@::Gramadoir;
my $gr = new Lingua::@TEANGA@::Gramadoir;
my $errors = $gr->grammatical_errors( $text );
foreach my $error (@$errors) {
# process $error appropriately
}
=head1 DESCRIPTION
This module contains the code for segmentation, spell checking,
part-of-speech tagging, and grammar checking used by "An GramadE<oacute>ir",
an open-source grammar and style checker that can be used
with vim, emacs, OpenOffice, or through a command-line interface.
An GramadE<oacute>ir is intended as a platform for the development of
sophisticated natural language processing tools for languages with
limited computational resources.
The Perl code contained in this module is generated automatically
from a higher-level representation of the grammatical rules
and should not be edited directly. Anyone interested in helping
improve the lexicon or the rule sets should download the
developers' pack from the An GramadE<oacute>ir web site:
L<http://borel.slu.edu/gramadoir/>.
=head1 CONSTRUCTOR
=over 4
=item new %PARAMS
Constructs an instance of the grammar checker and loads the lexicon
into memory. It should only be called once. Options may be specified
by passing a hash containing any of the following keys:
fix_spelling => 0
Suggest replacements for misspelled or unknown words.
use_ignore_file => 0
Read a file containing words to be ignored when checking spelling and grammar.
unigram_tagging => 1
Resolve ambiguous part of speech according to frequency. This should
be set to false only for debugging purposes because the pattern matching
for grammatical errors relies on complete disambiguation.
interface_language => ""
Specify the language of output messages
(B<not> necessarily the language of the text to be checked).
With the default value, Locale::Maketext attempts to determine
the correct language to use based on things like your
environment variables.
input_encoding => '@NATIVE@'
Specify the encoding for all texts passed to one of the module's exported
functions. There is no currently no way to change the encoding of
the data returned by the exported functions (always encoded as perl strings).
=back
=cut
sub new {
my $invocant = shift;
my $class = ref($invocant) || $invocant;
my $self = {
fix_spelling => 0,
use_ignore_file => 0,
unigram_tagging => 1,
interface_language => '',
input_encoding => '@NATIVE@',
@_,
};
if ($self->{'interface_language'}) {
$lh = Lingua::@TEANGA@::Gramadoir::Languages->get_handle($self->{'interface_language'});
}
else {
$lh = Lingua::@TEANGA@::Gramadoir::Languages->get_handle();
}
croak 'Could not set interface language' unless $lh;
( my $datapath ) = __FILE__ =~ /(.*)\.pm/;
my $ref;
my $errormsg = gettext('%s: problem reading the database\n',
gettext('An Gramadoir'));
eval {$ref = retrieve(File::Spec->catfile($datapath, 'eile.hash'))};
croak $errormsg if ($@ or !$ref);
%EILE = %$ref;
eval {$ref = retrieve(File::Spec->catfile($datapath, 'earraidi.hash'))};
croak $errormsg if ($@ or !$ref);
%EARRAIDI = %$ref;
eval {$ref = retrieve(File::Spec->catfile($datapath, 'nocombo.hash'))};
croak $errormsg if ($@ or !$ref);
%NOCOMBO = %$ref;
eval {$ref = retrieve(File::Spec->catfile($datapath, 'pos.hash'))};
croak $errormsg if ($@ or !$ref);
%POS = %$ref;
%SOP = reverse %POS;
eval {$ref = retrieve(File::Spec->catfile($datapath, '3grams.hash'))};
croak $errormsg if ($@ or !$ref);
%GRAMS = %$ref;
eval {$ref = retrieve(File::Spec->catfile($datapath, 'messages.hash'))};
croak $errormsg if ($@ or !$ref);
%MESSAGES = %$ref;
for my $i (0 .. 6) {
eval {$ref = retrieve(File::Spec->catfile($datapath, "focail$i.hash" ) )};
croak $errormsg if ($@ or !$ref);
push @FOCAIL, $ref;
}
eval {$ref = retrieve(File::Spec->catfile($datapath, 'token.hash'))};
croak $errormsg if ($@ or !$ref);
@TOKEN = @$ref;
foreach my $rule (@TOKEN) {
my $patt = $rule->{'patt'};
$rule->{'compiled'} = qr/$patt/;
$rule->{'tail'} = substr($rule->{'tag'},1,1);
}
eval {$ref = retrieve(File::Spec->catfile($datapath, 'morph.hash'))};
croak $errormsg if ($@ or !$ref);
@MORPH = @$ref;
foreach my $rule (@MORPH) {
my $patt = $rule->{'patt'};
$rule->{'compiled'} = qr/$patt/;
$patt = $rule->{'rootpos'};
if ($patt =~ m/^<\.([+*])?>$/) {
$rule->{'poscompiled'} = ''; # for speed
}
else {
$patt =~ s/\./[^>]/g;
$patt =~ s/>$/\/?>/;
$rule->{'poscompiled'} = qr/$patt/;
}
push @PUREMORPH, $rule if ($rule->{'level'} == -1);
}
if ($self->{'use_ignore_file'}) {
my $homedir = $ENV{HOME} || $ENV{LOGDIR}; # || (getpwuid($>))[7];
if (open (DATAFILE, File::Spec->catfile( $homedir, '.neamhshuim' ))) {
while (<DATAFILE>) {
chomp;
carp gettext('%s: `%s\' corrupted at %s\n',
gettext('An Gramadoir'), ".neamhshuim", $.) if /^$/;
$IGNORE{$_}++;
}
}
}
return bless $self, $class;
}
sub gettext
{
my ( $string, @rest ) = @_;
$string =~ s/\[/~[/g;
$string =~ s/\]/~]/g;
$string =~ s/\%s/[_1]/;
$string =~ s/\%s/[_2]/;
$string =~ s/\%s/[_3]/;
$string =~ s/\\n$/\n/;
$string =~ s#\\/\\([1-9])\\/#/[_$1]/#;
$string =~ s#\\/([^_\\]+)\\/#/$1/#;
return $lh->maketext($string, @rest);
}
##############################################################################
=head1 METHODS
=over
=item get_sentences TEXT
Splits the input TEXT up into sentences and returns a reference to an
array containing the sentences.
=cut
##############################################################################
# approximates "abairti" from bash version
# General philosophy is that it is *not* the job of the grammar checker
# to filter incoming texts (of, say, TeX or SGML markup). On the other hand,
# SGML-like markup *must* be stripped so it doesn't interfere with
# the real work of the grammar checker.
sub get_sentences
{
my ( $self, $text ) = @_;
return undef unless defined $text;
eval {from_to($text,$self->{'input_encoding'},'@NATIVE@') };
# TRANSLATORS: "conversion" here means conversion between character encodings
croak gettext('conversion from %s is not supported',
$self->{'input_encoding'}) if $@;
my $answer = get_sentences_real($text);
map{$_ = decode('@NATIVE@', $_)} @$answer;
# foreach my $s (@$answer) {
# $s = decode('@NATIVE@', $s);
# }
return $answer;
}
my $BD="\001";
my $NOBD="\002";
sub get_sentences_real
{
my $sentences = [];
for ($_[0]) {
s/^\s+//;
s/<[^>]*>/ /g; # naive; see comments above
s/\\[tnvfr]/ /g;
s/&/&/g; # this one first!
s/</</g;
s/>/>/g;
s/$NOBD//g;
s/$BD//g;
giorr ( $_ );
s/([^$NOBD][.?!][]"')}]*)[ \t\n]+/$1$BD/g;
s/"/"/g; # ' ok (note " in prev line)
s/\s+/ /g;
s/$NOBD//g;
@$sentences = split /$BD/;
}
return $sentences;
}
# two arguments; first is word to be tagged, 2nd is string of grammatical bytes
sub add_grammar_tags
{
my ( $self, $word, $grambytes ) = @_;
my $tagz = $self->get_grammar_tags($grambytes);
my $ans;
if ( length($grambytes) == 1) {
$tagz =~ m/^<([A-Z])/;
$ans = $tagz.$word."</".$1.">";
}
else {
$tagz =~ s/>/\/>/g;
$ans = "<B><Z>".$tagz."</Z>".$word."</B>";
}
return $ans;
}
# convert grammar bytes into string of tags like "<N><V><A>"
sub get_grammar_tags
{
my ( $self, $grambytes ) = @_;
my $ans='';
foreach my $byte (split //, $grambytes) {
my $tag = $POS{$byte};
if (defined($tag)) {
$ans = $ans.$tag;
}
else {
carp gettext('%s: illegal grammatical code\n', gettext('An Gramadoir'));
}
}
carp gettext('%s: no grammar codes: %s\n', gettext('An Gramadoir'), "x") unless ($ans);
return $ans;
}
# even though not called explicitly in this module,
# these functions are called indirectly to implement
# \l and \L in morphological rules; see Makefile.PL.in
sub mylc {
my ($string) = @_;
$string =~ tr/@CAPITALS@/@LOWERS@/;
return $string;
}
sub mylcfirst {
my ($string) = @_;
$string =~ s/^(.)(.*)$/mylc($1).$2/e;
return $string;
}
sub clean_lookup
{
my ( $self, $current ) = @_;
for my $href ( @FOCAIL ) {
if ( exists($href->{$current}) ) {
return $self->get_grammar_tags($href->{$current});
}
}
return "";
}
# look up in the hash tables FOCAIL, EILE, EARRAIDI consecutively
# same arguments, return conventions as tag_recurse, except
# no maximum depth set since this doesn't recurse.
sub lookup
{
my ( $self, $original, $current, $level, $posans ) = @_;
$$posans = $self->clean_lookup($current);
my $ans;
if ($$posans) {
if ( $level == 0 ) {
$ans = "<E msg=\"MOIRF{$current}\"><X>".$original."</X></E>";
}
elsif ( $level == 1 ) {
$ans = "<E msg=\"CAIGHDEAN{$current}\"><X>".$original."</X></E>";
}
elsif ( $level == 2 ) {
$ans = "<E msg=\"DROCHMHOIRF{$current}\"><X>".$original."</X></E>";
}
else {
# -1 will only occur when tagging as compound and
# recursing on the two components, in which case
# (for now), the tags don't matter
$ans = '<X>';
}
return $ans;
}
$$posans = '<OK>';
if ( exists($EILE{$current}) ) {
my $correction = $EILE{$current};
if ( $level == -1 ) {
$ans = "<E msg=\"CAIGHDEAN{$correction}\"><X>".$original."</X></E>";
}
elsif ( $level == 0 ) {
$ans = "<E msg=\"CAIGHMOIRF{$correction}\"><X>".$original."</X></E>";
}
elsif ( $level == 1 ) {
$ans = "<E msg=\"CAIGHDEAN{$current ($correction)}\"><X>".$original."</X></E>";
}
else {
$ans = "<E msg=\"DROCHMHOIRF{$current ($correction)}\"><X>".$original."</X></E>";
}
return $ans;
}
if ( exists($EARRAIDI{$current}) ) {
my $correction = $EARRAIDI{$current};
if ( $level == -1 ) {
$ans = "<E msg=\"MICHEART{$correction}\"><X>".$original."</X></E>";
}
else {
$ans = "<E msg=\"MIMHOIRF{$current ($correction)}\"><X>".$original."</X></E>";
}
return $ans;
}
return "";
}
# note use of "tag_recurse" on the conjectural pieces below;
# this is (primarily) to deal with capitalization of the halves.
# definitely *don't* want to call full tag on the two pieces or
# else *this* function will recurse
sub tag_as_compound
{
my ( $self, $word ) = @_;
my $dummy;
if ($word =~ m/^([^-]+)-(.*)$/) {
my $l = $1;
my $r = $2;
my $t1 = $self->tag_recurse( $l, $l, -1, \$dummy, 2 );
my $t2 = $self->tag_recurse( $r, $r, -1, \$dummy, 2 );
if ($t1 && $t2) {
if ($t1 !~ m/<E/ && $t2 !~ m/<E/) {
return "<E msg=\"COMHFHOCAL{$l+$r}\"><X>".$word."</X></E>";
}
else {
return "<E msg=\"COMHCHAIGH{$l+$r}\"><X>".$word."</X></E>";
}
}
}
else {
my $len = length($word);
for (my $i = 3; $i < $len-2; $i++) { # i=len of left
my $l = substr($word, 0, $i);
my $r = substr($word, $i, $len - $i);
if (!exists($NOCOMBO{$l}) &&
!exists($NOCOMBO{$r})) {
my $tl = $self->tag_recurse($l,$l,-1,\$dummy,2);
my $tr = $self->tag_recurse($r,$r,-1,\$dummy,2);
if ( $tl && $tr ) {
if ($tl !~ m/<E/ && $tr !~ m/<E/) {
return "<E msg=\"COMHFHOCAL{$l+$r}\"><X>".$word."</X></E>";
}
else {
return "<E msg=\"COMHCHAIGH{$l+$r}\"><X>".$word."</X></E>";
}
}
}
}
}
return "";
}
sub tag_as_near_miss
{
my ( $self, $word ) = @_;
if ($self->{'fix_spelling'}) {
my $wordlen = length($word);
if ($wordlen > 2) {
for my $href ( @FOCAIL ) {
my %matches;
my $dist = "1";
if ($word =~ m/[@CAPITALS@]/) {
$dist =~ s/$/ i/;
}
for (my $i = 0; $i < $wordlen-1; $i++) {
my $perm = $word;
$perm =~ s/(.{$i})(.)(.)/$1$3$2/;
$matches{$perm}++ if (exists($href->{$perm}));
}
for (amatch($word, [ $dist, "I0S0" ], (keys %$href))) {
$matches{$_}++ if (length($_)==$wordlen-1);
}
for (amatch($word, [ $dist, "D0S0" ], (keys %$href))) {
$matches{$_}++ if (length($_)==$wordlen+1);
}
for (amatch($word, [ $dist, "D0I0" ], (keys %$href))) {
$matches{$_}++ if (length($_)==$wordlen);
}
my $suggs = join(', ', (keys %matches));
return "<E msg=\"MOLADH{$suggs}\"><X>$word</X></E>" if $suggs;
}
}
}
return "";
}
sub find_bad_three_grams
{
my ( $self, $word ) = @_;
$word =~ s/^/</;
$word =~ s/$/>/;
my $end = length($word) - 2;
for (my $i = 0; $i < $end; $i++) {
my $cand = substr($word, $i, 3);
if (!exists($GRAMS{$cand})) {
$cand =~ tr/<>/^$/;
$word =~ tr/<>//d;
return "<E msg=\"GRAM{$cand}\"><X>$word</X></E>";
}
}
return "";
}
sub tag_one_word_clean
{
my ( $self, $word ) = @_;
my $ans = $self->clean_tag_recurse($word, 4);
if ($ans) {
# sort -u, plus take out <F> if there are others
my %tempseen;
while ($ans =~ m/(<[^>]+>)/g) {
my $cod = $SOP{$1};
if (defined($cod)) {
$tempseen{$cod}++;
}
else {
carp gettext('%s: illegal grammatical code\n',
gettext('An Gramadoir'));
}
}
my $codez = join('', sort(keys %tempseen));
$codez =~ s/\177// if (length($codez) > 1);
$ans = $self->add_grammar_tags($word, $codez);
}
return $ans;
}
# takes a single word as an argument and returns it tagged, without fail
# e.g. it will get something like <X>neamhword</X> if it is unknown
sub tag_one_word
{
my ( $self, $word ) = @_;
if ($self->{'use_ignore_file'}) {
return "<Y>".$word."</Y>" if ( exists($IGNORE{$word}) );
}
my $ans = $self->tag_one_word_clean($word);
return $ans if $ans;
my $dummy;
$ans = $self->tag_recurse($word, $word, -1, \$dummy, 6);
return $ans if $ans;
$ans = $self->tag_as_compound($word);
return $ans if $ans;
$ans = $self->tag_as_near_miss($word);
return $ans if $ans;
$ans = $self->find_bad_three_grams($word);
return $ans if $ans;
return "<X>$word</X>";
}
##############################################################################
=item tokenize TEXT
Splits the input TEXT up into orthographic words and returns a reference to an
array containing the words.
=cut
##############################################################################
sub tokenize
{
my ( $self, $text ) = @_;
return undef unless defined $text;
eval {from_to($text,$self->{'input_encoding'},'@NATIVE@') };
croak gettext('conversion from %s is not supported',
$self->{'input_encoding'}) if $@;
my $answer = [];
my $sentences = get_sentences_real($text);
foreach my $sentence (@$sentences) {
$sentence = $self->tokenize_real($sentence);
push @$answer, $1 while ($sentence =~ m/<[A-Zc][^>]*>([^<]*)<\/[A-Zc]>/g);
}
foreach my $s (@$answer) {
$s = decode('@NATIVE@', $s);
}
return $answer;
}
sub maybe_tokenize
{
my ( $self, $tag, $word, $t ) = @_;
if ( $t eq 'd') {
if ($self->tag_one_word_clean($word)) {
return '<c>'.$word.'</c>';
}
else {
return $word;
}
}
else {
return $tag.$word.'</'.$t.'>';
}
}
# takes a sentence as input and returns the sentence with trivial markup
# around each token (in bash version this was part of abairti)
sub tokenize_real
{
my ( $self, $sentence ) = @_;
my $answer="";
# assumes get_sentences_real has been called, collapses \s+ to " "
foreach my $chunk (split / /,$sentence) {
if ($chunk =~ m/^[@BDCHARS@]+$/) {
$chunk =~ s/^/<c>/;
$chunk =~ s/$/<\/c>/;
}
else {
my $chunkdone = '1';
foreach my $rule (@TOKEN) {
my $chtemp="";
my $p = $rule->{'compiled'};
my $tag = $rule->{'tag'};
my $t = $rule->{'tail'};
my $todo;
while ($chunk =~ /([^<]*)(<[A-Zc][^>]*>[^<]+<\/[A-Zc]>)/g) {
$todo = $1;
my $done = $2;
if ($todo) {
$chunkdone = '';
$todo =~ s/$p/$self->maybe_tokenize($tag,$1,$t)/eg;
}
$chtemp .= $todo.$done;
}
$chunk =~ /([^>]*)$/;
$todo = $1;
if ($todo) {
$chunkdone = '';
$todo =~ s/$p/$self->maybe_tokenize($tag,$1,$t)/eg;
}
last if $chunkdone;
$chtemp .= $todo;
$chunk = $chtemp;
}
# might have <Y>borel.slu.edu/&</Y>; as a URL
$chunk =~ s/&(quot|[gl]t|amp)(<\/.>);/&$1;$2/g;
# all others are external for now
$chunk =~ s/&<c>(quot|[gl]t|amp)<\/c>;/&$1;/g;
$chunk =~ s/(<\/.>)</$1 </g;
}
$answer .= " " if $answer;
$answer .= $chunk;
}
return $answer;
}
# takes an untagged sentence (usually fresh from get_sentences_real),
# tokenizes, and adds a preliminary XML markup consisting of all possible
# parts of speech for each word
sub unchecked_xml
{
my ( $self, $sentence ) = @_;
$sentence = $self->tokenize_real($sentence);
$sentence =~ s/(<[A-Zc][^>]*>[^<]+<\/[A-Zc]>) \1/<E msg="DUBAILTE">$1 $1<\/E>/g;
1 while ( $sentence =~ s/<c>([^<]*)<\/c>/$self->tag_one_word($1);/e );
$sentence =~ s/<E msg="DUBAILTE">(<E[^>]+><X>[^<]+<\/X><\/E>) \1<\/E>/$1 $1/g;
$sentence =~ s/^/<line> /;
$sentence =~ s/$/ <\/line>/;
return $sentence;
}
##############################################################################
=item spell_check TEXT
Returns a reference to an array containing the misspelled words appearing
in the input text.
=cut
##############################################################################
# current behavior is to accept <F> words as correct, like aspell-ga literary.
# Just change X -> FX below to reject these words (this would
# break the replcheck target though...)
sub spell_check
{
my ( $self, $text ) = @_;
return undef unless defined $text;
eval {from_to($text,$self->{'input_encoding'},'@NATIVE@') };
croak gettext('conversion from %s is not supported',
$self->{'input_encoding'}) if $@;
my $badwords = [];
my $sentences = get_sentences_real($text);
foreach my $s (@$sentences) {
$s = $self->unchecked_xml($s);
if ($s =~ m/<[X]>/) {
$s =~ s/<[^X\/][^>]*>//g;
$s =~ s/<\/[^X][^>]*>//g;
$s =~ s/^[^<]*<[X]>//;
$s =~ s/<\/[X]>[^<]*$//;
$s =~ s/<\/[X]>[^<]*<[X]>/\n/g;
$s = decode('@NATIVE@', $s);
push @$badwords,split (/\n/,$s);
}
}
return $badwords;
}
##############################################################################
=item all_possible_tags WORD
Takes the input WORD and returns it with (XML-style) markup
indicating all of its possible parts of speech.
=cut
##############################################################################
sub all_possible_tags
{
my ( $self, $word ) = @_;
return undef unless defined $word;
eval {from_to($word,$self->{'input_encoding'},'@NATIVE@') };
croak gettext('conversion from %s is not supported',
$self->{'input_encoding'}) if $@;
return decode('@NATIVE@', $self->tag_one_word($word));
}
##############################################################################
=item add_tags TEXT
Takes the input TEXT and returns a reference to an array of sentences
with (XML-style) *disambiguated* part-of-speech tags. Does not do
any grammatical rule checking.
=cut
##############################################################################
sub add_tags
{
my ( $self, $text ) = @_;
return undef unless defined $text;
eval {from_to($text,$self->{'input_encoding'},'@NATIVE@') };
croak gettext('conversion from %s is not supported',
$self->{'input_encoding'}) if $@;
my $sentences = get_sentences_real($text);
foreach my $s (@$sentences) {
$s = $self->add_tags_real($s);
$s =~ s/<\/?E[^>]*>//g; # just POS tags
$s = decode('@NATIVE@', $s);
}
return $sentences;
}
# takes a sentence as input, usually fresh from get_sentences_real
# Forms the main step in add_tags, and also in xml_stream and
# grammatical_errors (in the latter two cases being followed by
# a call to "rialacha" to add additional <E> markup)
sub add_tags_real
{
(my $self, my $sentence) = @_;
$sentence = unchecked_xml(@_);
comhshuite($sentence);
aonchiall($sentence);
aonchiall_deux($sentence);
unigram($sentence) if $self->{'unigram_tagging'};
return $sentence;
}
##############################################################################
=item xml_stream TEXT
Takes the input TEXT and returns it as well-formed XML (encoded as perl
strings, not utf-8) with full grammatical markup. Error messages are not
localized. This function should only be exported for debugging/development
purposes. Use "grammatical_errors" (which is basically "xml_stream" plus
some whittling down) as an interface with other programs.
=cut
##############################################################################
# bash version's vanilla_xml_output/aspell_xml_output
sub xml_stream
{
my ( $self, $text ) = @_;
return undef unless defined $text;
eval {from_to($text,$self->{'input_encoding'},'@NATIVE@') };
croak gettext('conversion from %s is not supported',
$self->{'input_encoding'}) if $@;
my $langcode='@TEANGA@';
my $langlower="\L$langcode\E";
my $answer='<?xml version="1.0" encoding="utf-8" standalone="no"?>';
$answer = $answer."\n<!DOCTYPE teacs SYSTEM \"http://borel.slu.edu/dtds/gram-$langlower.dtd\">";
$answer = $answer."\n<teacs>\n";
my $sentences = get_sentences_real($text);
foreach my $s (@$sentences) {
$s = $self->add_tags_real($s);
rialacha ($s);
}
$answer = $answer.join("\n", @$sentences);
$answer = $answer."\n</teacs>\n";
$answer = decode("@NATIVE@", $answer);
return $answer;
}
sub localize_me
{
my ( $self, $msg ) = @_;
$msg =~ m/^([^{]+)/;
my $macro = $1;
my $msgstr = '-';
if (exists($MESSAGES{$macro})) {
my $msgid = $MESSAGES{$macro};
if ($msg =~ m/{(.*)}$/) {
my $argument = $1;
$argument =~ tr/_/ /; # from EILE database
$msgstr = gettext($msgid, $argument);
}
else {
$msgstr = gettext($msgid);
}
}
else {
carp gettext('%s: unrecognized error macro: %s\n',
gettext('An Gramadoir'),$macro);
}
return $msgstr;
}
#
# The next batch of functions consists of helpers for grammatical_errors
#
# used to be " " x length($text) but we need to keep newlines for coords
sub whiteout
{
my ( $text ) = @_;
$text =~ s/[^\n]/ /g;
return $text;
}
# preserve length; see computation of "offset" attribute below; convention is
# that it is measured with entities in place of &, <, >, ". But if we
# just leave the entities they mess up the various [^A-Za-z]* patts
sub strip_entities
{
my ( $text ) = @_;
$text =~ s/"/""""""/g;
$text =~ s/</<<<</g;
$text =~ s/>/>>>>/g;
$text =~ s/&/&&&&&/g;
return $text;
}
# note amp is done last of course
sub deentify
{
my ( $text ) = @_;
$text =~ s/"/"/g;
$text =~ s/</</g;
$text =~ s/>/>/g;
$text =~ s/&/&/g;
return $text;
}
# used by regexify; e.g. ^ in Esperanto, $ in "$100" tokens, etc.
sub escape_meta
{
my ( $text ) = @_;
$text =~ s/\[/\\[/g;
$text =~ s/\]/\\]/g;
$text =~ s/([.?+\$*^()])/\\$1/g;
return $text;
}
# Called from search routine below; takes a chunk of the XML
# stream and turns it into a regex that can be matched against
# the original unmodified input stream. So we need to escape
# regex chars like parens, ^, $, and strip markup...
# Assuming no error markup is left when this is called; see below...
sub regexify
{
my ( $text ) = @_;
$text =~ s/ *<\/?line> *//;
$text =~ s/<\/E>//; # nested
if ($text =~ m/^[^<]+/) {
$text =~ s/^[^<]+/"[^@BDCHARS@]*?"/e;
}
$text = deentify($text); # do after previous!
$text =~ s/<[A-Z][^>]*>([^<]+)<\/[A-Z]>[^<]*/escape_meta($1)."[^@BDCHARS@]*?"/eg; # note * not + in replacement; also minimal match avoids some amazing implausible errors
$text =~ s/ /\\s+/g; # spaces within word tokens only
$text =~ s/(["&<>])/$1+/g; # within tokens only (like URLs!)
# need this b/c of strip_entities
return $text;
}
# call this on the raw input string that we use to search for
# global coordinates of errors; need to strip out markup and stuff
# but without changing any substring lengths or newlines.
# Should mimic similar lines in get_sentences_real
sub tidy_input
{
my ( $text ) = @_;
$text =~ s/(<[^>]*>)/whiteout($1);/eg;
$text =~ s/\\[tnvfr]/ /g;
$text =~ s/$NOBD/ /g;
$text =~ s/$BD/ /g;
# next three lines add "buffering" for easier searching per-line
# these are subtracted appropriately from offsets when matching occurs
$text =~ s/^/ /;
$text =~ s/\n/ \n /g;
$text =~ s/$/ /;
return $text;
}
##############################################################################
=item grammatical_errors TEXT
Returns the grammatical errors in the input TEXT as a reference to an array,
one error per element of the array, with each error given in a simple
XML format usable by other applications. Error messages are localized
according to locale settings as determined by Locale::Maketext.
=cut
##############################################################################
# like the bash "xml_api"
sub grammatical_errors
{
my ( $self, $text ) = @_;
return undef unless defined $text;
eval {from_to($text,$self->{'input_encoding'},'@NATIVE@') };
croak gettext('conversion from %s is not supported',
$self->{'input_encoding'}) if $@;
my $pristine = tidy_input($text);
my $errors = []; # array reference to return
# endoflast is global offset in $pristine following the end of last error
my $endoflast = 0;
my $toy = 0; # line number at position $endoflast; lines count from 1
my $tox = -1; # line position of end of last match (not like $+[0]!)
my $sentences = get_sentences_real($text);
# these "plain" sentences include entities like " and
# are used as the "context" attribute in the --api output
foreach my $plain (@$sentences) {
my $s = $self->add_tags_real($plain);
rialacha ($s); # just like xml_stream now
if ($s =~ /<E/) {
my $buffered = strip_entities(" $plain ");
while ($s =~ m!(.*?)(<E[^>]+>)(.*?)</E>!g) {
my $prefix = $1;
my $thiserror = $2; # modify and push onto ans
my $errorregex = $3;
# deal with rare nested errors - only happens
# when one (usu. len==1) is inserted in int.
# of existing error of len>=3 (no overlapping!)
if ($errorregex =~ m/^(.*)(<E[^>]+>)(.*)$/) {
$prefix .= $1;
$thiserror = $2;
$errorregex = $3;
}
$prefix = regexify($prefix);
$errorregex = regexify($errorregex);
$errorregex =~ s/\[\^[^]]+\]\*$//;
my $fromy;
my $fromx;
my $matchregex = "$prefix($errorregex)";
$matchregex =~ s/^/(?<=[^@BDCHARS@])/ unless $prefix;
# print "MRE=$matchregex\n";
$pristine =~ m!$matchregex!gs;
my $globs = $-[1];
my $globe = $+[1];
unless (defined($globs) and defined($globe)) {
# segfaults from carp?
print STDERR "regex error in computing global coordinates for $thiserror\nMRE=$matchregex\n";
next;
}
my $str = substr($pristine, $endoflast, $globs - $endoflast);
# toy is that of the previous err (tox too)
$fromy = $toy + ($str =~ tr/\n/\n/);
if ($fromy == $toy) {
$fromx = $tox + 1 + ($globs - $endoflast);
}
else {
$str =~ m/([^\n]+)$/s;
$fromx = length ($1);
}
$str = substr($pristine, $globs, $globe - $globs);
$toy = $fromy + ($str =~ tr/\n/\n/);
if ($fromy == $toy) {
$tox = $fromx + ($globe - $globs) - 1;
}
else {
$str =~ m/([^\n]+)$/s;
$tox = length ($1) - 1 ;
}
$endoflast = $globe;
$fromx--;
my $toans = $tox - 1; # keep tox for next err
# now setup context; search in buffered which has had
# entities stripped. Means we can't just insert <match> in it.
$buffered =~ m!$matchregex!g;
my $offset = $-[1] - 1;
my $errortext = $1;
my $errlen = length($errortext);
$thiserror =~ s!^<E (msg="(.+)")>$!<error fromy="$fromy" fromx="$fromx" toy="$toy" tox="$toans" ruleId="Lingua::@TEANGA@::Gramadoir/$2" $1 context="$plain" contextoffset="$offset" errorlength="$errlen"/>!;
$thiserror = decode("@NATIVE@", $thiserror);
$thiserror =~ s! msg="([^"]+)"!" msg=\"".$self->localize_me($1)."\""!e;
push @$errors, $thiserror;
}
}
} # loop over sentences
return $errors;
}
# functionally same as aonchiall; separate for profiling
sub aonchiall_deux
{