-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsearch.py
executable file
·143 lines (108 loc) · 3.3 KB
/
search.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
#!/usr/bin/python3
import requests
import os
import sys
import json
def best(results):
"""
Return best score
"""
return max(results, key=(lambda key: results[key]))
def worst(results):
"""
Return worst score
"""
return min(results, key=(lambda key: results[key]))
class Guesser:
def guess(self, question, options):
raise NotImplementedError()
class Searcher:
def search(self, query):
raise NotImplementedError()
class Aggregator(Guesser):
"""
Combine the result of multiple guessers
"""
def __init__(self, guessers):
self.guessers = guessers
def guess(self, question, options):
#TODO: parallelize
pass
def get_final_result(self, question, results):
if question.contains('NOT'):
return worst(results)
else:
return best(results)
class BingSearcher(Searcher):
url = 'https://api.cognitive.microsoft.com/bing/v7.0/search'
def __init__(self, token):
self.headers = {'Ocp-Apim-Subscription-Key': token}
def search(self, query):
params = {"q": query, "textDecorations":True, "textFormat":"HTML"}
response = requests.get(self.url, headers=self.headers, params=params)
response.raise_for_status()
return response.json()
class ResultsGuesser(Guesser):
"""
Search web for:
question + "option"
Return the number of results for each search
"""
def __init__(self, searcher):
self.searcher = searcher
def guess(self, question, options):
#TODO parallelize
# options = [options[0]]
results = {}
for i,opt in enumerate(options):
answer = self.searcher.search(question+ ' ' + _q(opt))
try:
results[opt] = answer['webPages']['totalEstimatedMatches']
except:
print(json.dumps(answer, indent=4))
print('--------------')
return results
class FrequencyGuesser(Guesser):
"""
Search for question
Count the number of times each option appears.
TODO: Find a way to treat multi-word options
"""
def __init__(self, searcher):
self.searcher = searcher
def guess(self, question, options):
results = {}
answer = self.searcher.search(question)
for opt in options:
results[opt] = 0
for a in answer['webPages']['value']:
for opt in options:
results[opt] += a['snippet'].count(min(opt.split(' '), key=(lambda x: a['snippet'].count(x))))
return results
def _q(string):
return '"' + string + '"'
def main():
try:
data = json.load(sys.stdin)
except:
raise ValueError("Non ho ottenuto il json di input correttamente")
try:
s = BingSearcher(os.environ['BING_API_KEY'])
except:
raise ValueError("Non è stata impostata la key di bing correttamente")
g = ResultsGuesser(s)
print(json.dumps(data, indent=4))
print("\n")
guess = g.guess(data['question'], [data['a_1'], data['a_2'], data['a_3']])
print(guess)
guess = best(guess)
print(guess)
if guess == data['a_1']:
print('0')
if guess == data['a_2']:
print('1')
if guess == data['a_3']:
print('2')
return
if __name__ == '__main__':
main()