forked from aliostad/WikiRockWord2Vec
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwiki_rock_w2v_api.py
64 lines (50 loc) · 1.75 KB
/
wiki_rock_w2v_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
from __future__ import unicode_literals
from flask import Flask, jsonify, request
import logging
from logging import FileHandler
import time
import gensim
t = time.time()
if __name__ == '__main__':
print("Time is now {}".format(t))
app = Flask(__name__)
application = app
try:
file_handler = FileHandler("wordsim_api.log", "a")
file_handler.setLevel(logging.WARNING)
app.logger.addHandler(file_handler)
word_sim = gensim.models.Word2Vec.load('data/rock_music.w2v')
if __name__ == '__main__':
print("Took {}".format(time.time() - t))
except:
if __name__ == '__main__':
print("could not start file logging")
def order_sims(similars, minFreq = 10):
res = []
similars = sorted(similars, key=lambda x: x[1], reverse=True)
for c in similars:
if word_sim.vocab[c[0]].count > minFreq:
res.append(c)
return res
@app.route('/api/v1/rock/similar', methods=['GET'])
def similar():
poss = request.args.get('pos')
negs = request.args.get('neg')
topns = request.args.get('topn')
min_freqs = request.args.get('min_freq')
pos = [] if poss==None else map(lambda x: x, poss.split(','))
neg = [] if negs==None else map(lambda x: x, negs.split(','))
topn = 100 if topns==None else int(topns)
min_freq = 10 if min_freqs==None else int(min_freqs)
if word_sim is None:
jsonify({"result": "Could not find the model."}), 500
for p in pos:
if p not in word_sim.vocab:
return jsonify({"result": "Not in vocab: " + p}), 400
for p in neg:
if p not in word_sim.vocab:
return jsonify({"result": "Not in vocab: " + p}), 400
sims = word_sim.most_similar(positive=pos, negative=neg, topn=topn)
return jsonify({"result": order_sims(sims, min_freq)})
if __name__ == '__main__':
app.run(debug = True, use_reloader=False)