-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.py
73 lines (55 loc) · 1.8 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
"""
This script runs a web interface of ask-fandom
"""
import logging
from ask import ask_fandom
from ask_fandom.intents.base import AskFandomIntentBase
from ask_fandom.errors import AskFandomError, QuestionNotUnderstoodError
from flask import Flask, jsonify, request, render_template
app = Flask(__name__)
logging.basicConfig(level=logging.INFO)
def get_example_questions():
"""
:rtype: list[str]
"""
ret = []
for intent in AskFandomIntentBase.intents():
ret += intent.get_example_questions()
return sorted(ret)
@app.route('/')
def index():
return render_template(
'index.html',
examples=get_example_questions()
)
@app.route('/ask')
def ask():
question = request.args.get('q')
# you need to specify a question
if not question:
return jsonify({'error': 'You need to specify a question'}), 400 # Bad request
app.logger.info('Question: %s', question)
try:
intent, words, answer = ask_fandom(question)
except QuestionNotUnderstoodError:
return jsonify({'error': 'I could not understand your question'}), 422 # UNPROCESSABLE ENTITY
except AskFandomError as ex:
return jsonify({'error': ex.__class__.__name__}), 404 # Not found the answer
return jsonify({
'answer': str(answer),
'_intent': intent.__class__.__name__,
'_meta': answer.meta,
'_words': words, # how the question has been understood by NLP system
'_reference': answer.reference # a link to the answer source
})
@app.route('/examples')
def examples():
return jsonify({
'questions': get_example_questions()
})
@app.route('/info')
def info():
return jsonify({
'name': 'ask-fandom',
'intents': [intent.__name__ for intent in AskFandomIntentBase.intents()]
})