lower case N in the usage instructions
[wikiq] / wikiq.cpp
1 /* 
2  * An XML parser for Wikipedia Data dumps.
3  * Converts XML files to tab-separated values files readable by spreadsheets
4  * and statistical packages.
5  */
6
7 #include <stdio.h>
8 #include <iostream>
9 #include <string.h>
10 #include <ctype.h>
11 #include <stdlib.h>
12 #include "expat.h"
13 #include <getopt.h>
14 #include "disorder.h"
15 #include "md5.h"
16 #include "dtl/dtl.hpp"
17 #include <vector>
18 #include <map>
19 #include <pcrecpp.h>
20
21
22 using namespace std;
23
24 // timestamp of the form 2003-11-07T00:43:23Z
25 #define DATE_LENGTH 10
26 #define TIME_LENGTH 8
27 #define TIMESTAMP_LENGTH 20
28
29 #define MEGABYTE 1048576
30 #define FIELD_BUFFER_SIZE 1024
31
32 // this can be changed at runtime if we encounter an article larger than 10mb
33 size_t text_buffer_size = 10 * MEGABYTE;
34
35 enum elements { 
36     TITLE, ARTICLEID, REVISION, REVID, TIMESTAMP, CONTRIBUTOR, 
37     EDITOR, EDITORID, MINOR, COMMENT, UNUSED, TEXT
38 }; 
39
40 enum block { TITLE_BLOCK, REVISION_BLOCK, CONTRIBUTOR_BLOCK, SKIP };
41
42 enum outtype { FULL, SIMPLE };
43
44 typedef struct {
45
46     // pointers to once-allocated buffers
47     char *title;
48     char *articleid;
49     char *revid;
50     char *date;
51     char *time;
52     char *timestamp;
53     char *anon;
54     char *editor;
55     char *editorid;
56     char *comment;
57     char *text;
58     vector<string> last_text_tokens;
59     vector<pcrecpp::RE> regexes;
60     vector<string> regex_names;
61     map<string, string> revision_md5; // used for detecting reversions
62
63     // track string size of the elements, to prevent O(N^2) processing in charhndl
64     // when we have to take strlen for every character which we append to the buffer
65     size_t title_size;
66     size_t articleid_size;
67     size_t revid_size;
68     size_t date_size;
69     size_t time_size;
70     size_t timestamp_size;
71     size_t anon_size;
72     size_t editor_size;
73     size_t editorid_size;
74     size_t comment_size;
75     size_t text_size;
76
77     bool minor;
78     
79     enum elements element;
80     enum block position;
81     enum outtype output_type;
82     
83 } revisionData;
84
85
86 /* free_data and clean_data
87  * Takes a pointer to the data struct and an integer {0,1} indicating if the 
88  * title data needs to be cleared as well.
89  * Also, frees memory dynamically allocated to store data.
90  */ 
91 static void
92 clean_data(revisionData *data, int title)
93 {
94     // reset title (if we are switching articles)
95     if (title) {
96         data->title[0] = '\0';
97         data->articleid[0] = '\0';
98         data->title_size = 0;
99         data->articleid_size = 0;
100     }
101
102     // reset text fields
103     data->revid[0] = '\0';
104     data->date[0] = '\0';
105     data->time[0] = '\0';
106     data->timestamp[0] = '\0';
107     data->anon[0] = '\0';
108     data->editor[0] = '\0';
109     data->editorid[0] = '\0';
110     data->comment[0] = '\0';
111     data->text[0] = '\0';
112
113     // reset length tracking
114     data->revid_size = 0;
115     data->date_size = 0;
116     data->time_size = 0;
117     data->timestamp_size = 0;
118     data->anon_size = 0;
119     data->editor_size = 0;
120     data->editorid_size = 0;
121     data->comment_size = 0;
122     data->text_size = 0;
123
124     // reset flags and element type info
125     data->minor = false;
126     data->element = UNUSED;
127
128 }
129
130 // presently unused
131 static void
132 free_data(revisionData *data, int title)
133 {
134     if (title) {
135         //printf("freeing article\n");
136         free(data->title);
137         free(data->articleid);
138     }
139     free(data->revid);
140     free(data->date);
141     free(data->time);
142     free(data->timestamp);
143     free(data->anon);
144     free(data->editor);
145     free(data->editorid);
146     free(data->comment);
147     free(data->text);
148     data->last_text_tokens.clear();
149 }
150
151 void cleanup_revision(revisionData *data) {
152     clean_data(data, 0);
153 }
154
155 void cleanup_article(revisionData *data) {
156     clean_data(data, 1);
157     data->last_text_tokens.clear();
158     data->revision_md5.clear();
159 }
160
161
162 static void 
163 init_data(revisionData *data, outtype output_type)
164 {
165     data->text = (char*) malloc(text_buffer_size);
166     data->comment = (char*) malloc(FIELD_BUFFER_SIZE);
167     data->title = (char*) malloc(FIELD_BUFFER_SIZE);
168     data->articleid = (char*) malloc(FIELD_BUFFER_SIZE);
169     data->revid = (char*) malloc(FIELD_BUFFER_SIZE);
170     data->date = (char*) malloc(FIELD_BUFFER_SIZE);
171     data->time = (char*) malloc(FIELD_BUFFER_SIZE);
172     data->timestamp = (char*) malloc(FIELD_BUFFER_SIZE);
173     data->anon = (char*) malloc(FIELD_BUFFER_SIZE);
174     data->editor = (char*) malloc(FIELD_BUFFER_SIZE);
175     data->editorid = (char*) malloc(FIELD_BUFFER_SIZE);
176     data->minor = false;
177
178     // resets the data fields, null terminates strings, sets lengths
179     clean_data(data, 1);
180
181     data->output_type = output_type;
182 }
183
184 /* for debugging only, prints out the state of the data struct
185  */
186 static void
187 print_state(revisionData *data) 
188 {
189     printf("element = %i\n", data->element);
190     printf("output_type = %i\n", data->output_type);
191     printf("title = %s\n", data->title);
192     printf("articleid = %s\n", data->articleid);
193     printf("revid = %s\n", data->revid);
194     printf("date = %s\n", data->date);
195     printf("time = %s\n", data->time);
196     printf("anon = %s\n", data->anon);
197     printf("editor = %s\n", data->editor);
198     printf("editorid = %s\n", data->editorid);
199     printf("minor = %s\n", (data->minor ? "1" : "0"));
200     printf("comment = %s\n", data->comment); 
201     printf("text = %s\n", data->text);
202     printf("\n");
203
204 }
205
206
207 /* 
208  * write a line of comma-separated value formatted data to standard out
209  * follows the form:
210  * title,articleid,revid,date,time,anon,editor,editorid,minor,comment
211  * (str)  (int)    (int) (str)(str)(bin)(str)   (int)   (bin) (str)
212  *
213  * it is called right before cleanup_revision() and cleanup_article()
214  */
215 static void
216 write_row(revisionData *data)
217 {
218
219     // get md5sum
220     md5_state_t state;
221     md5_byte_t digest[16];
222     char md5_hex_output[2 * 16 + 1];
223     md5_init(&state);
224     md5_append(&state, (const md5_byte_t *)data->text, data->text_size);
225     md5_finish(&state, digest);
226     int di;
227     for (di = 0; di < 16; ++di) {
228         sprintf(md5_hex_output + di * 2, "%02x", digest[di]);
229     }
230
231     string reverted_to;
232     map<string, string>::iterator prev_revision = data->revision_md5.find(md5_hex_output);
233     if (prev_revision != data->revision_md5.end()) {
234         reverted_to = prev_revision->second; // id of previous revision
235     }
236     data->revision_md5[md5_hex_output] = data->revid;
237
238     string text = string(data->text, data->text_size);
239     vector<string> text_tokens;
240     size_t pos = 0;
241     size_t start = 0;
242     while ((pos = text.find_first_of(" \n\t\r", pos)) != string::npos) {
243         //cout << "\"\"\"" << text.substr(start, pos - start) << "\"\"\"" << endl;
244         text_tokens.push_back(text.substr(start, pos - start));
245         start = pos;
246         ++pos;
247     }
248
249     //vector<string> additions;
250     //vector<string> deletions;
251     string additions;
252     string deletions;
253
254     vector<bool> regex_matches_adds;
255     vector<bool> regex_matches_dels;
256
257     if (data->last_text_tokens.empty()) {
258         additions = data->text;
259     } else {
260         // do the diff
261         
262         dtl::Diff< string, vector<string> > d(data->last_text_tokens, text_tokens);
263         //d.onOnlyEditDistance();
264         d.compose();
265
266         vector<pair<string, dtl::elemInfo> > ses_v = d.getSes().getSequence();
267         for (vector<pair<string, dtl::elemInfo> >::iterator sit=ses_v.begin(); sit!=ses_v.end(); ++sit) {
268             switch (sit->second.type) {
269             case dtl::SES_ADD:
270                 //cout << "ADD: \"" << sit->first << "\"" << endl;
271                 additions += sit->first;
272                 break;
273             case dtl::SES_DELETE:
274                 //cout << "DEL: \"" << sit->first << "\"" << endl;
275                 deletions += sit->first;
276                 break;
277             }
278         }
279     }
280     
281     if (!additions.empty()) {
282         //cout << "ADD: " << additions << endl;
283         for (vector<pcrecpp::RE>::iterator r = data->regexes.begin(); r != data->regexes.end(); ++r) {
284             pcrecpp::RE& regex = *r;
285             regex_matches_adds.push_back(regex.PartialMatch(additions));
286         }
287     }
288
289     if (!deletions.empty()) {
290         //cout << "DEL: " << deletions << endl;
291         for (vector<pcrecpp::RE>::iterator r = data->regexes.begin(); r != data->regexes.end(); ++r) {
292             pcrecpp::RE& regex = *r;
293             regex_matches_dels.push_back(regex.PartialMatch(deletions));
294         }
295     }
296
297     data->last_text_tokens = text_tokens;
298
299
300     // print line of tsv output
301     cout
302         << data->title << "\t"
303         << data->articleid << "\t"
304         << data->revid << "\t"
305         << data->date << " "
306         << data->time << "\t"
307         << ((data->editor[0] != '\0') ? "FALSE" : "TRUE") << "\t"
308         << data->editor << "\t"
309         << data->editorid << "\t"
310         << ((data->minor) ? "TRUE" : "FALSE") << "\t"
311         << (unsigned int) data->text_size << "\t"
312         << shannon_H(data->text, data->text_size) << "\t"
313         << md5_hex_output << "\t"
314         << reverted_to << "\t"
315         << (int) additions.size() << "\t"
316         << (int) deletions.size();
317
318     for (int n = 0; n < data->regex_names.size(); ++n) {
319         cout << "\t" << ((!regex_matches_adds.empty() && regex_matches_adds.at(n)) ? "TRUE" : "FALSE")
320              << "\t" << ((!regex_matches_dels.empty() && regex_matches_dels.at(n)) ? "TRUE" : "FALSE");
321     }
322     cout << endl;
323
324     // 
325     if (data->output_type == FULL) {
326         cout << "comment:" << data->comment << endl
327              << "text:" << endl << data->text << endl;
328     }
329
330 }
331
332 void
333 split_timestamp(revisionData *data) 
334 {
335     char *t = data->timestamp;
336     strncpy(data->date, data->timestamp, DATE_LENGTH);
337     char *timeinstamp = &data->timestamp[DATE_LENGTH+1];
338     strncpy(data->time, timeinstamp, TIME_LENGTH);
339 }
340
341 // like strncat but with previously known length
342 char*
343 strlcatn(char *dest, const char *src, size_t dest_len, size_t n)
344 {
345    size_t i;
346
347    for (i = 0 ; i < n && src[i] != '\0' ; i++)
348        dest[dest_len + i] = src[i];
349    dest[dest_len + i] = '\0';
350
351    return dest;
352 }
353
354 static void
355 charhndl(void* vdata, const XML_Char* s, int len)
356
357     revisionData* data = (revisionData*) vdata;
358     size_t bufsz;
359     if (data->element != UNUSED && data->position != SKIP) {
360         switch (data->element) {
361             case TEXT:
362                     // check if we'd overflow our buffer
363                     bufsz = data->text_size + len;
364                     if (bufsz + 1 > text_buffer_size) {
365                         data->text = (char*) realloc(data->text, bufsz + 1);
366                         text_buffer_size = bufsz + 1;
367                     }
368                     strlcatn(data->text, s, data->text_size, len);
369                     data->text_size = bufsz;
370                     break;
371             case COMMENT:
372                     strlcatn(data->comment, s, data->comment_size, len);
373                     data->comment_size += len;
374                     break;
375             case TITLE:
376                     strlcatn(data->title, s, data->title_size, len);
377                     data->title_size += len;
378                     break;
379             case ARTICLEID:
380                    // printf("articleid = %s\n", t);
381                     strlcatn(data->articleid, s, data->articleid_size, len);
382                     data->articleid_size += len;
383                     break;
384             case REVID:
385                    // printf("revid = %s\n", t);
386                     strlcatn(data->revid, s, data->revid_size, len);
387                     data->revid_size += len;
388                     break;
389             case TIMESTAMP: 
390                     strlcatn(data->timestamp, s, data->timestamp_size, len);
391                     data->timestamp_size += len;
392                     if (strlen(data->timestamp) == TIMESTAMP_LENGTH)
393                         split_timestamp(data);
394                     break;
395             case EDITOR:
396                     strlcatn(data->editor, s, data->editor_size, len);
397                     data->editor_size += len;
398                     break;
399             case EDITORID: 
400                     //printf("editorid = %s\n", t);
401                     strlcatn(data->editorid, s, data->editorid_size, len);
402                     data->editorid_size += len;
403                     break;
404             /* the following are implied or skipped:
405             case MINOR: 
406                     printf("found minor element\n");  doesn't work
407                     break;                   minor tag is just a tag
408             case UNUSED: 
409             */
410             default: break;
411         }
412     }
413 }
414
415 static void
416 start(void* vdata, const XML_Char* name, const XML_Char** attr)
417 {
418     revisionData* data = (revisionData*) vdata;
419     
420     if (strcmp(name,"title") == 0) {
421         cleanup_article(data); // cleans up data from last article
422         data->element = TITLE;
423         data->position = TITLE_BLOCK;
424     } else if (data->position != SKIP) {
425         if (strcmp(name,"revision") == 0) {
426             data->element = REVISION;
427             data->position = REVISION_BLOCK;
428         } else if (strcmp(name, "contributor") == 0) {
429             data->element = CONTRIBUTOR;
430             data->position = CONTRIBUTOR_BLOCK;
431         } else if (strcmp(name,"id") == 0)
432             switch (data->position) {
433                 case TITLE_BLOCK:
434                     data->element = ARTICLEID;
435                     break;
436                 case REVISION_BLOCK: 
437                     data->element = REVID;
438                     break;
439                 case CONTRIBUTOR_BLOCK:
440                     data->element = EDITORID;
441                     break;
442             }
443     
444         // minor tag has no character data, so we parse here
445         else if (strcmp(name,"minor") == 0) {
446             data->element = MINOR;
447             data->minor = true; 
448         }
449         else if (strcmp(name,"timestamp") == 0)
450             data->element = TIMESTAMP;
451
452         else if (strcmp(name, "username") == 0)
453             data->element = EDITOR;
454
455         else if (strcmp(name,"ip") == 0) 
456             data->element = EDITORID;
457
458         else if (strcmp(name,"comment") == 0)
459             data->element = COMMENT;
460
461         else if (strcmp(name,"text") == 0)
462             data->element = TEXT;
463
464         else if (strcmp(name,"page") == 0 
465                 || strcmp(name,"mediawiki") == 0
466                 || strcmp(name,"restrictions") == 0
467                 || strcmp(name,"siteinfo") == 0)
468             data->element = UNUSED;
469     }
470
471 }
472
473
474 static void
475 end(void* vdata, const XML_Char* name)
476 {
477     revisionData* data = (revisionData*) vdata;
478     if (strcmp(name, "revision") == 0 && data->position != SKIP) {
479         write_row(data); // crucial... :)
480         cleanup_revision(data);  // also crucial
481     } else {
482         data->element = UNUSED; // sets our state to "not-in-useful"
483     }                           // thus avoiding unpleasant character data 
484                                 // b/w tags (newlines etc.)
485 }
486
487 void print_usage(char* argv[]) {
488     cerr << "usage: <wikimedia dump xml> | " << argv[0] << "[options]" << endl
489          << endl
490          << "options:" << endl
491          << "  -t   print text and comments after each line of tab separated data" << endl
492          << "  -n   name of the following regex (e.g. -n name -r \"...\")" << endl
493          << "  -r   regex to check against additions and deletions" << endl
494          << endl
495          << "Takes a wikimedia data dump XML stream on standard in, and produces" << endl
496          << "a tab-separated stream of revisions on standard out:" << endl
497          << endl
498          << "title, articleid, revid, timestamp, anon, editor, editorid, minor," << endl
499          << "text_length, text_entropy, text_md5, reversion, additions_size, deletions_size" << endl
500          << ".... and additional fields for each regex executed against add/delete diffs" << endl
501          << endl
502          << "Boolean fields are TRUE/FALSE except in the case of reversion, which is blank" << endl
503          << "unless the article is a revert to a previous revision, in which case, it" << endl
504          << "contains the revision ID of the revision which was reverted to." << endl
505          << endl
506          << "author: Erik Garrison <erik@hypervolu.me>" << endl;
507 }
508
509
510 int
511 main(int argc, char *argv[])
512 {
513     
514     enum outtype output_type;
515     int dry_run = 0;
516     // in "simple" output, we don't print text and comments
517     output_type = SIMPLE;
518     char c;
519     string regex_name;
520
521     // the user data struct which is passed to callback functions
522     revisionData data;
523
524     while ((c = getopt(argc, argv, "htn:r:")) != -1)
525         switch (c)
526         {
527             case 'd':
528                 dry_run = 1;
529                 break;
530             case 't':
531                 output_type = FULL;
532                 break;
533             case 'n':
534                 regex_name = optarg;
535                 break;
536             case 'r':
537                 data.regexes.push_back(pcrecpp::RE(optarg, pcrecpp::UTF8()));
538                 data.regex_names.push_back(regex_name);
539                 if (!regex_name.empty()) {
540                     regex_name.clear();
541                 }
542                 break;
543             case 'h':
544                 print_usage(argv);
545                 exit(0);
546                 break;
547         }
548
549     if (dry_run) { // lets us print initialization options
550         printf("simple_output = %i\n", output_type);
551         exit(1);
552     }
553
554     // create a new instance of the expat parser
555     XML_Parser parser = XML_ParserCreate("UTF-8");
556
557     // initialize the elements of the struct to default values
558     init_data(&data, output_type);
559
560
561     // makes the parser pass "data" as the first argument to every callback 
562     XML_SetUserData(parser, &data);
563     void (*startFnPtr)(void*, const XML_Char*, const XML_Char**) = start;
564     void (*endFnPtr)(void*, const XML_Char*) = end;
565     void (*charHandlerFnPtr)(void*, const XML_Char*, int) = charhndl;
566
567     // sets start and end to be the element start and end handlers
568     XML_SetElementHandler(parser, startFnPtr, endFnPtr);
569     // sets charhndl to be the callback for character data
570     XML_SetCharacterDataHandler(parser, charHandlerFnPtr);
571
572     bool done;
573     char buf[BUFSIZ];
574
575     // write header
576
577     cout << "title" << "\t"
578         << "articleid" << "\t"
579         << "revid" << "\t"
580         << "date" << " "
581         << "time" << "\t"
582         << "anon" << "\t"
583         << "editor" << "\t"
584         << "editor_id" << "\t"
585         << "minor" << "\t"
586         << "text_size" << "\t"
587         << "text_entropy" << "\t"
588         << "text_md5" << "\t"
589         << "reversion" << "\t"
590         << "additions_size" << "\t"
591         << "deletions_size";
592
593     int n = 0;
594     if (!data.regexes.empty()) {
595         for (vector<pcrecpp::RE>::iterator r = data.regexes.begin(); r != data.regexes.end(); ++r, ++n) {
596             if (data.regex_names.at(n).empty()) {
597                 cout << "\t" << "regex_" << n << "_add"
598                      << "\t" << "regex_" << n << "_del";
599             } else {
600                 cout << "\t" << data.regex_names.at(n) << "_add"
601                      << "\t" << data.regex_names.at(n) << "_del";
602             }
603         }
604     }
605     cout << endl;
606     
607     // shovel data into the parser
608     do {
609         
610         // read into buf a bufferfull of data from standard input
611         size_t len = fread(buf, 1, BUFSIZ, stdin);
612         done = len < BUFSIZ; // checks if we've got the last bufferfull
613         
614         // passes the buffer of data to the parser and checks for error
615         //   (this is where the callbacks are invoked)
616         if (XML_Parse(parser, buf, len, done) == XML_STATUS_ERROR) {
617             cerr << "XML ERROR: " << XML_ErrorString(XML_GetErrorCode(parser)) << " at line "
618                  << (int) XML_GetCurrentLineNumber(parser) << endl;
619             return 1;
620         }
621     } while (!done);
622    
623
624     XML_ParserFree(parser);
625
626     return 0;
627 }

Benjamin Mako Hill || Want to submit a patch?