-
Notifications
You must be signed in to change notification settings - Fork 2
/
tw_query.py
286 lines (230 loc) · 10.1 KB
/
tw_query.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
# -*- coding: utf-8 -*-
"""
tw_query.py
Before using this module, please set the parameter in the line below identified as
### !!! APPLICATION DEPENDENT LINE
tw_query.py: Finding related terms using elasticsearch
DocTerms is a document made up of the first 500 terms found in a document, with fields for (1) all terms
(including duplicates) in the form of a single text blob, and
(2) a set of terms (without duplicates) as an
array of keywords.
NOTE: It appears that the document type must be named "doc".
Whenever I gave the doc_type a different
name, I got an error. I could not add a different doc_type
in the meta section of the class definition.
"""
import pdb
import re
import glob
import os
import sys
import log
import math
import collections
from collections import defaultdict
import codecs
import putils
import act_pnames
# imports for elasticsearch
import json
import time
import csv
from elasticsearch import Elasticsearch
from elasticsearch import helpers
from elasticsearch_dsl import Index, DocType, Text, Keyword, Integer
from elasticsearch_dsl.connections import connections
from elasticsearch_dsl.analysis import tokenizer, analyzer
from elasticsearch_dsl.query import MultiMatch, Match
#import shelve
# NOTE: shelve in python 2.7 does not support unicode keys. So, instead of
# using shelve, the demo uses a dictionary that must be loaded into
# memory when the python code is started. To support larger databases,
# the code should migrate to python 3 and use shelve or else adopt some
# other stable storage solution (e.g., sqlite).
# !! DocTerms meta information contains the name of the elasticsearch index.
# Currently this is hard_coded into the class, so make sure the index you
# want to query is set within that file before running tw_query.py
from tw_es import DocTerms
import roles_config
search = DocTerms.search()
# Connect to local host server
connections.create_connection(hosts=['127.0.0.1'])
# Establish elasticsearch instance
es = Elasticsearch()
# dictionary mapping terms to information (head, cat, freq)
d_ti = {}
CORPUS_SIZE = 0
def make_term_dict(corpus_root, corpus, sections, classifier_type, context_type, year):
"""
Read in the file created by run_make_term_info and create a dictionary
for use in elasticsearch runtime
"""
print "[act_term_info.py]Starting run_make_term_shelf"
sections_path = act_pnames.sections_root(corpus_root, corpus, sections)
term_info_path = sections_path + "/" + year + ".term_info"
cs_path = sections_path + "/" + year + ".cs"
term_shelf_path = sections_path + "/" + year + "_cache.term_info"
s_term_info = codecs.open(term_info_path, encoding='utf-8')
class TermInfo:
def __init__(self, term, head, cat, df):
self.term = term
self.head = head
self.cat = cat
self.df = df
# dictionary implementation of term_info database
d_ti = {}
# first populate dict of terms to doc freq
# Note that this file will contain terms that are not in .classes, since
# we do not label terms that have no relevant features.
# store the corpus_size as a special entry under term "|corpus_size|"
with open(cs_path) as f:
corpus_size = int(f.readline().strip())
print "[act_term_info.py]corpus_size: %i" % corpus_size
# Persistent storage of term_info has not been implemented
# shelve does not allow unicode keys in python 2.7 (fixed in 3.x)
# fcache gives a "Permission denied" error when we try to populate a cache
#term_shelf = shelve.open(term_shelf_path)
#term_shelf = FileCache(term_shelf_path)
# store the corpus_size as special term
d_ti["|corpus_size|"] = TermInfo("|corpus_size|", "", "", corpus_size)
for line in s_term_info:
line = line.strip("\n")
(term, head, cat, df) = line.split("\t")
df = int(df)
#pdb.set_trace()
#term_shelf[term] = TermInfo(term, head, cat, df)
d_ti[term] = TermInfo(term, head, cat, df)
#term_shelf.close()
s_term_info.close()
#print "[act_term_info.py]Shelf %s populated" % term_shelf_path
print "[act_term_info.py]d_ti term_info dictionary populated"
return(d_ti)
# load the term_info dictionary ///
# tw_query.run_make_term_dict("sp3", "ta", "9999")
def run_make_term_dict(corpus, sections, year):
corpus_root = roles_config.CORPUS_ROOT
classifier_type = roles_config.CLASSIFIER_TYPE
context_type = roles_config.CONTEXT_TYPE
d_ti = make_term_dict(corpus_root, corpus, sections, classifier_type, context_type, year)
return(d_ti)
# r = tw_query.mquery("support vector", 200)
def mquery(query, max_hits=100, operator='or', sort_by="r", df_factor=1):
d_term2freq = defaultdict(int)
d_term2idf = defaultdict(int)
#s = search.query("match", text=query, operator="and")
#s = search.query("match", text=query)
s = search.query("match", text={'query': query, 'operator': operator})
# using slice on s gives up to specified number of results.
# otherwise, you will get the default match size of 10
response = s[0:max_hits].execute()
print "Number hits: %i, operator: %s" % (len(response), operator)
# sum up the number of occurrences of terms in top max_hits restults
#pdb.set_trace()
for hit in response[0:max_hits]:
for term in hit.term:
d_term2freq[term] += 1
sorted_keys = []
# Now we have the "tf" (actually the number of docs a term
# occurs in within the result set for the current query.)
# Next we compute idf for each term in the results.
for (term, df) in d_term2freq.iteritems():
# A higher df_factor will give greater weight to df
df = df * df_factor
idf = (1 + math.log(df)) * math.log(CORPUS_SIZE / (d_ti[term].df * 1.0))
# store idf
d_term2idf[term] = idf
for key, value in sorted(d_term2idf.iteritems(), key=lambda (k,v): (v,k), reverse=True):
#print "%s: %s" % (key, value)
sorted_keys.append((key, value))
return(sorted_keys)
# tw_query.psk(r, 10, True)
# tw_query.psk(r)
# sort by relevance (r) or alphabetic (a)
def psk(sorted_keys, max=20, cat_p=True, sort_by="r"):
"""
Print a subset of sorted keys from the list sorted_keys,
classified into ACT categories (attribute, component, task).
Also return a dictionary containing the same info.
Sort is by relevance to a query.
Max is the maximum number of terms to keep for each category.
cat_p: If true, sort results by category. If false, just
return top uncategorized terms sorted by relevance.
sort_by: If "r", sort max top relevant terms by relevance.
If "a", sort alphabetically.
NOTE: The printing of terms to the terminal can be removed.
"""
result_max = 1000
# dictionary for returning results
d_qresult = {}
if cat_p:
# display by category
l_a = []
l_c = []
l_t = []
for key, value in sorted_keys[0:result_max]:
if d_ti[key].cat == "c":
l_c.append(key)
elif d_ti[key].cat == "a":
if len(key.split(" ")) >= 2:
l_a.append(key)
elif d_ti[key].cat == "t":
if len(key.split(" ")) >= 2:
l_t.append(key)
# create a dictionary in which to return the result of the query
d_qresult = { "tasks" : l_t[0:max],
"attributes" : l_a[0:max],
"components" : l_c[0:max] }
if sort_by == "a":
print "Sorted alphabetically"
print "\n***TASKS:\n%s" % "\n".join(sorted(l_t[0:max]))
print "\n***ATTRIBUTES:\n%s" % "\n".join(sorted(l_a[0:max]))
print "\n***COMPONENTS:\n%s" % "\n".join(sorted(l_c[0:max]))
else:
print "Sorted by relevance"
print "\n***terminology related to COMPONENTS:\n%s" % "\n".join(l_c[0:max])
print "\n***terminology related to TASKS:\n%s" % "\n".join(l_t[0:max])
print "\n***terminology related to ATTRIBUTES:\n%s" % "\n".join(l_a[0:max])
else:
# just print out terms in sorted order
for key, value in sorted_keys[0:max]:
print "%s: %d" % (key, value)
print "\n"
print "d_qresult: %s" % d_qresult
return(d_qresult)
# query and printed results (up to 20 in each cat)
# tw_query.pquery("support vectors")
# tw_query.pquery("signal processing")
# tw_query.pquery("signal processing", 50, "or", "r", 10)
def pquery(query, max_hits=50, operator='or', sort_by="r", df_factor=1):
sorted_keys = mquery(query, max_hits, operator, sort_by, df_factor)
d_qresult = psk(sorted_keys)
return(d_qresult)
def fquery(query):
"""
Simple top level function that takes a query and uses default parameters
to return a dictionary of related terms sorted by relevance.
It uses the top 50 results returned by the elasticsearch search.
The query is treated as a Boolean conjunction (all terms must match).
Results are ACT classified and returned in relevance order. df_factor
of 1 means simple tf*idf weighting without adding bias.
"""
# use query length to determine if query should be conjunctive or
# disjunctive
boolean_op = "and"
query_length = len(query.split(" "))
if len > 3:
boolean_op = "or"
d_qresult = pquery(query, 50, boolean_op, "r", 1)
return(d_qresult)
# NOTE: Since we cannot use shelve, we build a dictionary d_ti
# of term_info records on the fly when this module is imported. The d_ti
# data is used compute tfidf weights from term vectors of
# documents matching a query.
# We will read in doc freq, act category, and corpus size (# docs)
### !!! APPLICATION DEPENDENT LINE
### !!! The following line should be modified with the corpus name, sections parameter, and year
### corresponding to the corpus for which the index was built. This dependency will eventually
### be removed, once we replace the python dictionary with a stable storage alternative.
d_ti = run_make_term_dict("sp3", "ta", "9999")
CORPUS_SIZE = d_ti["|corpus_size|"].df
print "corpus size: %i" % CORPUS_SIZE