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

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

Minor change to print statement

File size: 13.7 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 urlContainsLangCodeInPath = false; /** If any URL on this site contains a /mi(/) in its URL */
77
78 private String domainOfSite;
79 private int numPagesInMRI = 0;
80
81 /** keep a list to store the text of each page */
82 private ArrayList<TextDumpPage> pages;
83
84 private boolean isStartOfNewWebPageRecord(String prevLine, String line) {
85 // The start of a new web page's record in nutch's text dump of an entire site
86 // is denoted by a newline followed by a URL (protocol)
87 // or the very start of the file with a URL (protocol)
88 return ((prevLine == null || prevLine.equals(""))
89 && (line.startsWith("http://") || line.startsWith("https://")));
90 }
91
92 public void debugPageDump(StringBuilder pageDump) {
93 if(DEBUG_MODE) {
94 // START DEBUG
95 logger.debug("__________________________________________");
96 logger.debug("@@@ Found page entry: ");
97 logger.debug("__________________________________________");
98 logger.debug(pageDump.toString());
99 logger.debug("------------------------------------------");
100 // END DEBUG
101 }
102 }
103
104 /** A NutchTextDumpToMongoDB processes the dump.txt for one site */
105 public NutchTextDumpToMongoDB(MongoDBAccess mongodbAccess,
106 MaoriTextDetector maoriTxtDetector, String siteID,
107 File txtDumpFile, long lastModified, boolean siteCrawlUnfinished)
108 throws IOException
109 {
110 // increment static counter of sites processed by a NutchTextDumpToMongoDB instance
111 SITE_COUNTER++;
112
113 // siteID is of the form %5d (e.g. 00020) and is just the name of a site folder
114 this.siteID = siteID;
115 this.siteCrawlUnfinished = siteCrawlUnfinished;
116 this.siteCrawledTimestamp = lastModified;
117
118 this.maoriTxtDetector = maoriTxtDetector;
119 this.mongodbAccess = mongodbAccess;
120
121 pages = new ArrayList<TextDumpPage>();
122
123 String line = null;
124 StringBuilder pageDump = null;
125 try (
126 BufferedReader reader = new BufferedReader(new FileReader(txtDumpFile));
127 ) {
128
129 boolean readingText = false;
130 String prevLine = null;
131
132 while((line = reader.readLine()) != null) { // readLine removes newline separator
133 line = line.trim();
134 // iff outside of a page's body text, then an empty line marks the end of a page
135 // in nutch's text dump of a site.
136 // But note, there can be an empty line (or more?) between the start and end
137 // markers of a page's text, though.
138
139 if(isStartOfNewWebPageRecord(prevLine, line)) {
140
141 if(pageDump != null) { // should also be the case then: if(prevLine != null)
142 // finish old pageDump and begin new one
143
144 //debugPageDump(pageDump);
145
146 TextDumpPage page = new TextDumpPage(siteID, pageDump.toString());
147 // parses the fields and body text of a webpage in nutch's txt dump of entire site
148 //page.parseFields();
149 //page.getText();
150 pages.add(page);
151 pageDump = null;
152
153 }
154
155 // begin new webpage dump
156 pageDump = new StringBuilder();
157 pageDump.append(line);
158 pageDump.append("\n");
159
160 }
161 else if(!line.equals("")) {
162 pageDump.append(line);
163 pageDump.append("\n");
164
165 }
166 // can throw away any newlines between text start and end markers.
167
168 prevLine = line;
169 }
170
171 // process final webpage record:
172 //debugPageDump(pageDump);
173
174 TextDumpPage page = new TextDumpPage(siteID, pageDump.toString());
175 pages.add(page);
176 pageDump = null;
177
178 // for every site, we just need to work out if any of its pages
179 // contains /mi(/) in its URL
180 String url = page.getPageURL();
181 if(!this.urlContainsLangCodeInPath && (url.contains("/mi/") || url.endsWith("/mi"))) {
182 this.urlContainsLangCodeInPath = true;
183 }
184
185 } catch (IOException ioe) {
186 logger.error("@@@@@@@@@ Error reading in nutch txtdump file " + txtDumpFile, ioe);
187 }
188
189 // Just do this once: get and store domain of site.
190 // Passing true to get domain with protocol prefix
191 if(pages.size() > 0) {
192 TextDumpPage firstPage = pages.get(0);
193 String url = firstPage.getPageURL();
194 this.domainOfSite = Utility.getDomainForURL(url, true);
195 }
196 else {
197 this.domainOfSite = "UNKNOWN";
198 }
199
200
201 prepareSiteStats(mongodbAccess);
202 }
203
204
205 private void prepareSiteStats(MongoDBAccess mongodbAccess) throws IOException {
206
207 TextDumpPage page = null;
208 for(int i = 0; i < pages.size(); i++) {
209
210 page = pages.get(i);
211
212 String text = page.getPageText();
213
214 if(text.equals("")) {
215 // don't care about empty pages
216 continue;
217 }
218 else {
219 WEBPAGE_COUNTER++; // count of cumulative total of webpages for all sites
220 countOfWebPagesWithBodyText++; // of this site alone
221
222 boolean isMRI = maoriTxtDetector.isTextInMaori(text);
223 if(isMRI) {
224 numPagesInMRI++;
225 }
226
227 String[] sentences = maoriTxtDetector.getAllSentences(text);
228 int totalSentences = sentences.length;
229 int numSentencesInMRI = 0;
230 ArrayList<SentenceInfo> singleSentences = maoriTxtDetector.getAllSentencesInfo(sentences);
231 ArrayList<SentenceInfo> overlappingSentences = maoriTxtDetector.getAllOverlappingSentencesInfo(sentences);
232
233 WebpageInfo webpage = page.convertStoredDataToWebpageInfo(WEBPAGE_COUNTER/*new ObjectId()*/,
234 this.siteID/*SITE_COUNTER*/,
235 isMRI,
236 totalSentences,
237 singleSentences,
238 overlappingSentences);
239
240 for(SentenceInfo si : singleSentences) {
241 if(si.langCode.equals(MaoriTextDetector.MAORI_3LETTER_CODE)) {
242 numSentencesInMRI++;
243 }
244 }
245 webpage.setMRISentenceCount(numSentencesInMRI);
246 webpage.setContainsMRI((numSentencesInMRI > 0));
247
248 //mongodbAccess.insertWebpageInfo(webpage);
249 mongodbAccess.datastore.save(webpage);
250 }
251 }
252 }
253
254 /*
255 public void printSiteStats() {
256
257
258 logger.info("------------- " + this.siteID + " SITE STATS -----------");
259
260 logger.info("SITE DOMAIN: " + this.domainOfSite);
261 logger.info("Total number of web pages in site: " + pages.size());
262 logger.info("Of these, the number of pages in Māori (mri) were: " + this.pagesInMRI.size());
263
264 if(pagesInMRI.size() > 0) {
265 logger.info("The following were the pages detected by OpenNLP as being in Māori with " + maoriTxtDetector.MINIMUM_CONFIDENCE + " confidence");
266 for(MRIWebPageStats mriWebPageInfo : pagesInMRI) {
267 logger.info(mriWebPageInfo.toString());
268 }
269 }
270
271 logger.info(" ----------- ");
272 if(pagesContainingMRI.size() > 0) {
273 logger.info("The following pages weren't detected as primarily being in Māori");
274 logger.info("But still contained sentences detected as Māori");
275 for(MRIWebPageStats mriWebPageInfo : pagesContainingMRI) {
276 logger.info(mriWebPageInfo.toString());
277 }
278
279 } else {
280 logger.info("No further pages detected as containing any sentences in MRI");
281 }
282 logger.info(" ----------- ");
283 }
284 */
285
286
287
288 public void websiteDataToDB() {
289
290
291 // https://stackoverflow.com/questions/35183146/how-can-i-create-a-java-8-localdate-from-a-long-epoch-time-in-milliseconds
292 // LocalDateTime date =
293 // LocalDateTime.ofInstant(Instant.ofEpochMilli(this.siteCrawledTimestamp), ZoneId.systemDefault());
294 // String crawlTimestamp =
295 // date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + " " + date.format(DateTimeFormatter.ofPattern("HH:mm:ss"));
296
297 boolean redoCrawl = false;
298
299 if(this.siteCrawlUnfinished) {
300 // arbitrary decision, but need some indication that the MRI content was not close to one-off in the website
301 if(this.numPagesInMRI > 2) {
302 redoCrawl = true;
303 }
304 }
305
306 File geoLiteCityDatFile = new File(this.getClass().getClassLoader().getResource("GeoLiteCity.dat").getFile());
307 try {
308 this.geoLocationCountryCode = Utility.getCountryCodeOfDomain(this.domainOfSite, geoLiteCityDatFile);
309 } catch(Exception e) {
310 e.printStackTrace();
311 this.geoLocationCountryCode = null;
312 }
313
314 int totalPages = pages.size();
315
316 WebsiteInfo website = new WebsiteInfo(/*SITE_COUNTER,*/ this.siteID, this.domainOfSite,
317 totalPages, this.countOfWebPagesWithBodyText, this.numPagesInMRI,
318 this.siteCrawledTimestamp, this.siteCrawlUnfinished, redoCrawl,
319 this.geoLocationCountryCode, this.urlContainsLangCodeInPath);
320
321 //mongodbAccess.insertWebsiteInfo(website);
322 mongodbAccess.datastore.save(website);
323 }
324
325
326 // --------------- STATIC METHODS AND INNER CLASSED USED BY MAIN -------------- //
327
328 public static void printUsage() {
329 System.err.println("Run this program as:");
330 System.err.println("\tNutchTextDumpToMongoDB <path to 'crawled' folder>");
331 }
332
333 public static void main(String[] args) {
334 if(args.length != 1) {
335 printUsage();
336 return;
337 }
338
339 File sitesDir = new File(args[0]);
340 if(!sitesDir.exists() || !sitesDir.isDirectory()) {
341 logger.error("Error: " + args[0] + " does not exist or is not a directory");
342 return;
343 }
344
345 NutchTextDumpToMongoDB.DEBUG_MODE = false;
346
347
348 try (
349 MongoDBAccess mongodb = new MongoDBAccess();
350 ) {
351
352 mongodb.connectToDB();
353 //mongodb.showCollections();
354
355 // print out the column headers for the websites csv file
356 // https://commons.apache.org/proper/commons-csv/apidocs/org/apache/commons/csv/CSVPrinter.html
357 // OPTIONAL TODO: creating collections can be done here if dropping and recreating
358
359 MaoriTextDetector mriTxtDetector = new MaoriTextDetector(true); // true: run silent
360 File[] sites = sitesDir.listFiles();
361
362 // sort site folders in alphabetical order
363 // https://stackoverflow.com/questions/7199911/how-to-file-listfiles-in-alphabetical-order
364 Arrays.sort(sites);
365
366 for(File siteDir : sites) { // e.g. 00001
367 if(siteDir.isDirectory()) {
368 // look for dump.txt
369 File txtDumpFile = new File(siteDir, "dump.txt");
370 if(!txtDumpFile.exists()) {
371 logger.error("Text dump file " + txtDumpFile + " did not exist");
372 continue;
373 }
374
375 else {
376 File UNFINISHED_FILE = new File(siteDir, "UNFINISHED");
377
378 String siteID = siteDir.getName();
379 long lastModified = siteDir.lastModified();
380 logger.debug("Processing siteID: " + siteID);
381 NutchTextDumpToMongoDB nutchTxtDump = new NutchTextDumpToMongoDB(
382 mongodb, mriTxtDetector,
383 siteID, txtDumpFile, lastModified, UNFINISHED_FILE.exists());
384 // now it's parsed all the web pages in the site's text dump
385
386 // Let's print stats on each web page's detected language being MRI or not
387 // and how many pages there were in the site in total.
388
389 //nutchTxtDump.printSiteStats();
390
391 nutchTxtDump.websiteDataToDB();
392 }
393 }
394
395 }
396
397 } catch(Exception e) {
398 // can get an exception when instantiating NutchTextDumpToMongoDB instance
399 // or with CSV file
400 logger.error(e.getMessage(), e);
401 }
402 }
403}
Note: See TracBrowser for help on using the repository browser.