-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile_upload.py
1465 lines (1318 loc) · 46.2 KB
/
file_upload.py
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import codecs
import io
import os
import pickle as pickle
import re
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
sys.path.append("./static/py")
import docx
# import matplotlib.pyplot as plt
import numpy as np
# import pandas as pd
import PyPDF2
# import simplejson as json
import json
from flask import *
from flask_babel import Babel
# from lxml import etree, html
from lz4.frame import compress, decompress
# import gzip
from nltk import word_tokenize
# from pathlib2 import Path
from sklearn.feature_extraction.text import CountVectorizer
import common as cm
import constants as CONST
import db
import erudit_corpus as corpus
import erudit_parser as erudit
import oht
import pickle_session as ps
import topic_model as tm
app = Flask(__name__)
app.config["UPLOAD_FOLDER"] = CONST.UPLOAD_FOLDER
app.secret_key = "super secret key"
app.config["SESSION_TYPE"] = "filesystem"
app.session_interface = ps.PickleSessionInterface("./app_session")
babel = Babel(app)
# Common variables
oht_wrapper = oht.Wrapper()
db = db.Database()
aStopWord = []
results = db.execQuery(
"select lower(word) word, treetag from stopword where dataset=%s", ("adam2",)
)
for result in results:
aStopWord.append(result[0].strip())
aStopWord = set(aStopWord)
tm = tm.TopicModel(stop_words=aStopWord)
# tm.tfidf_vect.fit(tm.tf)
# print("gzipping")
# with gzip.open("./model/tm.gzip", 'wb') as f:
# pickle.dump(tm, f, -1)
# print("done")
# with open("./model/tm.pkl", "w+") as f:
# pickle.dump(tm, f)
# print("loading again")
tm = cm.load_zipped_pickle("./model/tm.gzip")
tm.loadModel()
# with open("./model/pkl/tm.pkl", "r") as f:
# tm = pickle.load(f)
strPath = "/Users/jayrsawal/Documents"
# Select the language to use
@babel.localeselector
def get_locale():
if request.cookies.get("selected-language", None):
language = request.cookies.get("selected-language")
else:
language = request.accept_languages.best_match(CONST.LANGUAGES)
return language
# Return the list of languages available when requested
@app.route("/api/languages", methods=["GET"])
def get_languages():
return jsonify(CONST.LANGUAGES)
@app.route("/")
def index():
return render_template("index.html")
@app.route("/journal")
def journal():
return render_template("journal.html")
@app.route("/journal/analyzer")
def journal_analyzer():
""" Web hook for main document analyzer page """
# we have 4 options here
# 0. Default - After uploading a file, go here to analyze
# 2. Recover Document - Load a previously used document
# 3. Recover Search - Load a previously used search query
dochash_id = request.args.get("dochashid")
if dochash_id is not None:
recoverDocumentTfidf(dochash_id)
total_start = time.time()
search = getJournalSearchResults(session["tfidf"], 999)
search = [row for row in search]
search[0] = search[0] + (1,)
# otherwise, our search will be done dynamically through client
total_end = time.time()
print(("Total Time: %s seconds" % (total_end - total_start)))
return render_template("journal_analyzer.html", journal_list=search)
@app.route("/journal/documents")
def journal_view():
""" Web hook for viewing the documents in a journal """
journal_id = request.args.get("id")
if journal_id is None:
return redirect(url_for("index"))
results = db.execQuery(
"""
select documentid, 0
from meta where journalid=%s limit 100""",
(journal_id,),
)
documents = getSearchMetaInfo(results, [])
return render_template("journal_view.html", doc_list=documents)
@app.route("/document/keywords/<doc_id>", methods=["GET"])
def getKeywords(doc_id):
""" Get a keyword list for a single document """
results = db.execQuery(
"""select d.termid, d.word
, d.tfidf, t.headingid
from doctfidf d
left join tfidf t on t.termid=d.termid
where d.documentid=%s
order by d.tfidf desc""",
(doc_id,),
)
used_terms = []
keywords = []
i = 0
for topic in results:
if topic[1] in used_terms:
continue
i += 1
used_terms.append(topic[1])
temp = {}
temp["id"] = topic[0]
temp["name"] = topic[1]
temp["dist"] = topic[2]
temp["heading_id"] = topic[3]
temp["rank"] = i
keywords.append(temp)
return jsonify(keywords)
@app.route("/upload", methods=["GET", "POST"])
def upload():
""" Document upload web hook """
if request.method == "POST":
file = request.files["file"]
# make sure upload is support file type
if file and cm.isSupportedFile(file.filename):
strText = extractTextFromUpload(file)
if strText == "":
return
# remove stopwords
strText = tm.removeStopWords(strText)
# hash the text and look for any matches in db
strHash = cm.getSHA256(strText)
aHash = db.execQuery(
"""
select d.id, t.termid, t.word, udt.tf, udt.idf, udt.tfidf
from dochash d
left join userdoctfidf udt on udt.dochashid=d.id
left join tfidf t on t.id=udt.termid
where d.hashkey=%s""",
(strHash,),
)
if len(aHash) > 1:
# we have a match - recover it
tfidf = recoverDocumentTfidf(aHash[0][0])
else:
# no match, save this to the db for future reference
user_ip = request.environ["REMOTE_ADDR"]
doc_name = file.filename
db.execUpdate(
"""insert into dochash(ipaddr, hashkey, docname)
values(%s, %s, %s)""",
(user_ip, strHash, doc_name),
)
dochash_id = db.execQuery(
"""
select id from dochash where hashkey=%s
order by created desc limit 1""",
(strHash,),
)[0][0]
session["dochashid"] = dochash_id
# preprocess text
strClean = tm.preProcessText(strText.decode("utf8"))
# transform to model
tfidf = tm.transformTfidf(strClean)
session["tfidf"] = tfidf
for idx in tfidf:
db.execUpdate(
"""
insert into userdoctfidf(dochashid, termid, tf, idf, tfidf)
values(%s, %s, %s, %s, %s);
""",
(
dochash_id,
idx,
tfidf[idx]["tf"],
tfidf[idx]["idf"],
tfidf[idx]["tfidf"],
),
)
# add data to session for later
key_term = oht_wrapper.getTfidfHeadingList(tfidf)
session["keyterm"] = key_term
search_term = [term for term in key_term[: CONST.DS_MAXTOPIC]]
session["searchterm"] = search_term
session["tierindex"] = oht_wrapper.getTierIndexIntersection(search_term)
return redirect(url_for("index"))
@app.route("/search", methods=["POST"])
def search():
""" Web hook for document search """
# accepts either a search_id, or a json list of headings/keywords
content = request.get_json()
user_ip = request.environ["REMOTE_ADDR"]
search_id = None
if "search_id" in content:
search_id = content["search_id"]
# if not a previous search, save this search to search history
if search_id is None:
# use session based queries
cursor = db.beginSession()
result = db.execSessionQuery(
cursor,
"""
insert into search(ipaddr)
values(%s);
""",
(user_ip,),
)
# get last inserted record in session
result = db.execSessionQuery(
cursor,
"""
select last_insert_id();
commit;
""",
close_cursor=True,
)
search_id = result[0][0]
term_list = []
clean_list = []
must_include = []
if len(content["keyword_list"]) > 0:
# get all keywords
for k in content["keyword_list"]:
# clean_word = re.sub('[^A-Za-z0-9]+', '', k["keyword"])
clean_word = k["keyword"]
clean_list.append(clean_word)
term_list.append(k["term_id"])
try:
int(k["heading_id"])
except ValueError:
k["heading_id"] = None
if "search_id" not in content:
db.execQuery(
"""insert into searchterm(searchid, keyword, weight, rank, headingid)
values(%s, %s, %s, %s, %s); commit;""",
(search_id, k["keyword"], k["weight"], k["order"], k["heading_id"]),
)
if k["must_include"]:
must_include.append(clean_word)
# find matches in the corpus
rank_list = corpus.matchKeyword(clean_list, 50, must_include)
# attach meta info for display on the documents
search = getSearchMetaInfo(rank_list, clean_list, must_include)
return json.dumps(search)
@app.route("/searchkeyword", methods=["POST"])
def searchkeyword():
""" Web hook for searching OHT for matching topics on keywords """
content = request.get_json()
search = oht_wrapper.getKeywords(content["data"])
return json.dumps(search)
@app.route("/analyzer")
def analyzer():
""" Web hook for main document analyzer page """
# we have 4 options here
# 0. Default - After uploading a file, go here to analyze
# 1. Quick Search - single keyword document search
# 2. Recover Document - Load a previously used document
# 3. Recover Search - Load a previously used search query
quick_search = request.args.get("quicksearch")
dochash_id = request.args.get("dochashid")
search_id = request.args.get("searchid")
if dochash_id is not None:
recoverDocumentTfidf(dochash_id)
# nothing to load - return to home page
if dochash_id is None and quick_search is None and search_id is None:
return redirect(url_for("index"))
total_start = time.time()
search = None
search_term = None
key_term = None
tier_index = None
if quick_search is None and search_id is None:
# if we are searching using a document - get results
search_term = session["searchterm"]
key_term = session["keyterm"]
tier_index = session["tierindex"]
clean_list = []
# if len(search_term) > 0:
# # get all keywords
# for k in search_term:
# clean_list.append(k["name"])
# search = getSearchResults(session["tfidf"], clean_list)
# otherwise, our search will be done dynamically through client
total_end = time.time()
print(("Total Time: %s seconds" % (total_end - total_start)))
return render_template(
"analyzer.html",
search_result=search,
search_term=search_term,
key_term=key_term,
tier_index=tier_index,
)
@app.route("/oht")
@app.route("/oht/<tier_index>")
def oht_csv(tier_index=None):
""" Web hook for retrieving OHT tree based off tier index """
if tier_index is None:
return Response(oht_wrapper.csv(), mimetype="text/csv")
csv = oht_wrapper.getTierIndexChildren(tier_index)
return Response(csv, mimetype="text/csv")
@app.route("/oht/synset/<heading_id>")
def oht_synset(heading_id):
""" Web hook for retrieving a word heading synset """
if heading_id == "null":
heading_id = 181456
heading = oht.Heading(heading_id)
words = heading.Synset()
pos = heading.PartOfSpeech()
response = {
"id": heading_id,
"name": heading.fr,
"tier_index": heading.tierindex,
"words": words,
"pos": filterOHTHeadingList(pos),
}
return jsonify(response)
@app.route("/oht/tier/<tier_index>")
def oht_tier(tier_index):
return jsonify(oht_wrapper.getTierIndexTrio(tier_index))
@app.route("/erudit/journal_count", methods=["POST"])
def erudit_journal():
""" Get over-arching journal distribution based on search """
content = request.get_json()
clean_list = []
must_include = []
if len(content["keyword_list"]) > 0:
# get all keywords
for k in content["keyword_list"]:
# clean_word = re.sub('[^A-Za-z0-9]+', '', k["keyword"])
clean_word = k["keyword"]
clean_list.append(clean_word)
if k["must_include"]:
must_include.append(clean_word)
dist = corpus.getJournalCount(clean_list, must_include)
return jsonify(dist)
@app.route("/history")
def history():
""" Web hook for retrieving search history on main page """
user_ip = request.environ["REMOTE_ADDR"]
# get search queries
results = db.execQuery(
"""
select id
, DATE_FORMAT(created, '%%m/%%d/%%Y %%H:%%i')
from search
where ipaddr=%s
order by created desc
limit 5
""",
(user_ip,),
)
search_list = []
for result in results:
temp = {}
temp["search_id"] = result[0]
temp["date"] = result[1]
temp["terms"] = []
# get terms used for this search
term_list = db.execQuery(
"""select st.headingid
, st.keyword
, st.weight
, st.rank
, concat(h.tierindex, '.', h.tiering)
, h.heading
from searchterm st
left join search s on s.id=st.searchid
left join heading h on h.id=st.headingid
where st.searchid=%s
order by st.rank""",
(result[0],),
)
for term in term_list:
t = {}
if term[0] is not None:
t["heading_id"] = term[0]
t["tier_index"] = term[4]
t["keyword"] = term[1]
t["weight"] = term[2]
t["order"] = term[3]
temp["terms"].append(t)
search_list.append(temp)
# get document queries
results = db.execQuery(
"""
select id, docname
, DATE_FORMAT(created, '%%m/%%d/%%Y %%H:%%i')
from dochash d
order by created desc
limit 5
"""
)
doc_list = []
for result in results:
temp = {}
temp["dochashid"] = result[0]
temp["name"] = result[1]
temp["date"] = result[2]
doc_list.append(temp)
# json markup
history = {"searches": search_list, "documents": doc_list}
return jsonify(history)
@app.route("/recoversearch/<search_id>")
def recoverSearch(search_id):
""" Recover a set of search terms that was previously used by user """
user_ip = request.environ["REMOTE_ADDR"]
# get results and authenticate with ipaddress
results = db.execQuery(
"""select st.headingid
, st.keyword
, st.weight
, st.rank
, concat(h.tierindex, '.', h.tiering)
, h.heading
, w.headingid
, concat(h2.tierindex, '.', h2.tiering)
, th.termid
, ifnull(p.pos, 'n')
, ifnull(p.posdesc, 'noun')
from searchterm st
left join search s on s.id=st.searchid
left join heading h on h.id=st.headingid
left join word w on w.fr_translation = st.keyword
left join heading h2 on h2.id=w.headingid
left join tfidf_heading th on th.wordid=w.id
left join pos p on p.oht=w.pos
where st.searchid=%s
order by st.rank""",
(search_id,),
)
data = oht_wrapper.aggregateByRelevance(results, recovering=True)
# return json markup
return jsonify(data)
def recoverDocumentTfidf(dochash_id, redirect=True):
""" Recover a document that was uploaded by a user """
# In order for this to happen, we need to populate
# 1. session["tfidf"] - topic distribution
# 2. session["keyterm"] - Topic heading id matches based off topicdist
# 3. session["searchterm"] - filtered list of key terms
session["dochashid"] = dochash_id
aHash = db.execQuery(
"""
select t.termid, t.word, udt.tf, udt.idf, udt.tfidf, t.headingid, h.tierindex
from userdoctfidf udt
left join tfidf t on t.termid=udt.termid
left join heading h on h.id=t.headingid
where udt.dochashid=%s
order by udt.tfidf desc
limit 5""",
(dochash_id,),
)
# we have a match - recover it
tfidf = {}
for result in aHash:
term_idx = int(result[0])
tfidf[term_idx] = {}
tfidf[term_idx]["term"] = result[1]
tfidf[term_idx]["tf"] = result[2]
tfidf[term_idx]["idf"] = result[3]
tfidf[term_idx]["tfidf"] = result[4]
if result[5] is not None:
tfidf[term_idx]["heading_id"] = result[5]
tfidf[term_idx]["tier_index"] = result[6]
session["tfidf"] = tfidf
# get headings from oht
key_term = oht_wrapper.getTfidfHeadingList(session["tfidf"])
search_term = [term for term in key_term[: CONST.DS_MAXTOPIC]]
session["keyterm"] = key_term
session["searchterm"] = search_term
session["tierindex"] = oht_wrapper.getTierIndexIntersection(search_term)
# redirect to analyzer for display
if redirect:
return False
else:
return tfidf
def getSearchResults(tfidf, clean_list):
""" Get a list of documents and return it's meta-info """
start = time.time()
rank_list = match(tfidf, 100)
end = time.time()
print(("Found 10 results in %s seconds" % (end - start)))
# return meta info
return getSearchMetaInfo(rank_list, clean_list)
def match(tfidf, n=100):
""" Find closest matching docs using tfidf score """
terms = ",".join([str(term) for term in tfidf])
return db.execQuery(
"""
select documentid
, sum(tfidf)
from doctfidf
where termid in ("""
+ terms
+ """)
group by documentid
order by sum(tfidf) desc
limit %s
""",
(n,),
)
def getJournalSearchResults(tfidf, n=10):
""" Like search results, but amalgamated by journal instead """
terms = ",".join([str(term) for term in tfidf])
rank_list = db.execQuery(
"""
select m.journalid, j.title, j.logo, j.url from meta m
left join (
select documentid
, sum(tfidf) score
from doctfidf
where termid in ("""
+ terms
+ """)
group by documentid
order by sum(tfidf) desc) x on x.documentid=m.documentid
left join journal j on j.id=m.journalid
group by m.journalid
order by sum(x.score) desc
limit %s;
""",
(n,),
)
return rank_list
def getSearchMetaInfo(rank_list, keyword_list, must_include=[]):
""" Get the meta info for a list of document ids """
results = []
start = time.time()
# first get document info - author, title, etc.
for aDoc in rank_list:
r = corpus.getDocumentInfo(aDoc[0])
resultlist = list(r[0])
# if strDocHashID is None:
resultlist.append(aDoc[1])
results.append(resultlist)
end = time.time()
print(("Retrieved meta info in %s seconds" % (end - start)))
# create the markup to return and also pull topic distribution for doc
search = []
start = time.time()
for result in results:
if len(result) < 13:
continue
doc = {}
doc["id"] = result[0]
doc["title"] = result[1]
doc["author"] = result[2]
cit_arr = []
cit_arr.append(result[3])
cit_arr.append(", Vol. ")
cit_arr.append(result[4])
if result[5]:
cit_arr.append(", No. ")
cit_arr.append(result[5])
if result[6]:
cit_arr.append(".")
cit_arr.append(result[6])
cit_arr.append(", ")
cit_arr.append(result[1])
cit_arr.append(" (")
cit_arr.append(result[9])
cit_arr.append(" ")
cit_arr.append(result[8])
cit_arr.append("), pp. ")
cit_arr.append(result[10])
if result[11]:
cit_arr.append("-")
cit_arr.append(result[11])
doc["citation"] = "".join(cit_arr)
doc["topiclist"] = []
doc["keywordlist"] = []
doc["uri"] = result[12]
doc["cossim"] = result[13]
# get document distributions
aTopicDist = db.execQuery(
"""
select d.termid, d.word, d.tfidf, t.headingid
from doctfidf d
left join tfidf t on t.termid=d.termid
where d.documentid=%s""",
(doc["id"],),
)
aTopicDist = list(aTopicDist)
aTopicDist.sort(key=lambda tup: tup[2], reverse=True)
unused_terms = keyword_list[:]
used_terms = []
i = 0
for topic in aTopicDist:
if topic[1] in used_terms:
continue
else:
used_terms.append(topic[1])
i += 1
temp = {}
temp["id"] = topic[0]
temp["name"] = topic[1]
temp["dist"] = topic[2]
hid = topic[3]
if hid in oht_wrapper.heading:
temp["heading"] = oht_wrapper.heading[hid]["heading"]
temp["thematicheading"] = oht_wrapper.heading[hid]["thematicheading"]
temp["tier_index"] = oht_wrapper.heading[hid]["tier"]
temp["heading_id"] = hid
temp["pos"] = oht_wrapper.heading[hid]["pos"]
temp["posdesc"] = oht_wrapper.heading[hid]["posdesc"]
else:
temp["heading"] = topic[1]
temp["thematicheading"] = None
temp["tier_index"] = None
temp["heading_id"] = None
temp["pos"] = None
temp["posdesc"] = None
temp["is_keyword"] = None
added = True
if topic[1] in keyword_list:
temp["is_keyword"] = 1
if len(doc["topiclist"]) < CONST.DS_MAXTOPIC:
doc["topiclist"].append(temp)
else:
if topic[1] in keyword_list:
temp["rank"] = i
doc["keywordlist"].append(temp)
else:
added = False
if added and temp["is_keyword"] == 1:
unused_terms.remove(topic[1])
if len(unused_terms) > 0:
for term in unused_terms:
temp = {}
temp["name"] = term
doc["keywordlist"].append(temp)
# pull any named entities saved for this document
doc["entitylist"] = []
# aEntity = db.execQuery("""select entity, txt from entity where documentid=%s
# and (entitytype='nomorg' or entitytype='nompers')""", (doc["id"],))
# for entity in aEntity:
# temp = {}
# temp["type"] = result[0]
# temp["name"] = result[1]
# doc["entitylist"].append(temp)
search.append(doc)
end = time.time()
print(("Got document meta info in %s seconds" % (end - start)))
return search
def filterOHTWordList(words):
""" Filter a list of words for client side use """
heading_list = []
for word in words:
temp = {}
temp["id"] = word["word"].id
temp["name"] = word["word"].en
temp["pos"] = word["word"].pos
temp["heading_id"] = word["word"].headingid
if word["enable"]:
temp["enable"] = 1
heading_list.append(temp)
return heading_list
def filterOHTHeadingList(headings):
""" Filter a list of words for client side use """
heading_list = []
for heading in headings:
temp = {}
temp["id"] = heading.id
temp["name"] = heading.fr
temp["pos"] = heading.pos
temp["tier_index"] = heading.tierindex
temp["size"] = heading.size
heading_list.append(temp)
return heading_list
def extractTextFromUpload(file):
""" Extract complete text from an uploaded file """
text = []
ext = file.filename.split(".")[-1]
if ext == "xml":
strText = file.read()
xmlDoc = cm.parseXML(strText=strText)
strText = erudit.getTextFromXML(None, xmlDoc)
elif ext == "pdf":
pdfReader = PyPDF2.PdfFileReader(file)
# iterate pages and extract text from each
for i in range(pdfReader.numPages):
p = pdfReader.getPage(i)
text.append(p.extractText())
elif ext == "docx":
bytes = io.BytesIO(file.read())
doc = docx.Document(bytes)
# print the number of pages in pdf file
for p in doc.paragraphs:
text.append(p.text)
elif ext == "txt":
text.append(file.read())
else:
return ""
return " ".join(text).encode("utf8")
############################## HELPER FUNCTIONS ##############################
def saveTFDF():
tfdf = {}
with open("./model/pkl/tfdf2.pkl", "r") as f:
tfdf = pickle.load(f)
for word in tfdf:
db.execUpdate(
"insert into tfdf(word, freq, docfreq) values(%s, %s, %s)",
(word, tfdf[word]["tf"], tfdf[word]["df"]),
)
def saveStopWords():
aStopWord = []
results = db.execQuery(
"select lower(word) word from stopword where dataset=%s", ("adam2",)
)
for result in results:
aStopWord.append(result[0].lower().strip())
if " " not in aStopWord:
aStopWord.append(" ")
# aStopWord = set(aStopWord)
with open("./model/pkl/stopword.pkl", "w+") as f:
pickle.dump(aStopWord, f)
def inferTopic(tfidf):
# look up a list of words in OHT and place us somewhere
for key in tfidf:
word = tfidf[key]["word"]
def inferTopicNames():
results = db.execQuery("select word, pos from tfidf where headingid is null")
for result in results:
aHeading = oht_wrapper.getTopicHeadingRankList(result[0])
aTop = {"value": 0, "id": None, "col": []}
for key in aHeading:
if aHeading[key] > aTop["value"]:
aTop["value"] = aHeading[key]
aTop["id"] = key
aTop["col"] = []
elif aHeading[key] == aTop["value"]:
aTop["col"].append(key)
strCol = ",".join(str(key) for key in aTop["col"])
db.execUpdate(
"update topic set headingid=%s, infername=%s where id=%s",
(aTop["id"], strCol, result[0]),
)
def transformDocumentToModel(nSampleSize=100):
""" Save top 10 topics per document as well as a compressed version of
all topic distributions - Run cosin sim on top 10 topics and then run
cosin similarity on topic distribution """
results = db.execQuery(
"""
select distinct cleanpath from document
where cleanpath is not null
"""
)
n = 0
for result in results:
with codecs.open(result[0], encoding="utf-8") as json_file:
aData = json.load(json_file)
for key in aData:
topic_dist = tm.transform(aData[key])
db.execUpdate("delete from doctopic where documentid=%s;", (key,))
db.execUpdate("delete from doctopiclz where documentid=%s;", (key,))
topic_str = ""
for topic_idx, dist in enumerate(topic_dist[0]):
if topic_idx > 0:
topic_str = topic_str + ","
topic_str = topic_str + str(topic_idx) + "-" + str(dist)
topic_hash = compress(topic_str)
db.execUpdate(
"""
insert into doctopiclz(documentid, topichash)
values(%s, %s)""",
(key, str(topic_hash).decode("latin1").encode("utf8")),
)
for topic_idx in topic_dist[0].argsort()[::-1][: CONST.DS_MAXTOPIC]:
db.execUpdate(
"""
insert into doctopic(documentid, topicid, dist, rank)
select %s, id, %s, %s from topic where topicname=%s;""",
(key, topic_dist[0][topic_idx], rank, str(topic_idx)),
)
db.execUpdate(
"""update document set
transformdt=CURRENT_TIMESTAMP where id=%s""",
(key,),
)
n += 1
if n == nSampleSize:
break
if n == nSampleSize:
break
def savePreProcessedList():
db.execUpdate("update document set cleanpath=null", ())
aSavedFile = {}
with open("./model/pkl/preprocess_list.pkl", "rb") as f:
aSavedFile = pickle.load(f)
for aFile in aSavedFile:
db.execUpdate(
"update document set cleanpath=%s where id=%s",
(list(aFile.values())[0], list(aFile.keys())[0]),
)
def runTopicModel(nSampleSize=1000):
aDocument = []
aDocList = []
aSample = []
dirPath = "./model/corps/boosted/"
n = 0
strText = ""
for filename in os.listdir(dirPath):
if filename.endswith(".txt"):
result = dirPath + filename
with codecs.open(result, encoding="utf-8") as json_file:
aData = json.load(json_file)
for key in aData:
n += 1
aDocList.append(key)
aDocument.append(aData[key])
strText = aData[key]
if n == nSampleSize:
break
if n == nSampleSize:
break
tm.fitLDA(aDocument, aDocList)
for i in range(1000):
try:
tm.processText(strText)
except Exception as e:
print(str(e))
# tm.writeModelToDB()
# tm.saveModel()
def prePreProcessTextToDisk():
with open("./model/pkl/stopword.pkl", "r") as f:
tm.aStopWord = pickle.load(f)
results = db.execQuery(
"""
select max(cast(replace(replace(cleanpath,'./model/corps/', '')
, '.txt', '') as UNSIGNED)) lastfile
from document"""
)
if len(results) > 0:
nDoc = int(results[0][0])
else:
nDoc = 0
results = db.execQuery(
"""
select id, path from document
where dataset='erudit' and cleanpath is null"""
)
aData = {}
for result in results:
xmlDoc = cm.parseXML(strPath + result[1])
strText = erudit.getTextFromXML(result[0], xmlDoc)
if strText == "":
continue
strCleanText = tm.preProcessText(strText)
aData[str(result[0])] = strCleanText
nDoc += 1
if ((nDoc % 100) == 0) or (nDoc + 1 == len(results)):
strCleanPath = "./model/corps/" + str(nDoc) + ".txt"
cm.saveUTF8ToDisk(strCleanPath, json.dumps(aData))
for key in aData:
db.execUpdate(
"update document set cleanpath=%s where id=%s", (strCleanPath, key)
)
aData = {}
def countKeywords():
count_vect = CountVectorizer(
max_df=CONST.TM_MAXDF,
min_df=CONST.TM_MINDF,
max_features=CONST.TM_FEATURES,