-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsearch.py
237 lines (164 loc) · 6.01 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
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
from sklearn.feature_extraction.text import TfidfVectorizer
import numpy as np
import re
from tqdm import tqdm
import pandas as pd
from nltk.corpus import wordnet
import nltk
import random
import tensorflow as tf
from keras.models import load_model
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from keras.layers import Input, Dense, Activation, TimeDistributed, Softmax, TextVectorization, Reshape, RepeatVector, Conv1D, Bidirectional, AveragePooling1D, UpSampling1D, Embedding, Concatenate, GlobalAveragePooling1D, LSTM, Multiply
from keras.models import Model
import tensorflow as tf
import keras
nltk.download('wordnet')
nltk.download('omw')
nltk.download('omw-1.4')
DATASET = 'crawler_data.csv'
df = pd.read_csv(DATASET)
vectorizer = TfidfVectorizer()
tfidf = vectorizer.fit_transform(df['body'])
index = dict()
for w in tqdm(vectorizer.vocabulary_.keys()):
index[w] = dict()
for j in range(tfidf.shape[0]):
if tfidf[j, vectorizer.vocabulary_[w]] > 0:
index[w][j] = tfidf[j, vectorizer.vocabulary_[w]]
def buscar(palavras, indice):
assert type(palavras)==list
resultado = dict()
for p in palavras:
if p in indice.keys():
for documento in indice[p].keys():
if documento not in resultado.keys():
resultado[documento] = indice[p][documento]
else:
resultado[documento] += indice[p][documento]
return resultado
#2
def n_relevantes(result_busca, n):
res = []
for key in result_busca.keys():
res.append( (result_busca[key], key))
res = sorted(res, reverse= True)[0 : n]
return res
#3
def query(q_str, n, index):
words = re.findall('\w+', q_str)
res = buscar(words, index)
res_n = n_relevantes(res, n)
return res_n
def train(index = index):
for w in tqdm(vectorizer.vocabulary_.keys()):
index[w] = dict()
for j in range(tfidf.shape[0]):
if tfidf[j, vectorizer.vocabulary_[w]] > 0:
index[w][j] = tfidf[j, vectorizer.vocabulary_[w]]
def content_filter(content):
bad_words = 'datasets/bad_words.csv'
good_words = 'datasets/words_pos.csv'
bad_words = pd.read_csv(bad_words)
good_words = pd.read_csv(good_words)
good_words = good_words.drop(columns=['pos_tag'])
good_words['IsBad'] = 0
bad_words['IsBad'] = 1
good_words_sample = good_words.sample(1618, random_state=42)
words = pd.concat([good_words_sample, bad_words])
X = words["word"]
y = words["IsBad"]
X_train, X_test, y_train, y_test = train_test_split(X, y ,test_size=0.2, random_state=42)
classificador = Pipeline([
('meu_vetorizador', CountVectorizer(stop_words='english')),
('meu_classificador', LogisticRegression(penalty=None, solver='saga', max_iter=10000))
])
classificador.fit(X_train,y_train)
y_pred = classificador.predict(X_test)
acc = accuracy_score(y_pred,y_test)
prob = classificador.predict_log_proba([content])
probas = classificador.predict_proba([content])
if prob[0][1] >= 1:
return 1
elif prob[0][1] <= -1:
return -1
m = np.max(probas)
prob = 2 * (m -prob[0][1]) / (2 * m) - 1
return prob #[0][1]
def tfidf_search(command):
pattern = r"!search (.+)"
pattern2 = r"th=(\d+(\.\d+)?)"
term = ""
threshold = None
groups = re.match(pattern, command)
if groups:
term = groups.group(1)
threshold_match = re.search(pattern2, command)
if threshold_match:
threshold = float(threshold_match.group(1))
print("Term:", term)
if threshold is not None:
print("Threshold:", threshold)
#aqui usamos tudo acima para pegar o documento com maior tf-idf, com indice invertido
result = query(term, 1, index)
print("result:")
print(result)
if result:
# print(result[0][1])
url = df.loc[result[0][1]].url
content = df.loc[result[0][1]].body
if threshold is not None:
th = content_filter(content)
if th < threshold:
return "resultado abaixo do threshold especificado :("
return (url, content)
return "Nao Encontrado"
def wn_search(command):
url = 'none'
max_value = 0
pattern = r"!wn_search (.+)"
pattern2 = r"th=(\d+(\.\d+)?)"
term = ""
threshold = None
content = ""
groups = re.match(pattern, command)
if groups:
term = groups.group(1)
threshold_match = re.search(pattern2, command)
if threshold_match:
threshold = float(threshold_match.group(1))
print("Term:", term)
if threshold is not None:
print("Threshold:", threshold)
# if threshold is not None:
# threshold = threshold.group(1)
# threshold = float(threshold)
synsets = wordnet.synsets(term, lang='por')
print([syn for syn in synsets])
print([syn.name() for syn in synsets])
print([syn.definition() for syn in synsets])
#aqui usamos tudo acima para pegar o documento com maior tf-idf, com indice invertido
result = query(term, 1, index)
# print(result)
if result:
url = df.loc[result[0][1]].url
max_value = result[0][0]
for syn in synsets:
definition = syn.definition()
result = query(definition, 1, index)
if result:
value = result[0][0]
if value > max_value:
url = df.loc[result[0][1]].url
content = df.loc[result[0][1]].body
if url != 'none':
if threshold is not None:
th = content_filter(content)
if th < threshold:
return "resultado acima do threshold especificado :("
return (url, content)
return "Nao Encontrado"