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

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

Changes to support the top 5 predicted langcodes and their confidence values per sentence/overlapping sentence (all 103 made some documents, like of site 00006, too big too go into mongodb). Have re-run the NutchTextDumpToMongDB to send the new form of the docs into mongodb.

File size: 13.2 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 if(pageDump == null) {
175 logger.warn("siteID " + siteID + " had an empty dump.txt file. Reinspect site.");
176 } else {
177 TextDumpPage page = new TextDumpPage(siteID, pageDump.toString());
178 pages.add(page);
179 pageDump = null;
180
181 // for every site, we just need to work out if any of its pages
182 // contains /mi(/) in its URL
183 String url = page.getPageURL();
184 if(!this.urlContainsLangCodeInPath && (url.contains("/mi/") || url.endsWith("/mi"))) {
185 this.urlContainsLangCodeInPath = true;
186 }
187 }
188
189 } catch (IOException ioe) {
190 logger.error("@@@@@@@@@ Error reading in nutch txtdump file " + txtDumpFile, ioe);
191 }
192
193 // Just do this once: get and store domain of site.
194 // Passing true to get domain with protocol prefix
195 if(pages.size() > 0) {
196 TextDumpPage firstPage = pages.get(0);
197 String url = firstPage.getPageURL();
198 this.domainOfSite = Utility.getDomainForURL(url, true);
199 }
200 else {
201 this.domainOfSite = "UNKNOWN";
202 }
203
204
205 prepareSiteStats(mongodbAccess);
206 }
207
208
209 private void prepareSiteStats(MongoDBAccess mongodbAccess) throws IOException {
210
211 TextDumpPage page = null;
212 for(int i = 0; i < pages.size(); i++) {
213
214 page = pages.get(i);
215
216 String text = page.getPageText();
217
218 if(text.equals("")) {
219 // don't care about empty pages
220 continue;
221 }
222 else {
223 WEBPAGE_COUNTER++; // count of cumulative total of webpages for all sites
224 countOfWebPagesWithBodyText++; // of this site alone
225
226 boolean isMRI = maoriTxtDetector.isTextInMaori(text);
227 if(isMRI) {
228 numPagesInMRI++;
229 }
230
231 String[] sentences = maoriTxtDetector.getAllSentences(text);
232 int totalSentences = sentences.length;
233 int numSentencesInMRI = 0;
234 ArrayList<SentenceInfo> singleSentences = maoriTxtDetector.getAllSentencesInfo(sentences);
235 ArrayList<SentenceInfo> overlappingSentences = maoriTxtDetector.getAllOverlappingSentencesInfo(sentences);
236
237 WebpageInfo webpage = page.convertStoredDataToWebpageInfo(WEBPAGE_COUNTER/*new ObjectId()*/,
238 this.siteID/*SITE_COUNTER*/,
239 isMRI,
240 totalSentences,
241 singleSentences,
242 overlappingSentences);
243
244 for(SentenceInfo si : singleSentences) {
245 LanguageInfo bestLanguage = si.languagesInfo[0];
246 if(bestLanguage.langCode.equals(MaoriTextDetector.MAORI_3LETTER_CODE)) {
247 numSentencesInMRI++;
248 }
249 }
250 webpage.setMRISentenceCount(numSentencesInMRI);
251 webpage.setContainsMRI((numSentencesInMRI > 0));
252
253 //mongodbAccess.insertWebpageInfo(webpage);
254 // Uses morphia to save to mongodb, see https://www.baeldung.com/mongodb-morphia
255 mongodbAccess.datastore.save(webpage);
256 }
257 }
258 }
259
260
261 public void websiteDataToDB() {
262
263
264 // https://stackoverflow.com/questions/35183146/how-can-i-create-a-java-8-localdate-from-a-long-epoch-time-in-milliseconds
265 // LocalDateTime date =
266 // LocalDateTime.ofInstant(Instant.ofEpochMilli(this.siteCrawledTimestamp), ZoneId.systemDefault());
267 // String crawlTimestamp =
268 // date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + " " + date.format(DateTimeFormatter.ofPattern("HH:mm:ss"));
269
270 boolean redoCrawl = false;
271
272 if(this.siteCrawlUnfinished) {
273 // arbitrary decision, but need some indication that the MRI content was not close to one-off in the website
274 if(this.numPagesInMRI > 2) {
275 redoCrawl = true;
276 }
277 }
278
279 File geoLiteCityDatFile = new File(this.getClass().getClassLoader().getResource("GeoLiteCity.dat").getFile());
280 try {
281 if(this.domainOfSite.equals("UNKNOWN")) {
282 this.geoLocationCountryCode = "UNKNOWN";
283 } else {
284 this.geoLocationCountryCode = Utility.getCountryCodeOfDomain(this.domainOfSite, geoLiteCityDatFile);
285 }
286 } catch(Exception e) {
287 logger.error("*** For SiteID " + siteID + ", got exception: " + e.getMessage(), e);
288 this.geoLocationCountryCode = null;
289 }
290
291 int totalPages = pages.size();
292
293 WebsiteInfo website = new WebsiteInfo(/*SITE_COUNTER,*/ this.siteID, this.domainOfSite,
294 totalPages, this.countOfWebPagesWithBodyText, this.numPagesInMRI,
295 this.siteCrawledTimestamp, this.siteCrawlUnfinished, redoCrawl,
296 this.geoLocationCountryCode, this.urlContainsLangCodeInPath);
297
298 //mongodbAccess.insertWebsiteInfo(website);
299 // Uses morphia to save to mongodb, see https://www.baeldung.com/mongodb-morphia
300 mongodbAccess.datastore.save(website);
301 }
302
303
304 // --------------- STATIC METHODS AND INNER CLASSED USED BY MAIN -------------- //
305
306 public static void printUsage() {
307 System.err.println("Run this program as:");
308 System.err.println("\tNutchTextDumpToMongoDB <path to 'crawled' folder>");
309 }
310
311 public static void main(String[] args) {
312 if(args.length != 1) {
313 printUsage();
314 return;
315 }
316
317 File sitesDir = new File(args[0]);
318 if(!sitesDir.exists() || !sitesDir.isDirectory()) {
319 logger.error("Error: " + args[0] + " does not exist or is not a directory");
320 return;
321 }
322
323 NutchTextDumpToMongoDB.DEBUG_MODE = false;
324
325
326 try (
327 MongoDBAccess mongodb = new MongoDBAccess();
328 ) {
329
330 mongodb.connectToDB();
331 //mongodb.showCollections();
332
333 // print out the column headers for the websites csv file
334 // https://commons.apache.org/proper/commons-csv/apidocs/org/apache/commons/csv/CSVPrinter.html
335 // OPTIONAL TODO: creating collections can be done here if dropping and recreating
336
337 MaoriTextDetector mriTxtDetector = new MaoriTextDetector(true); // true: run silent
338 File[] sites = sitesDir.listFiles();
339
340 // sort site folders in alphabetical order
341 // https://stackoverflow.com/questions/7199911/how-to-file-listfiles-in-alphabetical-order
342 Arrays.sort(sites);
343
344 for(File siteDir : sites) { // e.g. 00001
345 if(siteDir.isDirectory()) {
346 // look for dump.txt
347 File txtDumpFile = new File(siteDir, "dump.txt");
348 if(!txtDumpFile.exists()) {
349 logger.error("Text dump file " + txtDumpFile + " did not exist");
350 continue;
351 }
352
353 else {
354 File UNFINISHED_FILE = new File(siteDir, "UNFINISHED");
355
356 String siteID = siteDir.getName();
357 if(siteID.contains("_")) {
358 logger.warn("*** Skipping site " + siteID + " as its dir name indicates it wasn't crawled properly.");
359 continue;
360 }
361
362 long lastModified = siteDir.lastModified();
363 logger.debug("@@@ Processing siteID: " + siteID);
364 NutchTextDumpToMongoDB nutchTxtDump = new NutchTextDumpToMongoDB(
365 mongodb, mriTxtDetector,
366 siteID, txtDumpFile, lastModified, UNFINISHED_FILE.exists());
367 // now it's parsed all the web pages in the site's text dump
368
369 // Let's print stats on each web page's detected language being MRI or not
370 // and how many pages there were in the site in total.
371
372 //nutchTxtDump.printSiteStats();
373
374 nutchTxtDump.websiteDataToDB();
375 }
376 }
377
378 }
379
380 } catch(Exception e) {
381 // can get an exception when instantiating NutchTextDumpToMongoDB instance
382 // or with CSV file
383 logger.error(e.getMessage(), e);
384 }
385 }
386}
Note: See TracBrowser for help on using the repository browser.