lib/AI/MicroStructure/Categorizer.pm untested

filter: Statementstmt 0.0% 0 / 171 Branchbran 0.0% 0 / 24 Conditioncond 0.0% 0 / 13 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 23 Podpod 0.0% 0 / 11 totaltotal 0.0% 0 / 242 CC 13 SCAR 21.6
CC
13
Cov
0%
getTestDocs
30.0
getBookList
12.0
analyseBookNames
12.0
CRAP 8.6
1 #!/usr/bin/perl -W
2  
3 package AI::MicroStructure::Categorizer;
4 use strict;
5 use warnings;
6 use Digest::MD5 qw(md5 md5_hex md5_base64);
7 use File::Spec;
8 use Data::Dumper;
9  
10 #use BerkeleyDB;
11 use AI::MicroStructure::util;
12 use Cache::Memcached::Fast;
13 require AI::Categorizer;
14 require AI::Categorizer::Learner::NaiveBayes;
15 require AI::Categorizer::Document;
16 require AI::Categorizer::KnowledgeSet;
17 require Lingua::StopWords;
18  
19 my $state = AI::MicroStructure::util::load_config(); my @CWD=$state->{cwd}; my $config=$state->{cfg};
20 $config->{memcached} ||= "localhost:11211";
21  
22 sub new {
23 my $this = shift;
24 my $class = ref($this) || $this;
25 my $self = {};
26 bless $self, $class;
27 $self->initialize(@_);
28 return $self;
29 }
30  
31 sub initialize {
32 my $self = shift;
33 %$self=@_;
34  
35 $self->{cache} = new Cache::Memcached::Fast({
36 servers => [ { address => $config->{memcached},
37 weight => 2.5 }],
38 namespace => 'my:',
39 connect_timeout => 0.2,
40 io_timeout => 0.5,
41 close_on_error => 1,
42 compress_threshold => 100_000,
43 compress_ratio => 0.9,
44 compress_methods =>
45 [ \&IO::Compress::Gzip::gzip,
46 \&IO::Uncompress::Gunzip::gunzip ],
47 max_failures => 3,
48 failure_timeout => 2,
49 ketama_points => 150,
50 nowait => 1,
51 hash_namespace => 1,
52 serialize_methods => [ \&Storable::freeze,
53 \&Storable::thaw ],
54 utf8 => ($^V ge v5.8.1 ? 1 : 0),
55 max_size => 4*512 * 1024,
56 });
57  
58  
59  
60 }
61  
62  
63 sub trim
64 {
65 my $self = shift;
66 my $string = shift;
67 $string = "" unless $string;
68 $string =~ s/^\s+//;
69 $string =~ s/\s+$//;
70 $string =~ s/\t//;
71 $string =~ s/^\s//;
72 return $string;
73 }
74  
75  
76 sub catfile{
77 my $self = shift;
78 my $path = sprintf("%s/%s",$self->{bookpath},
79 shift);
80 # print $path;
81 my $cat = {};
82 my @cat = map{
83 my @x = split(":",$_);
84 $_ = $self->trim($x[1]);
85 }split("\n",lc
86 `microdict $path | data-freq --limit 500`);
87  
88 $cat->{subject} = [@cat[0..10]];
89 $cat->{body} = [@cat];
90  
91 return $cat;
92  
93 }
94  
95 sub getBookList{
96  
97 my $self = shift;
98 my $dir = shift;
99  
100 $dir = $self->{bookpath} unless defined($dir);
101 die "$dir is not a directory" unless -d $dir;
102 opendir(DIR, $dir) or die $!;
103  
104 my @mp3s = grep { $_ = sprintf("%s",$_); }
105 sort grep /^[\x20-\x7E]+$/,
106 readdir(DIR);
107  
108 closedir DIR;
109  
110 return @mp3s;
111 }
112  
113 sub analyseBookNames{
114  
115 my $self = shift;
116 my $returns = {};
117 my @books = $self->getBookList();
118 my @data = ();
119 my $content = {};
120 my $name = "";
121 my $namehex = "";
122  
123 foreach(@books) {
124 $content = {};
125 $namehex = md5_hex($_);
126  
127 next if($_ eq "." || $_ eq "..");
128  
129 $content = $self->{cache}->get($namehex);
130 $name = sprintf("%s/%s",$self->{bookpath},$_);
131  
132 if(defined($content->{body})){
133  
134 $returns->{$namehex} =
135 {subject => $content->{subject},
136 body => $content->{body},
137 name => $name,
138 md5hex => $namehex};
139  
140 }else{
141  
142 $content = $self->catfile($_);
143  
144 $returns->{$namehex} =
145 {subject=>$content->{subject},
146 body=>$content->{body},
147 name=>$name,
148 md5hex=>$namehex};
149  
150 $self->{cache}->set($namehex,$content);
151  
152 }
153  
154 }
155  
156  
157 return $returns;
158  
159 }
160  
161  
162  
163 sub getFeatures {
164  
165 my $self = shift;
166  
167 my %features =
168 (content_weights => {subject =>2,
169 body => 1},
170 stopwords => Lingua::StopWords::getStopWords('en'),
171 stemming => 'porter');
172  
173  
174 return %features;
175 }
176  
177  
178 sub getTestDocs {
179  
180 my $self = shift;
181 my $amount = shift;
182 $amount = 5 unless($amount);
183  
184 my $test_set = { };
185  
186 my @theme = split("\n",`perl -MAI::MicroStructure -le 'print for AI::MicroStructure->structures;'`);
187 my $add = lc `micro`;
188 foreach(@theme){
189  
190 next if($_ =~ /any|new/);
191  
192 my $name = lc $_;
193 my $sub = "";
194 my $body = "";
195  
196 foreach my $i (0..($amount/2)) {
197 $add = lc `micro $name` ;
198 $sub .= " $add" unless($sub =~ m/$add/);
199 }
200  
201  
202  
203 foreach my $i (0..$amount) {
204 $add = lc `micro $name` ;
205 $body .= " $add" unless($body =~ m/$add/);
206 }
207  
208 $body .= " $name" ;
209 $sub .= " $name" ;
210 $body=~ s/\n/ /g;
211 $sub=~ s/\n/ /g;
212 # $name=~ s/_/ /g;
213 # $sub=~ s/_/ /g;
214 # $body=~ s/_/ /g;
215 $test_set->{$name} = {content =>{
216 subject => $self->trim($sub),
217 body => $self->trim($body)}};
218  
219  
220 }
221  
222 print Dumper $test_set;
223 return $test_set;
224 }
225  
226  
227 sub training_books {
228  
229 my $self = shift;
230 my $i = 0;
231 my $booklist = $self->analyseBookNames();
232 my $chaps = {};
233 my @keys = keys %$booklist;
234 my @subject = ();
235 my @body = ();
236  
237 foreach(@keys) {
238  
239 @subject = @{$booklist->{$keys[$i]}->{subject}};
240 @body = @{$booklist->{$keys[$i]}->{body}};
241  
242 if(@subject && @body){
243 $self->{booknames}->{$i}=$booklist->{$keys[$i]}->{name};
244  
245 $chaps->{$i} = {subject=>join(" ",@subject),
246 body=>join(" ",@body)};
247 $i++;
248 }
249 }
250  
251 return $chaps;
252  
253 }
254  
255 sub perform_standard_tests {
256  
257 my $self = shift;
258  
259 my %features = $self->getFeatures();
260 my $chaps = $self->training_books();
261 my $test_set = $self->getTestDocs();
262  
263  
264 my $docs;
265 foreach my $cat(keys %$chaps) {
266 $docs->{$cat} = {categories => [$cat],
267 content => {subject => $chaps->{$cat}->{subject},
268 body => $chaps->{$cat}->{body},
269 },
270 };
271 }
272 my $c = AI::Categorizer->new(knowledge_set =>
273 AI::Categorizer::KnowledgeSet->new( name => 'CSL'),
274 verbose => 0,
275 );
276  
277 while (my ($name, $data) = each %$docs) {
278 $c->knowledge_set->make_document(name => $name, %$data, %features);
279 }
280  
281 my $learner = $c->learner;
282 $learner->train;
283  
284 $learner->save_state('state');
285 $learner = $learner->restore_state('state');
286  
287 my $threshold = 0.9;
288 while (my ($name, $data) = each %$test_set) {
289  
290 my $doc = AI::Categorizer::Document->new
291 (name => $name,
292 content => $data->{content},
293 %features);
294  
295 my $r = $learner->categorize($doc);
296 $r->threshold($threshold);
297 my $b = $r->best_category;
298 next unless $r->in_category($b);
299 printf("\n\n[%s %s %s]\nis in category %d, with score %.3f\n%s\n%s\n",
300 $name,
301 $data->{content}->{subject},
302 $data->{content}->{body},
303 $b,
304 $r->scores($b),
305 $self->{booknames}->{$b},
306 sprintf lc `microdict $self->{booknames}->{$b} | data-freq --limit 15`);
307  
308 }
309  
310  
311 }
312  
313 END{
314 my $self = shift;
315 # untie %{$self->{microtree}};
316  
317 }
318  
319 1;
320  
321 =head1 NAME
322  
323 AI::MicroStructure::Categorizer;
324  
325 =head1 DESCRIPTION
326  
327 old obsolete Categorizer
328  
329 =head1 SYNOPSIS
330  
331 ~$ micro new world
332  
333 ~$ micro structures
334  
335 ~$ micro any 2
336  
337 ~$ micro drop world
338  
339 ~$ micro
340  
341 =head1 AUTHOR
342  
343 Hagen Geissler <santex@cpan.org>
344  
345 =head1 COPYRIGHT AND LICENCE
346  
347 Hagen Geissler <santex@cpan.org>
348  
349 =head1 SUPPORT AND DOCUMENTATION
350  
351 [sample using concepts](http://quantup.com)
352  
353 [PDF info on my works](https://github.com/santex)
354  
355  
356 =head1 SEE ALSO
357  
358 AI-MicroStructure
359  
360 =cut
361  
362  
363 __DATA__
364  
365  
366 new Cache::Memcached::Fast({
367 servers => [ { address => 'localhost:11211',
368 weight => 2.5 }],
369 namespace => 'my:',
370 connect_timeout => 0.2,
371 io_timeout => 0.5,
372 close_on_error => 1,
373 compress_threshold => 100_000,
374 compress_ratio => 0.9,
375 compress_methods =>
376 [ \&IO::Compress::Gzip::gzip,
377 \&IO::Uncompress::Gunzip::gunzip ],
378 max_failures => 3,
379 failure_timeout => 2,
380 ketama_points => 150,
381 nowait => 1,
382 hash_namespace => 1,
383 serialize_methods => [ \&Storable::freeze,
384 \&Storable::thaw ],
385 utf8 => ($^V ge v5.8.1 ? 1 : 0),
386 max_size => 4*512 * 1024,
387 });
388