Source

Blacklist Classifier / perllib / Lingua-Identify-Blacklists / lib / Lingua / Identify / Blacklists-old.pm

  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
#!env perl

use strict;
use vars qw($opt_a $opt_b $opt_c $opt_m $opt_n $opt_d $opt_v $opt_i $opt_r
            $opt_t $opt_e $opt_F $opt_T $opt_L $opt_U $opt_S $opt_A $opt_M);
use Getopt::Std;



getopts('a:b:c:d:im:nvt:e:F:T:L:USAM:');

binmode(STDIN,":encoding(UTF-8)");
binmode(STDOUT,":encoding(UTF-8)");
binmode(STDERR,":encoding(UTF-8)");

our $BlackListDir = $opt_d || &dist_dir('Lingua::Identify::Blacklists') . '/blacklists';


my %blacklists=();

my $min_high = defined $opt_a ? $opt_a : 10;
my $max_low  = defined $opt_b ? $opt_b : 3;
my $min_diff = defined $opt_c ? $opt_c : 0.8;

my $use_margin = $opt_M;


# run experiments with a given set of training corpora and 
# a set of evaluation corpora

if ($opt_e){
    my @langs = @ARGV;
    # run an experiment with exponentially increasing training sizes
    # from $opt_F to $opt_T
    if ($opt_F && $opt_T && $opt_L){
        $opt_m = $opt_F;
        while ($opt_m < $opt_T){
            %blacklists=();
            print "train with ca $opt_m tokens\n";
            &run_experiment($opt_t,$opt_e,@langs);
            $opt_m *= $opt_L;
        }
    }
    &run_experiment($opt_t,$opt_e,@langs);
    exit;
}


# train new black lists

if ($opt_t){
    my @traindata = split(/\s+/,$opt_t);
    my @langs = @ARGV;
    &batch_train(\@langs,\@traindata);
}
elsif ($opt_n){
    my $file1=shift(@ARGV);
    my $file2=shift(@ARGV);
    &train($file1,$file2);
}


# run classify

if ($opt_r){
    my @langs = @ARGV;
    @ARGV = ();

    my @predictions = &identify_file( undef, langs => \@langs );
    print join( "\n", @predictions );
    print "\n";
}



package Lingua::Identify::CLD;

use 5.008;
use strict;
use warnings;

use File::ShareDir 'dist_dir';

=encoding UTF-8

=head1 NAME

Lingua::Identify::Blacklists - Language identification for related languages based on blacklists

=head1 VERSION

Version 0.01

=cut

our $VERSION = '0.01';

# USAGE:
#-----------------------------------------------------------------------------
# classification:
#   blacklist_classifier.pl [OPTIONS] -r lang1 lang2 ... < file
#
# training:
#   blacklist_classifier.pl -n [OPTIONS] text1 text2 > blacklist.txt
#   blacklist_classifier.pl [OPTIONS] -t "t1.txt t2.txt ..." lang1 lang2 ...
#
# run experiments:
#   blacklist_classifier.pl -t "t1.txt t2.txt ..." \
#                           -e "e1.txt e2.txt ..." \
#                           lang1 lang2 ...
#
#-----------------------------------------------------------------------------
#
# - lang1 lang2 ... are language ID's
# - blacklists are expected in <BlackListDir>/<lang1-lang2.txt
# - t1.txt t2.txt ... are training data files (in UTF-8)
# - e1.txt e2.txt ... are training data files (in UTF-8)
# - the order of languages needs to be the same for training data, eval data
#   as given by the command line arguments (lang1 lang2 ..)
#
#-----------------------------------------------------------------------------
#
# OPTIONS:
#
# -a <freq> ...... min freq for common words
# -b <freq> ...... max freq for uncommon words
# -c <score> ..... min difference score to be relevant
# -d <dir> ....... directory of black lists
# -i ............. classify each line separately
# -m <number> .... use approximately <number> tokens to traing/classify
# -n ............. train a new black list
# -v ............. verbose mode
#
# -U ............. don't lowercase
# -S ............. don't tokenize (use the string as it is)
# -A ............. don't discard tokens with non-alphabetic characters



sub identify{
  my $text = shift;
  my %options = @_;

  my %dic = ();
  my $total = 0;

  &process_string( $text, \%dic, $total );
  return &classify( \%dic, %options );
}



sub identify_file{
    my $file = shift;
    my %options = @_;
    
    my %dic = ();
    my $total = 0;
    my @predictions = ();
    
    my $fh = *STDIN;
    if (defined $file){
	open $fh,"<$file" || die "cannot read from '$file'\n";
	binmode(F,":encoding(UTF-8)");
    }
    
    while (<$fh>){
	chomp;
	&process_string($_,\%dic,$total);
	if ($options{every_line}){                        # classify every line separately
            push( @predictions, &classify( \%dic, %options ) );
            %dic=();
	}
	elsif ($options{text_size}){                     # use only approx $opt_m words
	    if ($total > $options{text_size}){
		print STDERR "use $total tokens for classification\n" if ($options{verbose});
		last;
	    }
	}
    }
    unless ($options{every_line}){
	push( @predictions, &classify( \%dic, %options ) );
    }
    return @predictions;
}












