-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmine_google.py
More file actions
1563 lines (1390 loc) · 65.5 KB
/
mine_google.py
File metadata and controls
1563 lines (1390 loc) · 65.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# coding=utf-8
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# ! IMPORTANT ! Do NOT remove the first line of this file, you will break the code !
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
import os, sys, re, optparse, random, operator, unicodedata, time
from math import log10, sqrt
# from pprint import pprint
from pattern.web import URL, URLError, plaintext
from pdfminer.pdfdocument import PDFDocument
from pdfminer.pdfparser import PDFParser
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.pdfdevice import PDFDevice, TagExtractor
from pdfminer.pdfpage import PDFPage
from pdfminer.converter import XMLConverter, HTMLConverter, TextConverter
from pdfminer.cmapdb import CMapDB
from pdfminer.layout import LAParams
from pdfminer.image import ImageWriter
try:
# Try importing for Python 3
# pylint: disable-msg=F0401
# pylint: disable-msg=E0611
from urllib.request import HTTPCookieProcessor, Request, build_opener
from urllib.parse import quote
from http.cookiejar import CookieJar
except ImportError:
# Fallback for Python 2
from urllib2 import Request, build_opener, HTTPCookieProcessor
from urllib import quote
from cookielib import CookieJar
# Import BeautifulSoup -- try 4 first, then fall back to older
try:
from bs4 import BeautifulSoup
except ImportError:
try:
from BeautifulSoup import BeautifulSoup
except:
print('Must first install BeautifulSoup ... Sorry!')
sys.exit(1)
# Support unicode in both Python 2 and 3. In Python 3, unicode is str.
if sys.version_info[0] == 3:
unicode = str # pylint: disable-msg=W0622
encode = lambda s: s # pylint: disable-msg=C0103
else:
encode = lambda s: s.encode('utf-8') # pylint: disable-msg=C0103
#################################################################################################
'''""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
This class will query Google's search engine and return the resulting
HTML page.
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""'''
class GoogleQuerier(object):
GOOGLE_URL = 'https://www.google.com/search?client=safari&rls=en&q=%(query)s&ie=UTF-8&oe=UTF-8&num=%(count)s'
USER_AGENT = 'Mozilla/5.0 (X11; U; FreeBSD i386; en-US; rv:1.9.2.9) Gecko/20100913 Firefox/3.6.9'
def __init__(self, count=10):
# Google doesn't support more than 100 results per page
self.count = min(count, 100)
self.opener = build_opener(HTTPCookieProcessor(CookieJar()))
def query(self, query):
url = self.GOOGLE_URL % {'query': quote(encode(query)), 'count': str(self.count)}
timeout = 3# number of tries before erroring out
while timeout > 0:
try:
return self.opener.open(Request(url=url, headers={'User-Agent': self.USER_AGENT})).read()
except KeyboardInterrupt:
raise
except:
timeout -= 1
if timeout > 0:
time.sleep(5)
return None
#################################################################################################
class Result(object):
def __init__(self):
self.url = ''
self.title = ''
self.summary = ''
self.full_text = ''
#################################################################################################
'''""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
This class will parse the HTML of a page returned by Google's search
engine.
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""'''
class GoogleParser(object):
def __init__(self, quiet, verbose, forbidden_phrases):
self.soup = None
self.quiet = quiet
self.verbose = verbose
self.forbidden_url_phrases = forbidden_phrases
self.visited_urls = []
def parse_results_page(self, html):
results = []
if html:
self.soup = BeautifulSoup(html)
i = 1
for result in self.soup.findAll(GoogleParser.is_result):
parsed_result = self.parse_result(result, i)
if parsed_result == -1:
i -= 1
elif parsed_result:
results.append(parsed_result)
self.visited_urls.append(parsed_result.url)
i += 1
if not self.quiet:
print ' Total Results Parsed:\t' + str(len(results))
elif not self.quiet:
print ' COULD NOT COMPLETE REQUEST'
return results
# return value of -1 means the tag was not a webpage result (usually a collection of images that Google adds)
# return value of None means that the associated URL either contained a forbidden word or has already been mined
def parse_result(self, outer_tag, i):
result = Result()
result.title = ''.join(outer_tag.h3.a.findAll(text=True))
result.url = outer_tag.h3.a['href']
if result.url in self.visited_urls:
if not self.quiet and self.verbose:
print ' ' + str(i) + ')' + ' '*(4 - len(str(i))) + 'REPEAT:\t' + result.url
return None
if result.url.startswith('/url?q='):
index = result.url.find('&sa=')
result.url = result.url[7:index]
for phrase in self.forbidden_url_phrases:
if result.url.lower().find(phrase.lower()) > -1:
if not self.quiet and self.verbose:
print ' ' + str(i) + ')' + ' '*(4 - len(str(i))) + 'UNWANTED:\t' + result.url
return None
try:
URL(result.url).open()
except:
index = result.url.find('%')
if index > -1:
result.url = result.url[:index]
try:
URL(result.url).open()
except:
if not self.quiet and self.verbose:
print ' ' + str(i) + ')' + ' '*(4- len(str(i))) + 'UNABLE TO REACH:\t' + result.url
return None
else:
# tag does not represent a proper result
return -1
# result.summary = ''.join(outer_tag.div.span.findAll(text=True))
url = result.url
result = self.parse_full_text(result)
if not self.quiet and self.verbose:
if not result:
print ' ' + str(i) + ')' + ' '*(4 - len(str(i))) + 'UNABLE TO DOWNLOAD:\t' + url
else:
print ' ' + str(i) + ')' + ' '*(4 - len(str(i))) + result.title + '\n ' + url
return result
@staticmethod
def parse_full_text(result):
try:
if result.url.endswith('.pdf'):
result = GoogleParser.parsePDF(result)
elif not result.url.endswith('.ppt'):
result.full_text = unicodedata.normalize('NFKD', plaintext(URL(result.url).open().read())).encode('ascii', 'ignore')
except:
return None
return result
@staticmethod
def parsePDF(result):
f = open('/tmp/temp.pdf', 'w')
f.write(URL(result.url).download())
f.close()
f = open('/tmp/temp.pdf', 'rb')
rsrcmgr = PDFResourceManager(caching=True)
outfp = file('/tmp/temp-pdf.txt', 'w')
device = TextConverter(rsrcmgr, outfp, codec='utf-8', laparams=LAParams(), imagewriter=None)
# parse the PDF document
interpreter = PDFPageInterpreter(rsrcmgr, device)
for page in PDFPage.get_pages(f, set(), maxpages=0, password='', caching=True, check_extractable=True):
interpreter.process_page(page)
f.close()
device.close()
outfp.close()
# read in the resulting text
f = open('/tmp/temp-pdf.txt', 'r')
result.full_text = f.read()
f.close()
# remove the temporary files
os.system('rm -f /tmp/temp.pdf /tmp/temp-pdf.txt')
return result
@staticmethod
def tag_has_class(tag, klass):
"""
This predicate function checks whether a BeatifulSoup Tag instance
has a class attribute.
"""
res = tag.get('class') or []
if type(res) != list:
# BeautifulSoup 3 can return e.g. 'gs_md_wp gs_ttss',
# so split -- conveniently produces a list in any case
res = res.split()
return klass in res
@staticmethod
def is_result(tag):
return tag.name == 'li' and GoogleParser.tag_has_class(tag, 'g')
#################################################################################################
'''""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
Randomly pick a key in the specified dictionary based on the weight
of each key's value.
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""'''
def weightedRandom(dictionary, total_weight):
# scramble the internal state of the random number generator
random.jumpahead(random.randint(0, 9999999999))
rand = random.uniform(0, total_weight)
sum = 0.0
items = dictionary.items()
# shuffle the items to avoid an unfair advantage to the keys that
# appear earlier in the dictionary
random.shuffle(items)
for key, weight in items:
sum += weight
if rand < sum:
return key
return key
#################################################################################################
'''""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
Generates a (n word tuple: count) dictionary from a list of text
files. Text files must be only alphabetic characters and white space.
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""'''
def getCounts(seed_file, n):
ngrams = {}
f = open(seed_file, 'r')
for line in f:
line = line.rstrip()
wordList = line.split()
for i in range(len(wordList) - n + 1):
gram = tuple(wordList[i:i+n])
if gram in ngrams:
ngrams[gram] += 1
else:
ngrams[gram] = 1
f.close()
return ngrams
#################################################################################################
'''"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
Return the total count of all n-grams.
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""'''
def getTotalCount(dictionary):
sortedDict = sorted(dictionary.iteritems(), key=operator.itemgetter(1), reverse=True)
count = 0
for entry in sortedDict:
count += entry[1]
return count
#################################################################################################
def getDictCtSafe(dict, entry):
if entry in dict:
return dict[entry]
else :
return 0
#################################################################################################
'''"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
t_one:
measures the decrease in probability mass resulting from adding more
words
t_two:
measures the seed weighted improvement in probability for words in
the current sentence
if t_one < t_two the relative entropy is decreased (keep the sentence)
See "Selecting relevant text subsets from web-data for building topic
specific language models" for further reference. This algorithm is
roughly based on one described in that research paper, but is expanded
to filter on trigram counts rather than unigram counts.
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""'''
def incrementalFilter(seed_file, previously_mined, mined_text, quiet):
p = getCounts(seed_file, 3)
w = getCounts(seed_file, 3)
n = getTotalCount(w)
output = ''
# add the seed sentences
f = open(seed_file, 'r')
lines = f.read().splitlines()
f.close()
# add the previously mined sentences
if previously_mined:
f = open(previously_mined, 'r')
lines.extend(f.read().splitlines())
f.close()
# add the mined sentences
lines.extend(mined_text.splitlines())
# delete duplicates, then shuffle
lines = list(set(lines))
random.seed()
random.shuffle(lines)
size = 0
# i is an arbitrary scalar added to t_one as 1/i.
# this makes filtering more strict with larger i values.
for i in range(11,13):
if not quiet:
print ' Iteration ' + str(i - 10)
removeList = []
for line in lines:
removeList.append(line)
line = line.strip()
wordList = line.split()
linegrams = {}
# populate linegrams with the current line
for j in range(len(wordList) - 3 + 1):
gram = tuple(wordList[j:j+3])
if gram in linegrams:
linegrams[gram] += 1
else:
linegrams[gram] = 1
# the last term of t_one is an arbitrary scalar to make the
# filtering more strict. it can be anything.
t_one = log10(float(n + len(wordList))/float(n)) + 1.0/float(i)
t_two = 0.0
for gram in linegrams:
if gram in w:
t_two = t_two + log10(float(w[gram] + linegrams[gram])/float(w[gram])) * float(getDictCtSafe(p,gram))
#TODO: revisit this. it doesn't work as is, but I would like to add extra weight on oov.
#else:
# #place extra weight on introducing new words to vocab
# t_two = t_two + 50.0
if t_one < t_two:
for gram in linegrams:
if gram in w:
w[gram] += 1
else:
w[gram] = 1
output += line + '\n'
size = size + len(line)
else:
removeList.pop()
# if not quiet:
# print ' ' + str(len(removeList)) + " sentences added"
# print ' ' + str(len(lines)) + " sentences before filter"
# remove all lines that have been added to output file
# lines = filter (lambda a: removeList.count(a) == 0, lines)
# if not quiet:
# print ' ' + str(len(lines)) + " sentences after filter"
return output
#################################################################################################
def nonincrementalFilter(seed_file, previously_mined, mined_text, quiet):
p = getCounts(seed_file, 3)
w = getCounts(seed_file, 3)
n = getTotalCount(w)
output = ''
# add the seed sentences
f = open(seed_file, 'r')
lines = f.read().splitlines()
f.close()
# add the previously mined sentences
if previously_mined:
f = open(previously_mined, 'r')
lines.extend(f.read().splitlines())
f.close()
# add the mined sentences
lines.extend(mined_text.splitlines())
# delete duplicates, then shuffle
lines = list(set(lines))
random.seed()
random.shuffle(lines)
for line in lines:
line = line.strip()
wordList = line.split()
linegrams = {}
for i in range(len(wordList) - 3 + 1):
gram = tuple(wordList[i:i+3])
if gram in linegrams:
linegrams[gram] += 1
else:
linegrams[gram] = 1
t_one = log10(float(n + len(wordList))/float(n))
t_two = 0.0
for gram in linegrams:
if gram in w:
t_two = t_two + log(float(w[gram] + linegrams[gram])/float(w[gram])) * float(p[gram])
#TODO: revisit this. it doesn't work as is, but I would like to add extra weight on oov.
#else:
# #place extra weight on introducing new words to vocab
# t_two = t_two + 50.0
if t_one < t_two:
output += line + '\n'
return output
#################################################################################################
units = ["", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE "]
teens = ["", "ELEVEN", "TWELVE", "THIRTEEN", "FOURTEEN", "FIFTEEN", "SIXTEEN", "SEVENTEEN",
"EIGHTEEN", "NINETEEN"]
tens = ["", "TEN", "TWENTY", "THIRTY", "FORTY", "FIFTY", "SIXTY", "SEVENTY", "EIGHTY", "NINETY"]
thousands = ["","THOUSAND", "MILLION", "BILLION", "TRILLION", "QUADRILLION", "QUINTILLION",
"SEXTILLION", "SEPTILLION", "OCTILLION", "NONILLION", "DECILLION", "UNDECILLION",
"DUODECILLION", "TREDECILLION", "QUATTUORDECILLION", "SEXDECILLION", "SEPTENDECILLION",
"OCTODECILLION", "NOVEMDECILLION", "VIGINTILLION "]
def numToWordString(numStr):
# remove any superfluous leading zeros
decimal_index = numStr.find('.')
if decimal_index > 0:
start = numStr.find('-') + 1
if decimal_index - start > 1:
numStr = str(int(numStr[start:decimal_index])) + numStr[decimal_index:]
if start == 1:
numStr = '-' + numStr
elif decimal_index == -1:
start = numStr.find('-') + 1
numStr = str(int(numStr[start:]))
if start == 1:
numStr = '-' + numStr
words = []
if numStr[0] == '-':
words.append('NEGATIVE')
numStr = numStr[1:]
if numStr == '0' or numStr == '0.0':
words.append("ZERO")
else:
decimal_point_index = numStr.find('.')
decimalStr = None
if decimal_point_index > -1:
decimalStr = numStr[decimal_point_index + 1:]
numStr = numStr[:decimal_point_index]
numStrLen = len(numStr)
groups = (numStrLen + 2) / 3
numStr = numStr.zfill(groups * 3)
for i in range(0, groups*3, 3):
h = int(numStr[i])
t = int(numStr[i+1])
u = int(numStr[i+2])
g = groups - (i / 3 + 1)
if h >= 1:
words.append(units[h])
words.append("HUNDRED")
if t > 1:
words.append(tens[t])
if u >= 1:
words.append(units[u])
elif t == 1:
if u >= 1:
words.append(teens[u])
else:
words.append(tens[t])
else:
if u >= 1:
words.append(units[u])
if g >= 1 and (h + t + u) > 0:
try:
words.append(thousands[g])
except:
print 'ERROR:\twords.append(thousands[' + str(g) + '])\t'
print words
print numStr
if decimalStr:
words.append('POINT')
for i in range(0, len(decimalStr)):
digit = int(decimalStr[i])
if digit == 0:
words.append('ZERO')
else:
words.append(units[digit])
return ' '.join(words)
#################################################################################################
months = ['JANUARY', 'FEBRUARY', 'MARCH', 'APRIL', 'MAY', 'JUNE', 'JULY', 'AUGUST', 'SEPTEMBER',
'OCTOBER', 'NOVEMBER', 'DECEMBER']
days = ['FIRST', 'SECOND', 'THIRD', 'FOURTH', 'FIFTH', 'SIXTH', 'SEVENTH', 'EIGHTH', 'NINETH',
'TENTH', 'ELEVENTH', 'TWELFTH', 'THIRTEENTH', 'FOURTEENTH', 'FIFTEENTH', 'SIXTEENTH',
'SEVENTEENTH', 'EIGHTEENTH', 'NINETEENTH', 'TWENTIETH', 'TWENTY FIRST', 'TWENTY SECOND',
'TWENTY THIRD', 'TWENTY FOURTH', 'TWENTY FIFTH', 'TWENTY SIXTH', 'TWENTY SEVENTH',
'TWENTY EIGTH', 'TWENTY NINTH', 'THIRTIETH', 'THIRTY FIRST']
# currently, this method returns the empty string if the date string does not follow MONTH DAY YEAR ordering
def replaceDate(date):
replacement = ''
index = date.find('-')
separator = '/'
if index < 0:
index = date.find('/')
if index < 0:
index = date.find('\\')
separator = '\\'
else:
separator = '/'
# month
number = int(date[:index])
if number < 1:
return ''
if number > 12:
return ''
replacement = months[number - 1] + ' '
# day
rindex = date.rfind(separator)
if rindex <= index:
return ''
number = int(date[index + 1:rindex])
if number < 1:
return ''
if number > 31:
return ''
replacement += days[number - 1] + ' '
#year
index = date.rfind(separator) + 1
number = date[index:]
if len(number) == 2:
if number[0] == '0':
if number[1] == '0':
replacement += 'TWO THOUSAND'
else:
replacement += 'O '
replacement += units[int(number[1])]
else:
replacement += numToWordString(number)
else:
replacement += numToWordString(number[:2])
replacement += numToWordString(number[2:])
return replacement
#################################################################################################
def replaceTime(time):
midnight_re = re.compile(r'((12)|(00)):00( ?(AM)|(A))')
if midnight_re.match(time):
return 'TWENTY FOUR HUNDRED'
replacement = ''
colon_index = time.find(':')
hours = time[:colon_index]
if time.find('P') > -1:
hours = str(int(hours) + 12)
time = hours + time[colon_index:]
colon_index = time.find(':')
# hours
version = None
if colon_index == 1 or time[0] == '0':
version = random.randint(0,100) % 2
if version == 0:
replacement += 'O '
else:
replacement += 'ZERO '
if time[0] != '0':
replacement += units[int(time[0])] + ' '
if time[1] == '0':
if version == 0:
replacement += 'O '
else:
replacement += 'ZERO '
elif time[1] != ':':
replacement += units[int(time[1])] + ' '
else:
replacement += numToWordString(hours) + ' '
# minutes
time = re.sub(r'[A-Z ]', '', time)
if time[colon_index + 1:] == '00':
return replacement + 'HUNDRED'
elif time[colon_index + 1] == '0':
if not version:
version = random.randint(0,100) % 2
if version == 0:
replacement += 'O '
else:
replacement += 'ZERO '
colon_index += 1
return replacement + numToWordString(str(int(time[colon_index + 1:])))
#################################################################################################
def main():
rows, columns = os.popen('stty size', 'r').read().split()
usage = """python mineGoogle.py [options]
A tool for getting additional data relevant to a topic as
represented in an ARPA file and a set of seed sentences."""
fmt = optparse.IndentedHelpFormatter(max_help_position=int(columns) - 50, width=int(columns))
parser = optparse.OptionParser(usage=usage, formatter=fmt)
# add options to the option parser
parser.add_option('-i', '--input', help='ARPA file to use. This helps determine the weighted random trigram search queries. ["input.arpa"]')
parser.add_option('-s', '--seed', help='File containing seed sentences to use. ["seedsentences"]')
parser.add_option('-o', '--original', help='Append the downloaded text (pre-processed) to the end of the specified file.')
parser.add_option('-c', '--cleaned', help='Append the downloaded text (post-cleaning , pre-filtering) to the end of the specified file.')
parser.add_option('-a', '--append', help='Append the useful sentences to the end of the specified file. If not specified, console will be used.')
parser.add_option('-U', '--store-urls', help='Store the URLs visited in this file. [WARNING] This will overwrite the contents of the specified file.')
parser.add_option('-f', '--forbidden-urls', help='File containing phrases that cannot appear in an acceptable URL.')
parser.add_option('-C', '--common', help='File containing a list of common words to help filter search queries. If a query contains only words from this list, it will be ignored.')
parser.add_option('-p', '--prev-mined', action='store_true', help='Inclued the previously mined sentences in the entropy calculations.')
parser.add_option('-e', '--experimental', type='int', help='Use the unigram probabilities to further weed out bad search queries. The integer is the minimum number of std deviations away from the highest probability.')
parser.add_option('-n', '--nonincremental', action='store_true', help='Use non-incremental filtering algorithm for filtering out junk sentences. Default is incremental.')
parser.add_option('-r', '--results', type='int', help='The number of results to use per query. [15]')
parser.add_option('-Q', '--queries', type='int', help='The number of queries to run. [100]')
parser.add_option('-A', '--all-queries', action='store_true', help='Run every trigram query that passes query filtering. This option precludes the option "-Q"')
parser.add_option('-t', '--trigrams', help='Write all of the trigram search queries that remain after query filtering to the specified file along with their probabilities.')
parser.add_option('-S', '--search-file', help='File containing additional search queries to perform.')
parser.add_option('-F', '--search-file-only', help='File containing search queries to perform. This option precludes any combination of options: -i -C -e -Q -S -u -A')
parser.add_option('-u', '--urls', help='File containing a list of additional URLs to mine.')
parser.add_option('-O', '--urls-only', help='File containing a list of URLs to mine. This option precludes any combination of options: -i -C -e -r -Q -S -u -U -F -f -A')
parser.add_option('-q', '--quiet', action='store_true', help='Quiet mode. Precludes -v option.')
parser.add_option('-v', '--verbose', action='store_true', help='Verbose mode.')
parser.set_defaults(input='input.arpa',
seed='seedsentences',
original=None,
cleaned=None,
append=None,
store_urls=None,
forbidden_urls=None,
common=None,
prev_mined=None,
experimental=None,
nonincremental=None,
results=15,
queries=100,
trigrams=None,
all_queries=None,
search_file=None,
search_file_only=None,
urls=None,
urls_only=None,
quiet=None,
verbose=None)
options, args = parser.parse_args()
# clean up
del fmt
del parser
del rows
del columns
if not options.search_file_only and not options.urls_only:
# read forbidden URL phrases
forbidden_url_phrases = []
if options.forbidden_urls:
if not options.quiet:
print 'Reading forbidden URL phrases'
infile = open(options.forbidden_urls, 'r')
for line in infile:
forbidden_url_phrases.append(line.strip())
if options.common:
common_words = []
if not options.quiet:
print 'Reading common words file'
infile = open(options.common, 'r')
for line in infile:
common_words.append(line.strip())
# read in the ARPA file
dictionary = dict()
unigrams = dict()
if not options.quiet:
print 'Reading ARPA file'
infile = open(options.input, 'r')
for line in infile:
if line.startswith('\\1'):
break
if options.experimental or options.common:
for line in infile:
entry = line.strip().split()
if len(entry) == 0:
break
unigrams[entry[1]] = pow(10, float(entry[0]))
# experimental - if all 3 words in a trigram entry are less than
# 1.5 standard deviations away from the highest probability
if options.experimental:
if not options.quiet:
print 'Performing experimental unigram removal'
# calculate the standard deviation of the unigram probabilities
mean = 0
for entry in unigrams:
mean += unigrams[entry]
mean /= len(unigrams)
std_dev = 0
for entry in unigrams:
std_dev += pow(unigrams[entry] - mean, 2)
std_dev = sqrt(std_dev / len(unigrams))
# get the highest probability in the unigrams
sorted_probs = sorted(unigrams.iteritems(), key=operator.itemgetter(1))
high = sorted_probs[len(sorted_probs) - 1][1]
# talk to the user
if not options.quiet and options.verbose:
print ' MEAN UNIGRAM PROBABILITY: \t' + str(mean)
print ' STANDARD DEVIATION UNIGRAM PROBABILITY:\t' + str(std_dev)
print ' HIGHEST UNIGRAM PROBABILITY: \t' + str(high)
# remove all unigrams that are less than 1.5 standard deviations
# away from the highest probability unigram
grams = unigrams.keys()
for entry in grams:
if high - unigrams[entry] < options.experimental * std_dev:
# if not options.quiet:
# print ' - IGNORING UNIGRAM:\t' + entry + ' '*(20-len(entry)) + str(unigrams.pop(entry))
# else:
unigrams.pop(entry)
# clean up
del high
del std_dev
del mean
del sorted_probs
if options.common:
if not options.quiet:
print 'Performing common word removal'
for word in common_words:
if word in unigrams:
if not options.quiet and options.verbose:
print ' IGNORING WORD:\t' + word + ' '*(50-len(word)) + str(unigrams.pop(word))
else:
unigrams.pop(word)
del common_words
for line in infile:
if line.startswith('\\3'):
break
if not options.quiet:
print 'Reading in valid trigram search queries'
trigrams_ignored = 0
total_trigrams = 1
for line in infile:
if line.startswith('-'):
entry = line.strip().split()
if entry[1] != '<s>':# can't represent beginning of sentence in a search
if options.experimental or options.common:
if entry[1] in unigrams or entry[2] in unigrams or entry[3] in unigrams:
dictionary[tuple(entry[1:4])] = pow(10, float(entry[0]))
elif not options.quiet:
trigrams_ignored += 1
# print ' - IGNORING TRIGRAM:\t' + str(entry[1:4]) + ' '*(35-len(str(entry[1:4]))) + str(pow(10, float(entry[0])))
else:
dictionary[tuple(entry[1:4])] = pow(10, float(entry[0]))
total_trigrams += 1
infile.close()
if not options.quiet and options.verbose:
print ' Total Queries Before Filtering: ' + str(total_trigrams)
print ' - Total Queries Filtered: ' + str(trigrams_ignored)
print ' ----------------------------------' + '-' * len(str(total_trigrams))
print ' Total Queries After Filtering: ' + str(len(dictionary))
# clean up
del total_trigrams
del trigrams_ignored
del infile
del unigrams
# change the probability distribution so that words that are in the middle
# are more likely to be picked for querying. the idea is that high-probability
# trigrams are just commonly occurring to every subject and low-probability
# ones are not very representative of the topic.
# use the median as the middle to be more robust against outliers
if not options.quiet:
print 'Calculating query probabilities'
sorted_probs = sorted(dictionary.iteritems(), key=operator.itemgetter(1))
median_prob = sorted_probs[int(len(sorted_probs)/2)][1]
for key, value in dictionary.iteritems():
if median_prob - value == 0:
dictionary[key] = -1
else:
dictionary[key] = 1 / abs(median_prob - value)
# get the highest value after the median
sorted_probs = sorted(dictionary.iteritems(), key=operator.itemgetter(1))
next_highest = sorted_probs[len(sorted_probs) - 1][1]
# estimate the approximate value for the median
estimated_value = 1.5 * next_highest# arbitrary scalar chosen
# set the keys with median value to the estimated value
for key, value in dictionary.iteritems():
if value == -1:
dictionary[key] = estimated_value # .05 * estimated_value
# dictionary[key] = .95 * estimated_value - dictionary[key]
# TODO: look into further modifying probability distribution
# based on trigrams with the highest amount of entropy
if options.trigrams:
if not options.quiet:
print 'Writing remaining trigrams to file'
trigrams_file = open(options.trigrams, 'w')
sorted_trigrams = sorted(dictionary.iteritems(), key=operator.itemgetter(1))
for trigram in sorted_trigrams:
trigrams_file.write(str(trigram[0]) + ' '*(50-len(str(trigram[0]))) + str(trigram[1]) + '\n')
trigrams_file.close()
del trigrams_file
random.seed()
# add up all the weights in the dictionary
total_weight = 0.0
for key, value in dictionary.iteritems():
total_weight += value
# make sure that all queries are ran if the user wants
if options.all_queries:
options.queries = len(dictionary)
# run the queries
if not options.quiet:
print 'Running queries'
results = []
querier = GoogleQuerier(options.results)
parser = GoogleParser(options.quiet, options.verbose, forbidden_url_phrases)
for i in range(0, options.queries):
# select the next query, replacing any ending "</s>" token with a period
entry = weightedRandom(dictionary, total_weight)
dictionary.pop(tuple(entry))# avoid using the same query twice
q = '"' + re.sub(r'((\bU S\b)|((?<!\')\bS))\b', 'U.S.', ' '.join(entry).replace(' </s>', '.')) + '"'
q = re.sub(r'\bO TWO\b', 'O2', q)
q = re.sub(r'\bSPO TWO\b', 'SPO2', q)
if not options.quiet:
print ' Performing Query ' + str(i + 1) + ':\t' + q
# perform the next query
results.extend(parser.parse_results_page(querier.query(q)))
if len(dictionary) == 0:
print ' Ran out of trigram queries'
break
del dictionary
# perform custom queries
if options.search_file:
if not options.quiet:
print 'Running additional queries'
search_file = open(options.search_file, 'r')
elif options.search_file_only:
results = []
querier = GoogleQuerier(options.results)
parser = GoogleParser(options.quiet, options.verbose, [])
if not options.quiet:
print 'Running custom queries'
search_file = open(options.search_file_only, 'r')
i = 1
if options.search_file or options.search_file_only:
for line in search_file:
line = '"' + line.strip() + '"'
if not options.quiet:
print ' Performing Query ' + str(i) + ':\t' + line
# perform the next query
results.extend(parser.parse_results_page(querier.query(line)))
i += 1
search_file.close()
del search_file
# output the urls visited if user requested to do so
if options.store_urls:
if not options.quiet:
print 'Writing visited urls to file'
out = open(options.store_urls, 'w')
for url in parser.visited_urls:
out.write(url + '\n')
out.close()
del out
# parse specified urls
if options.urls_only:
results = []
querier = GoogleQuerier(options.results)
parser = GoogleParser(options.quiet, forbidden_url_phrases)
if not options.quiet:
print 'Parsing urls'
urls_file = open(options.urls_only, 'r')
elif options.urls:
if not options.quiet:
print 'Parsing additional urls'
urls_file = open(options.urls, 'r')
if options.urls_only or options.urls:
for line in urls_file:
if not options.quiet:
if result.url in parser.visited_urls:
print ' SKIPPING REPEAT URL:\t' + line
else:
print ' Parsing ' + line
result = Result()
result.url = line
result = GoogleParser.parse_full_text(result)
if result:
results.append(result)
del result
urls_file.close()
del urls_file
del parser
del querier
# concatenate all of the mined text
print 'Concatenating mined text'
mined_text = ''
for result in results:
mined_text += result.full_text + '.'
# clean up
del results
# append the pre-processed text to the specified file
if options.original:
if not options.quiet:
print 'Appending pre-processed text to requested file'
original_file = open(options.original, 'a')
original_file.write(mined_text)
original_file.close()
del original_file
# replace unicode hyphens with ASCII hyphen
mined_text = re.sub(r'–|—|−', '-', mined_text)
# capitalize everything
if not options.quiet:
print 'Cleaning up mined text'
print ' Capitalizing text'
mined_text = mined_text.upper()
# remove newlines
mined_text = re.sub(r'\n', ' ', mined_text)
mined_text = re.sub(r'\r', ' ', mined_text)
# remove wikipedia references
mined_text = re.sub(r'\[[0-9]+\]', '', mined_text)
mined_text = re.sub(r'\[EDIT\]', '', mined_text)
# make each interjection a new sentence w/o splitting the rest of the sentence