-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathexplore
executable file
·82 lines (71 loc) · 2.72 KB
/
explore
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
#!/usr/bin/env python
import sys
import os
import cherrypy
from cherrypy.lib.static import serve_file
from explorer import Model
STATIC_DIR = os.path.dirname(os.path.realpath(__file__)) + '/public'
CACHE = {}
class ApiController(object):
@cherrypy.expose
@cherrypy.tools.json_out()
def explore(self,
query=None,
limit='1000',
enable_clustering='',
num_clusters='30'):
cache_key = '-'.join([query, limit, enable_clustering, num_clusters])
result = CACHE.get(cache_key, {})
if len(result) > 0:
return {'result': CACHE[cache_key], 'cached': True}
try:
exploration = self.model.explore(query, limit=int(limit))
exploration.reduce()
if len(enable_clustering):
if (len(num_clusters)):
num_clusters = int(num_clusters)
exploration.cluster(num_clusters=num_clusters)
result = exploration.serialize()
CACHE[cache_key] = result
return {'result': result, 'cached': False}
except KeyError:
return {'error': {'message': 'No vector found for ' + query}}
@cherrypy.expose
@cherrypy.tools.json_out()
def compare(self, **kw):
limit = kw.pop('limit', '100')
queries = kw.pop('queries[]', [])
try:
result = self.model.compare(queries, limit=int(limit))
return {'result': result}
except KeyError:
return {'error':
{'message': 'No vector found for {}'.format(queries)}}
@cherrypy.expose
@cherrypy.tools.json_out()
def autocomplete(self, query=None, limit='20'):
result = self.model.autocomplete(query, limit=int(limit))
return {'result': result}
class AppController(object):
@cherrypy.expose
def index(self, **kw):
return serve_file(STATIC_DIR + '/index.html', "text/html")
if __name__ == '__main__':
if len(sys.argv) < 2:
sys.stderr.write('Usage: {} <Word2Vec model file>\n'.format(sys.argv[0]))
sys.exit()
api_controller = ApiController()
api_controller.model = Model(sys.argv[1])
app_controller = AppController()
dispatch = cherrypy.dispatch.RoutesDispatcher()
dispatch.connect('api', '/api/:action', controller=api_controller)
dispatch.connect('app', '/:id', controller=app_controller, action="index")
dispatch.connect('app', '/', controller=app_controller, action="index")
app = cherrypy.tree.mount(None, config={
'/': {
'request.dispatch': dispatch,
'tools.staticdir.on': True,
'tools.staticdir.dir': STATIC_DIR
}
})
cherrypy.quickstart(app)