-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
73 lines (55 loc) · 2.17 KB
/
server.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
from aiohttp import web
import json
import os
from model import *
from data_reader import DataReader
from vocab import Vocab
from tensor_generator import TensorGenerator
from download_data import OPEN_CORPORA_DEST_FILE
def init():
global loader, vocab, tensor_generator
loader = DataReader(OPEN_CORPORA_DEST_FILE)
loader.load()
vocab = Vocab(loader)
vocab.load()
tensor_generator = TensorGenerator(loader, vocab)
global input_, predictions, dropout
input_, logits, dropout = model(
max_words_in_sentence=tensor_generator.max_sentence_length,
max_word_length=tensor_generator.max_word_length,
char_vocab_size=vocab.char_vocab_size(),
num_output_classes=vocab.part_vocab_size()
)
_targets, _target_mask, _loss_, _accuracy, predictions = loss(
logits=logits,
batch_size=0,
max_words_in_sentence=tensor_generator.max_sentence_length
)
def split_sentence(sentence_string):
return sentence_string.split(" ")
def calculate_sentence_pos(sentence):
with tf.Session() as session:
restore_model(session)
input_tensors = tensor_generator.tensor_from_sentences([sentence])
predicted = session.run([predictions], {input_: input_tensors, dropout: 0.0})
sentence_prediction = predicted[0][0]
result = [[word, vocab.index_to_speech_part_human(word_prediction)] for word, word_prediction in zip(sentence, sentence_prediction)]
return result
async def calculator(request):
sentence_string = request.rel_url.query.get('sentence')
if not sentence_string:
return web.Response(status=404, text='sentence not specified')
sentence = split_sentence(sentence_string)
if(len(sentence) > tensor_generator.max_sentence_length):
return web.Response(status=422, text='sentence is too long')
result = calculate_sentence_pos(sentence)
return web.json_response({'result': result})
##############
## Server
##############
init()
app = web.Application()
app.router.add_route('GET', '/{tail:.*}', calculator)
# server_port = int(os.environ['SERVER_PORT']) if os.environ['SERVER_PORT'] else 3000
server_port = 8084
web.run_app(app, port=server_port)