sub classify{
    my $dic = shift;
    my %options = @_;

    my @langs = ref($options{langs}) eq 'ARRAY' ? 
	@{$options{langs}} : split( /\s+/, $options{langs} ) ;

    return &classify_with_margin(@_) if ($options{use_margin});
    return &classify_cascaded(@_);
}


sub classify_cascaded{
    my $dic = shift;
    my @langs = @_;

    my $lang1 = shift(@langs);
    foreach my $lang2 (@langs){

        # load blacklists on demand
        unless (exists $blacklists{"$lang1-$lang2"}){
            $blacklists{"$lang1-$lang2"}={};
            &load_blacklist($blacklists{"$lang1-$lang2"},
                            $BlackListDir,$lang1,$lang2);
        }
        my $list = $blacklists{"$lang1-$lang2"};

        my $score = 0;
	foreach my $w (keys %{$dic}){
	    if (exists $$list{$w}){
                $score += $$dic{$w} * $$list{$w};
                print STDERR "$$dic{$w} x $w found ($$list{$w})\n" if ($opt_v);
            }
        }
        if ($score < 0){
            $lang1 = $lang2;
        }
        print STDERR "select $lang1 ($score)\n" if ($opt_v);
    }
    return $lang1;
}


# OTHER WAY OF CLASSIFYING
# test all against all ...

sub classify_with_margin{
    my $dic = shift;
    my @langs = @_;

    my %selected = ();
    while (@langs){
        my $lang1 = shift(@langs);
        foreach my $lang2 (@langs){

            # load blacklists on demand
            unless (exists $blacklists{"$lang1-$lang2"}){
                $blacklists{"$lang1-$lang2"}={};
                &load_blacklist($blacklists{"$lang1-$lang2"},
                                $BlackListDir,$lang1,$lang2);
            }
            my $list = $blacklists{"$lang1-$lang2"};

            my $score = 0;
            foreach my $w (keys %{$dic}){
                if (exists $$list{$w}){
                    $score += $$dic{$w} * $$list{$w};
                    print STDERR "$$dic{$w} x $w found ($$list{$w})\n" 
                        if ($opt_v);
                }
            }
            next if (abs($score) < $opt_M);
            if ($score < 0){
                # $selected{$lang2}-=$score;
                $selected{$lang2}++;
                print STDERR "select $lang2 ($score)\n" if ($opt_v);
            }
            else{
                # $selected{$lang1}+=$score;
                $selected{$lang1}++;
                print STDERR "select $lang1 ($score)\n" if ($opt_v);
            }
        }
    }
    my ($best) = sort { $selected{$b} <=> $selected{$a} } keys %selected;
    return $best;
}




sub load_blacklist{
    my ($list,$dir,$lang1,$lang2) = @_;

    my $inverse = 0;
    if (! -e "$dir/$lang1-$lang2.txt"){
	($lang1,$lang2) = ($lang2,$lang1);
        $inverse = 1;
    }

    open F,"<:encoding(UTF-8)","$dir/$lang1-$lang2.txt" || die "...";
    while (<F>){
	chomp;
	my ($score,$word) = split(/\t/);
        $$list{$word} = $inverse ? 0-$score : $score;
    }
    close F;
}




sub read_file{
    my ($file,$dic)=@_;
    my $total = 0;
    if ($file=~/\.gz$/){
	open F,"gzip -cd < $file |" || die "...";
	binmode(F,":encoding(UTF-8)");
    }
    else{
	open F,"<:encoding(UTF-8)",$file || die "...";
    }
    while (<F>){
	chomp;
        &process_string($_,$dic,$total);
        if ($opt_m){
            if ($total > $opt_m){
                print STDERR "read $total tokens from $file\n";
                last;
            }
        }
    }
    close F;
    return $total;
}


# process_string($string,\%dic,\$wordcount)

sub process_string{
    $_[0]=lc($_[0]) unless ($opt_U);
    $_[0]=~s/([\A\s]\P{IsAlpha}+|\P{IsAlpha}+[\s\Z])/ /gs unless ($opt_S);
    my @words = $opt_A ? 
        split(/\s+/,$_[0]) :
        grep(/^\p{IsAlpha}/,split(/\s+/,$_[0]));
    foreach my $w (@words){${$_[1]}{$w}++;$_[2]++;}
}


