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

Last change on this file since 33808 was 33808, checked in by ak19, 4 years ago

Storing not just whether /mi(/) suffix is in path, but also whether http(s):mi. is in path, as storing these can help reducing number of auto-translated sites too in a similar way.

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