blib/lib/Alvis/Wikipedia/XMLDump.pm untested

filter: Statementstmt 0.0% 0 / 316 Branchbran 0.0% 0 / 112 Conditioncond 0.0% 0 / 9 MC/DCmcdc 0.0% 0 / 6 Subroutinesub 0.0% 0 / 25 Podpod 0.0% 0 / 14 totaltotal 0.0% 0 / 482 CC 57 SCAR 56.1
CC
57
Cov
0%
extract_records
756.0
_return_alvis_record
90.0
_pass_over_records
56.0
CRAP 272.8
1 package Alvis::Wikipedia::XMLDump;
2  
3 use warnings;
4 use strict;
5  
6 $Alvis::Wikipedia::XMLDump::VERSION = '0.1';
7  
8 use Storable;
9 use Parse::MediaWikiDump;
10 use Digest::MD5;
11 use Encode;
12 use Data::Dumper;
13  
14 use Alvis::Wikipedia::WikitextParser;
15 use Alvis::Wikipedia::Variables;
16 use Alvis::Wikipedia::CatGraph;
17 use Alvis::Canonical;
18  
19 ########################################################################
20 #
21 # Exported constants
22 #
23 #######################################################################
24  
25 # Record output formats
26 our ($OUTPUT_HTML,
27 $OUTPUT_ALVIS
28 )=(0..1);
29  
30 ############################################################################
31 #
32 # Error message stuff
33 #
34 ############################################################################
35  
36 my ($ERR_OK,
37 $ERR_VAR,
38 $ERR_PARSER,
39 $ERR_FIRST_PASS,
40 $ERR_SECOND_PASS,
41 $ERR_TEMPL_ADD,
42 $ERR_EXPAND,
43 $ERR_DUMP,
44 $ERR_TABLE_PARSE,
45 $ERR_REC_CB,
46 $ERR_HTML,
47 $ERR_CAN_DOC_CONV,
48 $ERR_ALVIS,
49 $ERR_BUILD_CAT_GRAPH,
50 $ERR_CATEGORIES,
51 $ERR_XML_PARSER,
52 $ERR_CAN_DOC_CONVERSION,
53 $ERR_ID,
54 $ERR_TITLE,
55 $ERR_CAT_PAGE_LINKS_ADD,
56 $ERR_CAT_GRAPH,
57 $ERR_LOAD_TEMPLATES,
58 $ERR_CAT_GRAPH_DUMP,
59 $ERR_UNK_OUTPUT_FORMAT
60 )=(0..23);
61 my %ErrMsgs=($ERR_OK=>"",
62 $ERR_VAR=>"Unable to instantiate Alvis::Wikipedia::Variables.",
63 $ERR_PARSER=>
64 "Unable to instantiate Alvis::Wikipedia::WikitextParser.",
65 $ERR_FIRST_PASS=>"The first pass over the records failed.",
66 $ERR_SECOND_PASS=>"The main pass over the records failed.",
67 $ERR_TEMPL_ADD=>"Adding the definition of a template failed.",
68 $ERR_EXPAND=>"Variable and template expansion failed.",
69 $ERR_DUMP=>"Opening the SQL dump file failed.",
70 $ERR_TABLE_PARSE=>"Parsing a subtable failed.",
71 $ERR_REC_CB=>"Record handling callback failed.",
72 $ERR_HTML=>"Wikitext -> HTML failed.",
73 $ERR_CAN_DOC_CONV=>
74 "Creating a new instance of Alvis::Canonical failed.",
75 $ERR_ALVIS=>"Converting to Alvis failed",
76 $ERR_BUILD_CAT_GRAPH=>"Adding to the category graph failed.",
77 $ERR_CATEGORIES=>"Determining the categories of an article " .
78 "failed.",
79 $ERR_XML_PARSER=>"Unable to instantiate Parse::MediaWikiDump",
80 $ERR_CAN_DOC_CONVERSION=>"Converting the text from HTML to " .
81 "canonicalDocument format failed",
82 $ERR_ID=>"Calculating the id failed.",
83 $ERR_TITLE=>"Malformed title",
84 $ERR_CAT_PAGE_LINKS_ADD=>"Adding the links of a category page " .
85 "to the graph failed",
86 $ERR_CAT_GRAPH=>"Instantiating CatGraph failed",
87 $ERR_LOAD_TEMPLATES=>"Loading the templates failed.",
88 $ERR_CAT_GRAPH_DUMP=>"Dumping the category graph failed.",
89 $ERR_UNK_OUTPUT_FORMAT=>"Unrecognized XML dump record output " .
90 "format."
91 );
92  
93 sub _set_err_state
94 {
95 my $self=shift;
96 my $errcode=shift;
97 my $errmsg=shift;
98  
99  
100 if (!defined($errcode))
101 {
102 confess("set_err_state() called with an undefined argument.");
103 }
104  
105 if (exists($ErrMsgs{$errcode}))
106 {
107 if ($errcode==$ERR_OK)
108 {
109 $self->{errstr}="";
110 }
111 else
112 {
113 $self->{errstr}.=" " . $ErrMsgs{$errcode};
114 if (defined($errmsg))
115 {
116 $self->{errstr}.=" " . $errmsg;
117 }
118  
119 }
120 }
121 else
122 {
123 confess("Internal error: set_err_state() called with an " .
124 "unrecognized argument ($errcode).")
125 }
126 }
127  
128 sub clearerr
129 {
130 my $self=shift;
131
132 $self->{errstr}="";
133 }
134  
135 sub errmsg
136 {
137 my $self=shift;
138
139 return $self->{errstr};
140 }
141  
142 ##########################################################################
143 #
144 # Public methods
145 #
146 ##########################################################################
147  
148 sub new
149 {
150 my $proto=shift;
151  
152 my $class=ref($proto)||$proto;
153 my $parent=ref($proto)&&$proto;
154 my $self={};
155 bless($self,$class);
156  
157 $self->_set_err_state($ERR_OK);
158  
159 $self->_init(@_);
160  
161 $self->{variables}=Alvis::Wikipedia::Variables->new();
162 if (!defined($self->{variables}))
163 {
164 $self->_set_err_state($ERR_VAR);
165 return undef;
166 }
167  
168 $self->{parser}=Alvis::Wikipedia::WikitextParser->new();
169 if (!defined($self->{parser}))
170 {
171 $self->_set_err_state($ERR_PARSER);
172 return undef;
173 }
174  
175 $self->{canDocConverter}=Alvis::Canonical->new(convertCharEnts=>1,
176 convertNumEnts=>1,
177 sourceEncoding=>'utf8');
178 if (!defined($self->{canDocConverter}))
179 {
180 $self->_set_err_state($ERR_CAN_DOC_CONV);
181 return undef;
182 }
183  
184 $self->{catGraph}=Alvis::Wikipedia::CatGraph->new();
185 if (!defined($self->{catGraph}))
186 {
187 $self->_set_err_state($ERR_CAT_GRAPH);
188 return undef;
189 }
190  
191 return $self;
192 }
193  
194 sub _init
195 {
196 my $self=shift;
197  
198 $self->{expandTemplates}=0;
199 $self->{outputFormat}=$OUTPUT_HTML;
200 $self->{skipRedirects}=0;
201 $self->{categoryWord}='Category';
202 $self->{templateWord}='Template';
203 $self->{dumpCategoryData}=1;
204 $self->{dumpTemplateData}=1;
205 $self->{catGraphDumpF}='CatGraph.storable';
206 $self->{templateDumpF}='Templates.storable';
207  
208 if (defined(@_))
209 {
210 my %args=@_;
211 @$self{ keys %args }=values(%args);
212 }
213 }
214  
215 #
216 # opts: hash with fields
217 #
218 # namespaces ref to a list of namespace identifiers whose
219 # records to extract
220 # expandTemplates flag for true template expansion
221 # templateDumpF template dump file
222 # outputFormat format for result records ($OUTPUT_HTML,
223 # $OUTPUT_ALVIS),...
224 # categoryWord category namespace identifier (changes with
225 # language)
226 # templateWord template namespace identifier (changes with
227 # language)
228 # rootCategory root category identifier (changes with
229 # language)
230 # date the date of the dump
231 # dumpCatGraph flag for dumping the category graph
232 # catGraphDumpF category graph dump file
233 #
234 sub extract_records
235 {
236 my $self=shift;
237 my $fd=shift; # dump fd ref
238 my $cb=shift; # [\&foo,$arg1,$arg2], callback for each [record title,text]
239 my $opts=shift;
240 my $prog_cb=shift; # [\&foo,$arg1,$arg2], optional callback for progress
241 # ('N records processed')
242  
243 if (!defined($cb))
244 {
245 $self->_set_err_state($ERR_XML_PARSER);
246 return 0;
247 }
248  
249 my $prog_txt="";
250  
251 my $expand_templates;
252 if (exists($self->{expandTemplates}))
253 {
254 $expand_templates=$self->{expandTemplates};
255 }
256 if (exists($opts->{expandTemplates}))
257 {
258 $expand_templates=$opts->{expandTemplates};
259 }
260  
261 my %namespaces;
262  
263 if ($expand_templates)
264 {
265 if ($opts->{templateDumpF})
266 {
267 if (defined($prog_cb))
268 {
269 my @prog_cb=@$prog_cb;
270 &{$prog_cb[0]}(@prog_cb[1..$#prog_cb],"Loading the templates");
271 }
272 if (!$self->{variables}->load_templates($opts->{templateDumpF}))
273 {
274 $self->_set_err_state($ERR_LOAD_TEMPLATES);
275 return 0;
276 }
277 }
278 else # Have to do a pass first to collect the templates
279 {
280 $self->{XMLParser}=Parse::MediaWikiDump::Pages->new($fd);
281 if (!defined($self->{XMLParser}))
282 {
283 $self->_set_err_state($ERR_XML_PARSER);
284 return 0;
285 }
286
287 my $template_word;
288 if (exists($self->{templateWord}))
289 {
290 $template_word=$self->{templateWord};
291 }
292 if (exists($opts->{templateWord}))
293 {
294 $template_word=$opts->{templateWord};
295 }
296  
297 $prog_txt="Collecting templates";
298 %namespaces=($template_word=>1);
299 if (!$self->_pass_over_records(\%namespaces,
300 [\&_collect_templates,$self],
301 [$prog_cb,$prog_txt]))
302 {
303 $self->_set_err_state($ERR_FIRST_PASS);
304 return 0;
305 }
306
307 if ($self->{dumpTemplateData})
308 {
309 $self->{variables}->dump_templates($opts->{templateDumpF});
310 }
311 }
312 }
313  
314 $prog_txt="Expanding variables and converting";
315 #
316 # Just in case we did a first pass, destroy old instance
317 #
318 undef $self->{XMLParser};
319 $self->{XMLParser}=Parse::MediaWikiDump::Pages->new($fd);
320 if (!defined($self->{XMLParser}))
321 {
322 $self->_set_err_state($ERR_XML_PARSER);
323 return 0;
324 }
325  
326 my $category_word;
327 if (exists($self->{categoryWord}))
328 {
329 $category_word=$self->{categoryWord};
330 }
331 if (exists($opts->{categoryWord}))
332 {
333 $category_word=$opts->{categoryWord};
334 }
335  
336 my $date;
337 if ($opts->{date})
338 {
339 $date=$opts->{date};
340 }
341 else # pick the current date
342 {
343 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=
344 localtime();
345 $date=sprintf("%04d%02d%02d",1900+$year,1+$mon,$mday);
346 }
347  
348 my $output_format;
349 if (exists($self->{outputFormat}))
350 {
351 $output_format=$self->{outputFormat};
352 }
353 if (exists($opts->{outputFormat}))
354 {
355 $output_format=$opts->{outputFormat};
356 }
357  
358 # Pick articles and category pages
359 %namespaces=(''=>1,$category_word=>1);
360 #
361 # Add any other wanted namespaces
362 #
363 if ($opts->{namespaces})
364 {
365 for my $ns ($opts->{namespaces})
366 {
367 $namespaces{$ns}=1;
368 }
369 }
370 my $p_cb=[@$prog_cb,$prog_txt];
371 if (!$self->_pass_over_records(\%namespaces,
372 [\&_return_alvis_record,
373 $self,$cb,$date,$category_word,
374 $expand_templates,$output_format],
375 $p_cb))
376 {
377 $self->_set_err_state($ERR_SECOND_PASS);
378 return 0;
379 }
380  
381 my $dump_cat_graph;
382 if (exists($self->{dumpCatGraph}))
383 {
384 $dump_cat_graph=$self->{dumpCatGraph};
385 }
386 if (exists($opts->{dumpCatGraph}))
387 {
388 $dump_cat_graph=$opts->{dumpCatGraph};
389 }
390  
391 if ($dump_cat_graph)
392 {
393 my $cat_graph_f;
394 if (exists($self->{catGraphDumpF}))
395 {
396 $cat_graph_f=$self->{catGraphDumpF};
397 }
398 if (exists($opts->{catGraphDumpF}))
399 {
400 $cat_graph_f=$opts->{catGraphDumpF};
401 }
402 if (!$self->{catGraph}->dump_graph($cat_graph_f))
403 {
404 $self->_set_err_state($ERR_CAT_GRAPH_DUMP);
405 return 0;
406 }
407 }
408  
409 return 1;
410 }
411  
412 #########################################################################
413 #
414 # Private methods
415 #
416 #########################################################################
417  
418 sub _collect_templates
419 {
420 my $self=shift;
421 my $namespace=shift;
422 my $title=shift;
423 my $text=shift;
424  
425 if ($namespace eq $self->{templateWord})
426 {
427 if (!$self->{variables}->add_template($title,$text))
428 {
429 $self->_set_err_state($ERR_TEMPL_ADD);
430 return 0;
431 }
432 }
433  
434 return 1;
435 }
436  
437 sub _return_alvis_record
438 {
439 my $self=shift;
440 my $cb=shift;
441 my $mod_date=shift;
442 my $category_word=shift;
443 my $expand_templates=shift;
444 my $output_format=shift;
445 my $namespace=shift;
446 my $title=shift;
447 my $text=shift;
448 my $is_redir=shift;
449  
450 my $orig_text=$text;
451 my $expansion;
452
453 $text=~s/<!--.*?-->//sgo;
454
455 $title=$self->{parser}->normalize_title($title);
456 if (!defined($title))
457 {
458 $self->_set_err_state($ERR_TITLE,"title: \"$title\"");
459 return 0;
460 }
461
462 $expansion=$self->{variables}->expand($namespace,$title,$text,
463 $expand_templates);
464 if (!defined($expansion))
465 {
466 $self->_set_err_state($ERR_EXPAND);
467 return 0;
468 }
469 $text=$expansion;
470
471 if ($namespace ne '')
472 {
473 $title="$namespace/$title";
474 }
475
476 if ($namespace eq $category_word && $self->{dumpCategoryData})
477 {
478 if (!$self->_add_cat_page_links_to_graph($title,$text))
479 {
480 $self->_set_err_state($ERR_CAT_PAGE_LINKS_ADD,
481 "title: \"$title\"");
482 return 0;
483 }
484 }
485
486 my @cb;
487
488 if ($output_format eq $OUTPUT_HTML)
489 {
490 my $html=$self->{parser}->to_HTML($text);
491 if (!defined($html))
492 {
493 $self->_set_err_state($ERR_HTML);
494 return 0;
495 }
496 $html="<HTML>\n<BODY>\n" . $html . "</BODY>\n</HTML>\n";
497
498 @cb=@$cb;
499 &{$cb[0]}(@cb[1..$#cb],$title,$mod_date,$output_format,$html,
500 $is_redir,$namespace);
501 }
502 elsif ($output_format eq $OUTPUT_ALVIS)
503 {
504 ; # Skip HTML and convert directly to Alvis XML to save time
505 die("NOT IMPLEMENTED YET!");
506 my $alvis_XML;
507
508 @cb=@$cb;
509 &{$cb[0]}(@cb[1..$#cb],$title,$mod_date,$output_format,
510 $alvis_XML,$is_redir,$namespace);
511 }
512 else
513 {
514 $self->_set_err_state($ERR_UNK_OUTPUT_FORMAT,
515 "format: \"$output_format\"");
516 return 0;
517 }
518  
519 return 1;
520 }
521  
522 sub _add_cat_page_to_graph
523 {
524 my $self=shift;
525 my $namespace=shift;
526 my $title=shift;
527 my $text=shift;
528 my $is_redir=shift;
529  
530 my $orig_text=$text;
531 my $expansion;
532
533 $text=~s/<!--.*?-->//sgo;
534
535 $title=$self->{parser}->normalize_title($title);
536 if (!defined($title))
537 {
538 $self->_set_err_state($ERR_TITLE,"title: \"$title\"");
539 return 0;
540 }
541
542 $expansion=$self->{variables}->expand($namespace,$title,$text);
543 if (!defined($expansion))
544 {
545 $self->_set_err_state($ERR_EXPAND);
546 return 0;
547 }
548 $text=$expansion;
549  
550 if (!$self->_add_cat_page_links_to_graph($title,$text))
551 {
552 $self->_set_err_state($ERR_CAT_PAGE_LINKS_ADD,
553 "title: \"$title\"");
554 return 0;
555 }
556  
557 return 1;
558 }
559  
560 sub _add_cat_page_links_to_graph
561 {
562 my $self=shift;
563 my $title=shift; # already normalized
564 my $text=shift;
565  
566 my $cat=$title;
567  
568 $text=~s/\[\[(?:(?i)$self->{categoryWord}):(.*?)\]\]/$self->_add_cat_link($cat,$1)/sgoe;
569  
570 return 1;
571 }
572  
573 sub _add_cat_link
574 {
575 my $self=shift;
576 my $cat=shift;
577 my $parent_spec=shift;
578  
579 my @parts=split(/\|/,$parent_spec);
580  
581 my $parent=$self->{parser}->normalize_title($parts[0]);
582 if (!defined($parent))
583 {
584 $self->_set_err_state($ERR_TITLE,
585 "category parent title: \"$parts[0]\"");
586 return 0;
587 }
588  
589 $self->{catGraph}->add_link($cat,$parent);
590 }
591  
592 sub _pass_over_records
593 {
594 my $self=shift;
595 my $target_namespaces=shift;
596 my $cb=shift;
597 my $prog_cb=shift;
598  
599  
600 $self->{'N'}=0;
601 $self->{'n'}=0;
602  
603 while (defined(my $page=$self->{XMLParser}->page()))
604 {
605 my $namespace;
606 my $title=$page->title();
607 if ($title=~/^(.*?):(.*)$/)
608 {
609 $namespace=$1;
610 $title=$2;
611 }
612 else
613 {
614 $namespace='';
615 }
616  
617 if (exists($target_namespaces->{$namespace}))
618 {
619 my $is_redirect=0;
620  
621 if (defined($page->redirect()))
622 {
623 if ($self->{skipRedirects})
624 {
625 next;
626 }
627 else
628 {
629 $is_redirect=1;
630 }
631 }
632
633 my $text=${$page->text()};
634 $text=$self->_dequote_txt($text);
635  
636 my @cb=@$cb;
637 if (!&{$cb[0]}(@cb[1..$#cb],$namespace,$title,$text,$is_redirect))
638 {
639 $self->_set_err_state($ERR_REC_CB,
640 "Title:\"$title\".");
641 warn "Handling \"$title\" failed: " .
642 $self->errmsg();
643 }
644 else
645 {
646 $self->{'n'}++;
647 }
648 }
649
650 my @prog_cb=@$prog_cb;
651 &{$prog_cb[0]}(@prog_cb[1..$#prog_cb],++$self->{'N'},$self->{'n'}) if
652 defined($prog_cb);
653 }
654  
655 return 1;
656 }
657  
658 sub _dequote_txt
659 {
660 my $self=shift;
661 my $text=shift;
662
663 $text=~s/\\\'/\'/isgo;
664 $text=~s/\\\"/\"/isgo;
665 $text=~s/\\n/\n/isgo;
666  
667 return $text;
668 }
669  
670 sub txt2XMLsafe
671 {
672 my $self=shift;
673 my $text=shift;
674  
675 if (!defined($text))
676 {
677 return "";
678 }
679  
680 $text=~s/\&/\&amp;/go;
681 $text=~s/</\&lt;/go;
682 $text=~s/>/\&gt;/go;
683  
684 return $text;
685 }
686  
687  
688 1;