sub batch_train{
    my $langs = shift;
    my $traindata = shift;

    die "no languages given\n" unless (ref($langs) eq 'ARRAY');
    die "no training data given\n" unless (ref($traindata) eq 'ARRAY');
    die "number of languages and training data does not match\n" 
        unless ($#{$traindata} == $#{$langs});

    for my $s (0..$#{$langs}){
        for my $t ($s+1..$#{$langs}){
            print STDERR "traing blacklist for $$langs[$s]-$$langs[$t]\n";
            &train($$traindata[$s],$$traindata[$t],
                   "$BlackListDir/$$langs[$s]-$$langs[$t].txt");
        }
    }
}


sub train{
    my ($file1,$file2,$outfile) = @_;

    my %dic1=();
    my %dic2=();

    my ($total1,$total2);

    my $total1 = &read_file($file1,\%dic1);
    my $total2 = &read_file($file2,\%dic2);

    if ($outfile){
        system("mkdir -p $BlackListDir") unless (-d $BlackListDir);
        open O,">$outfile" || die "cannot write to $outfile\n";
        binmode(O,":encoding(UTF-8)");
    }

    foreach my $w (keys %dic1){
	next if ($dic1{$w}<$min_high && $dic2{$w}<$min_high);
	next if ($dic1{$w}>$max_low && $dic2{$w}>$max_low);

        my $s1 = $dic1{$w} * $total2;
        my $s2 = $dic2{$w} * $total1;
        my $diff = ($s1 - $s2) / ($s1 + $s2);

	if (abs($diff) > $min_diff){
            if ($outfile){
                print O "$diff\t$w\t$dic1{$w}\t$dic2{$w}\n";
            }
            else{
                print "$diff\t$w\t$dic1{$w}\t$dic2{$w}\n";
            }
	}
    }
    # don't forget words that do NOT appear in dic1!!!
    foreach my $w (keys %dic2){
	next if (exists $dic1{$w});
	next if ($dic2{$w}<10);
        if ($outfile){
            print O "-1\t$w\t$dic1{$w}\t$dic2{$w}\n";
        }
        else{
            print "-1\t$w\t$dic1{$w}\t$dic2{$w}\n";
        }
    }
    close O if ($outfile);
}






sub run_experiment{

    use Benchmark;

    my $trainfiles = shift;
    my $evalfiles = shift;

    my @traindata = split(/\s+/,$trainfiles);
    my @evaldata = split(/\s+/,$evalfiles);
    my @langs = @_;

    die "no languages given!\n" unless (@langs);
    die "no training nor evaluation data given!\n" 
        unless ($#traindata == $#evaldata || $#traindata == $#langs);

    # train blacklists

    if ($#traindata == $#langs){
        $BlackListDir = $opt_d || "blacklist-experiment";
        my $t1 = new Benchmark;
        &batch_train(\@langs,\@traindata);
        print STDERR "training took: ".
            timestr(timediff(new Benchmark, $t1)).".\n";
    }

    # classify test data

    if ($#evaldata == $#langs){
        print STDERR "classify ....\n";

        my $correct=0;
        my $count=0;
        my %guesses=();

        my %correct_lang=();
        my %count_lang=();

        my $t1 = new Benchmark;
        foreach my $i (0..$#langs){
            open IN,"<:encoding(UTF-8)",$evaldata[$i] || die "...";
            while (<IN>){
                chomp;
                my %dic = ();
                &process_string($_,\%dic);
                my $guess = &classify(\%dic,@langs);
                $count++;
                $count_lang{$langs[$i]}++;
                if ($guess eq $langs[$i]){
                    $correct++;
                    $correct_lang{$langs[$i]}++;
                }
                $guesses{$langs[$i]}{$guess}++;
            }
            close IN;
        }
        print STDERR "classification took: ".
            timestr(timediff(new Benchmark, $t1)).".\n";

        printf "accuracy: %6.4f\n   ",$correct/$count;
        foreach my $c (@langs){
            print "  $c";
        }
        print "\n";
        foreach my $c (@langs){
            print "$c ";
            foreach my $g (@langs){
                printf "%4d",$guesses{$c}{$g};
            }
            printf "  %6.4f",$correct_lang{$c}/$count_lang{$c};
            print "\n";
        }
    }
    system("wc -l $BlackListDir/*.txt");
}

1;


__END__


=head1 AUTHOR

Jörg Tiedemann, L<https://bitbucket.org/tiedemann>

=head1 BUGS

Please report any bugs or feature requests to
L<https://bitbucket.org/tiedemann/blacklist-classifier>.  I will be notified,
and then you'll automatically be notified of progress on your bug as I
make changes.

=head1 SUPPORT

You can find documentation for this module with the perldoc command.

    perldoc Lingua::Identify::Blacklists

=head1 LICENSE AND COPYRIGHT

   Copyright 2012 Jörg Tiedemann.

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU Lesser General Public License as published
   by the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
   GNU Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.

=cut