source: other-projects/maori-lang-detection/src/org/greenstone/atea/NutchTextDumpToMongoDB.java@ 33988

Last change on this file since 33988 was 33988, checked in by ak19, 4 years ago
  1. Print out which web pages of which web site's dump.txt were empty. Then can run NutchTextDumpToMongoDB > outfile.txt 2>&1. 2. More instructions for before running NutchTextDumpToMongoDB
File size: 16.5 KB
Line 
1package org.greenstone.atea;
2
3import java.io.*;
4import java.lang.ArrayIndexOutOfBoundsException;
5import java.time.LocalDateTime;
6import java.util.ArrayList;
7import java.util.Arrays;
8
9import org.apache.commons.csv.*;
10import org.apache.log4j.Logger;
11
12//import org.bson.types.ObjectId;
13
14import org.greenstone.atea.morphia.*;
15
16
17/**
18 * Class to process the dump text files produced FOR EACH SITE (e.g. site "00001") that
19 * Nutch has finished crawling and whose text has been dumped out to a file called dump.txt.
20 * This reads in the dump.txt file contained in each site folder within the input folder.
21 * (e.g. input folder "crawled" could contain folders 00001 to 01465. Each contains a dump.txt)
22 * Each dump.txt could contain the text contents for an entire site, or for individual pages.
23 * This class then uses class TextDumpPage to parse each webpage within a dump.txt,
24 * which parses out the actual text body content of each webpage's section within a dump.txt.
25 * Finally, MaoriTextDetector is run over that to determine whether the full body text is
26 * likely to be in Maori or not.
27 *
28 * Potential issues: since a web page's text is dumped out by nutch with neither paragraph
29 * nor even newline separator, it's hard to be sure that the entire page is in language.
30 * If it's in multiple languages, there's no way to be sure there aren't promising Maori language
31 * paragraphs contained in a page, if the majority/the remainder happen to be in English.
32 *
33 * So if we're looking for any paragraphs in Maori to store in a DB, perhaps it's better to run
34 * the MaoriTextDetector.isTextInMaori(BufferedReader reader) over two "lines" at a time,
35 * instead of running it over the entire html body's text.
36 *
37 * TO COMPILE OR RUN, FIRST DO:
38 * cd maori-lang-detection/apache-opennlp-1.9.1
39 * export OPENNLP_HOME=`pwd`
40 * cd maori-lang-detection/src
41 *
42 * MORE IMPORTANT PRELIMINARIES:
43 * - Make sure the MongoDB is up and running and accessible.
44 * - If you want to keep any existing MongoDB collections called Websites and Webpages, then
45 * first renamed those collections in MongoDB (using Robo3T makes renaming easy) before
46 * running this program.
47 *
48 * TO COMPILE:
49 * maori-lang-detection/src$
50 * javac -cp ".:../conf:../lib/*:$OPENNLP_HOME/lib/opennlp-tools-1.9.1.jar" org/greenstone/atea/NutchTextDumpToMongoDB.java
51 *
52 * TO RUN:
53 * maori-lang-detection/src$
54 * java -cp ".:../conf:../lib/*:$OPENNLP_HOME/lib/opennlp-tools-1.9.1.jar" org/greenstone/atea/NutchTextDumpToMongoDB ../crawled-small
55 *
56 * or:
57 * java -cp ".:../conf:../lib/*:$OPENNLP_HOME/lib/opennlp-tools-1.9.1.jar" org/greenstone/atea/NutchTextDumpToMongoDB ../crawled-small > ../crawled-small/bla.txt 2>&1
58 *
59*/
60public class NutchTextDumpToMongoDB {
61 static Logger logger = Logger.getLogger(org.greenstone.atea.NutchTextDumpToMongoDB.class.getName());
62
63 static boolean DEBUG_MODE = true; // this is set to false in main() at the end of this class
64
65 /** Counter for number of sites.
66 * Should be equal to number of times NutchTextDumpToMongoDB constructor
67 * is called: once per site.
68 */
69 static private int SITE_COUNTER = 0;
70 static private long WEBPAGE_COUNTER = 0;
71
72 private final MaoriTextDetector maoriTxtDetector;
73 private final MongoDBAccess mongodbAccess;
74
75 public final String siteID;
76 public final boolean siteCrawlUnfinished;
77 public final long siteCrawledTimestamp; /** When the crawl of the site terminated */
78
79 private int countOfWebPagesWithBodyText = 0;
80
81 private String geoLocationCountryCode = null; /** 2 letter country code */
82 private boolean urlContainsLangCodeInPath = false; /** If any URL on this site contains a /mi(/) or http(s)://mi.* in its URL path */
83
84 private String domainOfSite;
85 //private String baseSiteDomain; // domainOfSite stripped of any http(s)://www.
86 private int numPagesInMRI = 0;
87 private int numPagesContainingMRI = 0;
88
89 /** keep a list to store the text of each page */
90 private ArrayList<TextDumpPage> pages;
91
92
93
94 /** Number of language and confidence results to return for storing in MongoDB
95 * MongoDB runs out of space if storing too many, as we store this info per sentence
96 * and a long text document becomes a very large MongoDB document presumably */
97 private static final int NUM_TOP_LANGUAGES = 3; // 103 max, in current version of opennlp lang model
98
99
100 private boolean isStartOfNewWebPageRecord(String prevLine, String line) {
101 // The start of a new web page's record in nutch's text dump of an entire site
102 // is denoted by a newline followed by a URL (protocol)
103 // or the very start of the file with a URL (protocol)
104 return ((prevLine == null || prevLine.equals(""))
105 && (line.startsWith("http://") || line.startsWith("https://")));
106 }
107
108 public void debugPageDump(StringBuilder pageDump) {
109 if(DEBUG_MODE) {
110 // START DEBUG
111 logger.debug("__________________________________________");
112 logger.debug("@@@ Found page entry: ");
113 logger.debug("__________________________________________");
114 logger.debug(pageDump.toString());
115 logger.debug("------------------------------------------");
116 // END DEBUG
117 }
118 }
119
120 /** A NutchTextDumpToMongoDB processes the dump.txt for one site */
121 public NutchTextDumpToMongoDB(MongoDBAccess mongodbAccess,
122 MaoriTextDetector maoriTxtDetector, String siteID,
123 File txtDumpFile, long lastModified, boolean siteCrawlUnfinished)
124 throws IOException
125 {
126 // increment static counter of sites processed by a NutchTextDumpToMongoDB instance
127 SITE_COUNTER++;
128
129 // siteID is of the form %5d (e.g. 00020) and is just the name of a site folder
130 this.siteID = siteID;
131 this.siteCrawlUnfinished = siteCrawlUnfinished;
132 this.siteCrawledTimestamp = lastModified;
133
134 this.maoriTxtDetector = maoriTxtDetector;
135 this.mongodbAccess = mongodbAccess;
136
137 pages = new ArrayList<TextDumpPage>();
138
139 String line = null;
140 StringBuilder pageDump = null;
141 try (
142 BufferedReader reader = new BufferedReader(new FileReader(txtDumpFile));
143 ) {
144
145 boolean readingText = false;
146 String prevLine = null;
147
148 while((line = reader.readLine()) != null) { // readLine removes newline separator
149 line = line.trim();
150 // iff outside of a page's body text, then an empty line marks the end of a page
151 // in nutch's text dump of a site.
152 // But note, there can be an empty line (or more?) between the start and end
153 // markers of a page's text, though.
154
155 if(isStartOfNewWebPageRecord(prevLine, line)) {
156
157 if(pageDump != null) { // should also be the case then: if(prevLine != null)
158 // finish old pageDump and begin new one
159
160 //debugPageDump(pageDump);
161
162 TextDumpPage page = new TextDumpPage(siteID, pageDump.toString());
163 // parses the fields and body text of a webpage in nutch's txt dump of entire site
164 //page.parseFields();
165 //page.getText();
166 pages.add(page);
167 inspectPageURLPath(page);
168 pageDump = null;
169
170 }
171
172 // begin new webpage dump
173 pageDump = new StringBuilder();
174 pageDump.append(line);
175 pageDump.append("\n");
176
177 }
178 else if(!line.equals("")) {
179 pageDump.append(line);
180 pageDump.append("\n");
181
182 }
183 // can throw away any newlines between text start and end markers.
184
185 prevLine = line;
186 }
187
188 // process final webpage record:
189 //debugPageDump(pageDump);
190
191 if(pageDump == null) {
192 logger.warn("siteID " + siteID + " had an empty dump.txt file. Reinspect site.");
193 } else {
194 TextDumpPage page = new TextDumpPage(siteID, pageDump.toString());
195 pages.add(page);
196 inspectPageURLPath(page);
197 pageDump = null;
198 }
199
200
201 } catch (IOException ioe) {
202 logger.error("@@@@@@@@@ Error reading in nutch txtdump file " + txtDumpFile, ioe);
203 }
204
205 // Just do this once: get and store domain of site.
206 // Passing true to get domain with protocol prefix
207 if(pages.size() > 0) {
208 TextDumpPage firstPage = pages.get(0);
209 String url = firstPage.getPageURL();
210 this.domainOfSite = Utility.getDomainForURL(url, true);
211 //this.baseSiteDomain = Utility.stripProtocolAndWWWFromURL(this.domainOfSite);
212 }
213 else {
214 this.domainOfSite = "UNKNOWN";
215 //this.baseSiteDomain = "UNKNOWN";
216 }
217
218 /* No need to loop again through all pages. Instead, just inspectPageURLPath() as each page is created above.
219 // For any site, we just need to work out if any of its pages contains /mi(/) or http(s)://mi.* in its URL path
220 for(TextDumpPage aPage : pages) {
221 inspectPageURLPath(aPage);
222 }
223 */
224 webPageDataToMongoDB(mongodbAccess);
225 }
226
227
228 /** for every site, we just need to work out if any of its pages contains /mi(/) or http(s)://mi. in its URL.
229 * This method is called on each page of a site as the page is created. */
230 private void inspectPageURLPath(TextDumpPage page) {
231 String url = page.getPageURL();
232 //logger.debug("@@@@ pageURL: " + url);
233
234 if(!this.urlContainsLangCodeInPath) { // if not already set to true for any previous page in this site,
235 // check if this page of the site contains /mi(/) or http(s)://mi in its URL path
236 if(url.contains("/mi/") || url.endsWith("/mi") || url.startsWith("https://mi.") || url.startsWith("http://mi.")) {
237 this.urlContainsLangCodeInPath = true;
238 }
239 }
240 }
241
242
243 private void webPageDataToMongoDB(MongoDBAccess mongodbAccess) throws IOException {
244
245 TextDumpPage page = null;
246 for(int i = 0; i < pages.size(); i++) {
247
248 page = pages.get(i);
249
250 String text = page.getPageText();
251
252 if(text.equals("")) {
253 System.err.println("siteID: " + siteID + "- Empty page " + i + " - URL: "
254 + page.getPageURL());
255
256 // don't care about empty pages
257 continue;
258 }
259 else {
260 WEBPAGE_COUNTER++; // count of cumulative total of webpages for all sites
261 countOfWebPagesWithBodyText++; // of this site alone
262
263 boolean isMRI = maoriTxtDetector.isTextInMaori(text);
264 if(isMRI) {
265 numPagesInMRI++;
266 }
267
268 String[] sentences = maoriTxtDetector.getAllSentences(text);
269 int totalSentences = sentences.length;
270 int numSentencesInMRI = 0;
271 ArrayList<SentenceInfo> singleSentences = maoriTxtDetector.getAllSentencesInfo(sentences, NUM_TOP_LANGUAGES);
272 ArrayList<SentenceInfo> overlappingSentences = maoriTxtDetector.getAllOverlappingSentencesInfo(sentences, NUM_TOP_LANGUAGES);
273
274 WebpageInfo webpage = page.convertStoredDataToWebpageInfo(WEBPAGE_COUNTER/*new ObjectId()*/,
275 this.siteID/*SITE_COUNTER*/,
276 isMRI,
277 totalSentences,
278 singleSentences,
279 overlappingSentences);
280
281
282 for(SentenceInfo si : singleSentences) {
283 //LanguageInfo bestLanguage = si.languagesInfo[0];
284 //if(bestLanguage.langCode.equals(MaoriTextDetector.MAORI_3LETTER_CODE)) {
285 if(si.bestLangCode.equals(MaoriTextDetector.MAORI_3LETTER_CODE)) {
286 numSentencesInMRI++;
287 }
288 }
289
290
291 webpage.setMRISentenceCount(numSentencesInMRI);
292 webpage.setContainsMRI((numSentencesInMRI > 0));
293 if(numSentencesInMRI > 0) { // if(numSentencesInMRI >= 5) {
294 // Not sure if we can trust that a single sentence detected as Maori on a page is really Maori
295 // But if at least 5 sentences are detected as Maori, it is more likely to be the case to be MRI?
296 numPagesContainingMRI++;
297 }
298
299 //mongodbAccess.insertWebpageInfo(webpage);
300 // Uses morphia to save to mongodb, see https://www.baeldung.com/mongodb-morphia
301 mongodbAccess.datastore.save(webpage);
302 }
303 }
304 }
305
306
307 public void websiteDataToDB() {
308
309
310 // https://stackoverflow.com/questions/35183146/how-can-i-create-a-java-8-localdate-from-a-long-epoch-time-in-milliseconds
311 // LocalDateTime date =
312 // LocalDateTime.ofInstant(Instant.ofEpochMilli(this.siteCrawledTimestamp), ZoneId.systemDefault());
313 // String crawlTimestamp =
314 // date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + " " + date.format(DateTimeFormatter.ofPattern("HH:mm:ss"));
315
316 boolean redoCrawl = false;
317
318 if(this.siteCrawlUnfinished) {
319 // arbitrary decision, but need some indication that the MRI content was not close to one-off in the website
320 if(this.numPagesInMRI > 2) {
321 redoCrawl = true;
322 }
323 }
324
325 File geoLiteCityDatFile = new File(this.getClass().getClassLoader().getResource("GeoLiteCity.dat").getFile());
326 try {
327 if(this.domainOfSite.equals("UNKNOWN")) { // for sites that had 0 webpages downloaded, we have no domain
328 this.geoLocationCountryCode = "UNKNOWN";
329 } else {
330 this.geoLocationCountryCode = Utility.getCountryCodeOfDomain(this.domainOfSite, geoLiteCityDatFile);
331 }
332 } catch(Exception e) {
333 logger.error("*** For SiteID " + siteID + ", got exception: " + e.getMessage(), e);
334
335 //if(this.domainOfSite.endsWith(".nz")) { // nz TLDs are worth counting
336 //this.geoLocationCountryCode = "NZ";
337 //}
338
339 // Help along identification of domain's country by construing TLDs if 2 letters after last period mark
340 int periodIndex = domainOfSite.length()-3;
341 // .com|org etc extensions that have 3 chars afte period mark will remain unknown
342 // 2 letter extensions will be considered TLD
343 if(periodIndex >=0 && domainOfSite.charAt(periodIndex) == '.' && ((periodIndex+1) < domainOfSite.length())) {
344 // has a 2 letter TLD. Make it uppercase to match return value of Utility.getCountryCodeOfDomain() above
345 String TLD = domainOfSite.substring(periodIndex+1);
346 this.geoLocationCountryCode = TLD.toUpperCase();
347 } else {
348 this.geoLocationCountryCode = "UNKNOWN"; // couldn't get the country code, so should also be UNKNOWN not null
349 }
350 }
351
352 int totalPages = pages.size();
353
354 WebsiteInfo website = new WebsiteInfo(/*SITE_COUNTER,*/ this.siteID,
355 this.domainOfSite, //this.baseSiteDomain,
356 totalPages, this.countOfWebPagesWithBodyText,
357 this.numPagesInMRI, this.numPagesContainingMRI,
358 this.siteCrawledTimestamp, this.siteCrawlUnfinished, redoCrawl,
359 this.geoLocationCountryCode, this.urlContainsLangCodeInPath);
360
361 //mongodbAccess.insertWebsiteInfo(website);
362 // Uses morphia to save to mongodb, see https://www.baeldung.com/mongodb-morphia
363 mongodbAccess.datastore.save(website);
364 }
365
366
367 // --------------- STATIC METHODS AND INNER CLASSED USED BY MAIN -------------- //
368
369 public static void printUsage() {
370 System.err.println("Run this program as:");
371 System.err.println("\tNutchTextDumpToMongoDB <path to 'crawled' folder>");
372 }
373
374 public static void main(String[] args) {
375 if(args.length != 1) {
376 printUsage();
377 return;
378 }
379
380 File sitesDir = new File(args[0]);
381 if(!sitesDir.exists() || !sitesDir.isDirectory()) {
382 logger.error("Error: " + args[0] + " does not exist or is not a directory");
383 return;
384 }
385
386 NutchTextDumpToMongoDB.DEBUG_MODE = false;
387
388
389 try (
390 MongoDBAccess mongodb = new MongoDBAccess();
391 ) {
392
393 mongodb.connectToDB();
394 //mongodb.showCollections();
395
396 // print out the column headers for the websites csv file
397 // https://commons.apache.org/proper/commons-csv/apidocs/org/apache/commons/csv/CSVPrinter.html
398 // OPTIONAL TODO: creating collections can be done here if dropping and recreating
399
400 MaoriTextDetector mriTxtDetector = new MaoriTextDetector(true); // true: run silent
401 File[] sites = sitesDir.listFiles();
402
403 // sort site folders in alphabetical order
404 // https://stackoverflow.com/questions/7199911/how-to-file-listfiles-in-alphabetical-order
405 Arrays.sort(sites);
406
407 for(File siteDir : sites) { // e.g. 00001
408 if(siteDir.isDirectory()) {
409 // look for dump.txt
410 File txtDumpFile = new File(siteDir, "dump.txt");
411 if(!txtDumpFile.exists()) {
412 logger.error("Text dump file " + txtDumpFile + " did not exist");
413 continue;
414 }
415
416 else {
417 File UNFINISHED_FILE = new File(siteDir, "UNFINISHED");
418
419 String siteID = siteDir.getName();
420 if(siteID.contains("_")) {
421 logger.warn("*** Skipping site " + siteID + " as its dir name indicates it wasn't crawled properly.");
422 continue;
423 }
424
425 long lastModified = siteDir.lastModified();
426 logger.debug("@@@ Processing siteID: " + siteID);
427 NutchTextDumpToMongoDB nutchTxtDump = new NutchTextDumpToMongoDB(
428 mongodb, mriTxtDetector,
429 siteID, txtDumpFile, lastModified, UNFINISHED_FILE.exists());
430 // now it's parsed all the web pages in the site's text dump
431
432 // Let's print stats on each web page's detected language being MRI or not
433 // and how many pages there were in the site in total.
434
435 //nutchTxtDump.printSiteStats();
436
437 nutchTxtDump.websiteDataToDB();
438 }
439 }
440
441 }
442
443 } catch(Exception e) {
444 // can get an exception when instantiating NutchTextDumpToMongoDB instance
445 // or with CSV file
446 logger.error(e.getMessage(), e);
447 }
448 }
449}
Note: See TracBrowser for help on using the repository browser.