-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.py
227 lines (175 loc) · 6.29 KB
/
api.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
# -------- API ----------
from fastapi import FastAPI
# -------- News API ----------
import keys
import requests
# ------- Machine Learning ---------
import pandas as pd
import torch
import torch.nn as nn
from sklearn.feature_extraction import text
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from nltk.stem import WordNetLemmatizer
# ---------------- LETS GET TO THE CODE ---------------------
# Create News API Client
URL = "https://rapidapi.p.rapidapi.com/api/search/NewsSearchAPI"
HEADERS = {
"x-rapidapi-host": "contextualwebsearch-websearch-v1.p.rapidapi.com",
"x-rapidapi-key": keys.rapidapi_key
}
# ----------------------------- PARAMETERS -----------------------------
CUSTOM_SW = ["semst","u"] # TODO: add to actual stopwords
VOCAB = "kowalsky_vocab.csv"
USE_LEMMATIZER = True
# TODO: select headlines & body out of dataset
vocab_df = pd.read_csv(VOCAB, header=None)
# ----------------------------- BOW VECTORIZER PIPELINE -----------------------------
# takes [string], returns lowercased & lemmatized [string]
def lem_str(in_string):
out_str = [""]
lemmatizer = WordNetLemmatizer()
for word in in_string.split():
out_str[0] += (lemmatizer.lemmatize(word.lower()) + " ")
return out_str
# takes vocab & returns bow_vectorizer
def load_vectorizer(path):
# define stopwords
sw = text.ENGLISH_STOP_WORDS.union(["book"])
# read vocabulary
vocab_df = pd.read_csv(path, header=None)
vocab_df = vocab_df.drop([0])
bow_vectorizer = CountVectorizer(
stop_words=sw,
max_features=5000,
vocabulary=vocab_df[1]
)
return bow_vectorizer
# takes string & path to vocab and yeets it through the BoW pipeline
def create_bow(in_string, path):
bow_vectorizer = load_vectorizer(path)
if USE_LEMMATIZER == True:
bow = bow_vectorizer.fit_transform(lem_str(in_string), y=None)
else:
bow = bow_vectorizer.fit_transform([in_string], y=None)
return bow
# ----------------------------- TF-IDF PIPELINE -----------------------------
def create_tf(bow_vec):
tfreq_vec = TfidfTransformer(use_idf=False).fit(bow_vec)
tfreq = tfreq_vec.transform(bow_vec)
return tfreq
# TODO figure out
def create_tfidf(bow):
tfreq_vec = TfidfTransformer(use_idf=True)
tfreq = tfreq_vec.fit_transform(bow)
return tfreq
# -------------- GENEREATE 10001 VECTOR --------------
def yeet2vec(head, body):
# get our sub-vectores
claim_tf = create_tf(create_bow(head, VOCAB))
body_tf = create_tf(create_bow(body, VOCAB))
claim_tfidf = create_tfidf(create_bow(head, VOCAB))
body_tfidf = create_tfidf(create_bow(body, VOCAB))
print(" - created sub-vectors ✅")
# tasty cosine similarity
c_sim = cosine_similarity(claim_tfidf ,body_tfidf)
# do the yeeting
# HERE IS SOME ERRROR WITH CONCAT
claim_df = pd.DataFrame(claim_tf.toarray())
body_df = pd.DataFrame(body_tf.toarray())
c_sim_df = pd.DataFrame(c_sim)
tenk = pd.concat([claim_df,c_sim_df,body_df],axis=1)
tenk = tenk.to_numpy()
tenk = torch.from_numpy(tenk)
terror = [tenk]
print(" - created 10k vector ✅")
return tenk
# load the model
device = torch.device('cuda' if torch.cuda.is_available else 'cpu')
# set dimensions
in_dim = 10001
hidden_dim = 100
out_dim = 4
class NN(nn.Module):
def __init__(self, in_dim, hidden_dim, out_dim):
super(NN, self).__init__()
# define layers
self.l1 = nn.Linear(in_dim, hidden_dim)
self.relu = nn.ReLU()
self.l2 = nn.Linear(hidden_dim, out_dim)
# applies layers with sample x
def forward(self, x):
out = self.l1(x)
out = self.relu(out)
out = self.l2(out)
return out
model = NN(in_dim, hidden_dim, out_dim)
model.load_state_dict(torch.load('kowalsky_72_balanced.pth', map_location=torch.device('cpu')))
model.eval()
def predict(tenk_vec):
'''
predicts the stance/class of the query
params:
tenk_vec: 10001 vector
returns:
- dictionary of the predictions & the sources of news articles
- the stance alone
'''
with torch.no_grad():
pred = model(tenk_vec.float())
pred_out, pred_idx = torch.max(pred, 1)
classes = ['agree', 'disagree', 'discuss', 'unrelated']
print(pred)
stance = classes[((pred_idx.data).numpy()[0])]
return dict(zip(classes, pred.tolist()[0])), stance
app = FastAPI()
@app.get("/")
async def route():
return {"message":"Willkommen zu der Unreally API"}
@app.get("/predict")
async def use_model(query: str):
# get bodies matching test_string
test_string = query
# get bodies matching test_string
page_number = 1
page_size = 5
auto_correct = True
safe_search = True
with_thumbnails = False
from_published_date = ""
to_published_date = ""
querystring = {"q": test_string,
"pageNumber": page_number,
"pageSize": page_size,
"autoCorrect": auto_correct,
"safeSearch": safe_search,
"withThumbnails": with_thumbnails,
"fromPublishedDate": from_published_date,
"toPublishedDate": to_published_date}
response = requests.get(URL, headers=HEADERS, params=querystring).json()
test_body = "" # initiate test_body (the body we need to test the stance against the test_string)
sources = []
print(len(response['value']))
for article in response['value']:
body = article['body']
sources.append(article['url'])
test_body += body
vector = yeet2vec(test_string, test_body)
prediction = predict(vector)
if len(test_body) == 0:
return "No articles found :/"
# yeets strings through pipeline, outputs finished 10k vector
print(len(test_body))
print(test_body)
vector = yeet2vec(test_string, test_body)
values, prediction = predict(vector)
# send answer tweet
return {'prediction': prediction,'values': values, 'sources': sources}
import nest_asyncio
# Allow for asyncio to work within the Jupyter notebook cell
nest_asyncio.apply()
import uvicorn
# Run the FastAPI app using uvicorn
uvicorn.run(app)