Skip to content

Commit 12dc355

Browse files
hadifaralfredfrancis
authored andcommitted
Feature/pep8 (alfredfrancis#87)
* fix pep-8 issues and utf language issue in version 2
1 parent 9499df1 commit 12dc355

19 files changed

+383
-287
lines changed

app/__init__.py

+12-11
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,31 @@
11
import os
2+
3+
from blinker import Namespace
24
from flask import Flask
35
from flask_cors import CORS
6+
from flask_mongoengine import MongoEngine
47

58
app = Flask(__name__)
69

7-
cors = CORS(app)
10+
CORS(app)
811

912
# Configurations
1013
try:
1114
env = os.environ['APPLICATION_ENV']
1215
except KeyError as e:
1316
# logging.error('Unknown environment key, defaulting to Development')
1417
env = 'Development'
18+
1519
app.config.from_object('config.%s' % env)
1620
app.config.update(
1721
DEBUG=True,
1822
TESTING=True,
19-
TEMPLATES_AUTO_RELOAD=True
20-
)
23+
TEMPLATES_AUTO_RELOAD=True)
2124

22-
23-
from flask_mongoengine import MongoEngine
2425
db = MongoEngine(app)
2526

26-
from blinker import Namespace
2727
my_signals = Namespace()
2828

29-
@app.errorhandler(404)
30-
def not_found(error):
31-
return "Not found", 404
32-
3329
from app.agents.controllers import bots
3430
from app.nlu.controllers import nlu
3531
from app.intents.controllers import intents
@@ -42,4 +38,9 @@ def not_found(error):
4238
app.register_blueprint(train)
4339
app.register_blueprint(endpoint)
4440
app.register_blueprint(bots)
45-
app.register_blueprint(entities_blueprint)
41+
app.register_blueprint(entities_blueprint)
42+
43+
44+
@app.errorhandler(404)
45+
def not_found(error):
46+
return "Not found", 404

app/agents/controllers.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,7 @@
44
from app.commons import build_response
55

66
bots = Blueprint('bots_blueprint', __name__,
7-
url_prefix='/agents/<bot_name>')
8-
7+
url_prefix='/agents/<bot_name>')
98

109

1110
@bots.route('/config', methods=['PUT'])
@@ -22,6 +21,7 @@ def set_config(bot_name):
2221
bot.save()
2322
return build_response.sent_ok()
2423

24+
2525
@bots.route('/config', methods=['GET'])
2626
def get_config(bot_name):
2727
"""
@@ -31,4 +31,4 @@ def get_config(bot_name):
3131
"""
3232
bot = Bot.objects.get(name=bot_name)
3333

34-
return build_response.build_json(bot.config)
34+
return build_response.build_json(bot.config)

app/agents/models.py

+6-3
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
1-
from mongoengine.fields import StringField , Document,DictField
1+
from mongoengine.fields import DictField
2+
from mongoengine.fields import Document
3+
from mongoengine.fields import StringField
4+
25

36
class Bot(Document):
47
name = StringField(max_length=100, required=True, unique=True)
5-
config = DictField(required=True,default={
8+
config = DictField(required=True, default={
69
"confidence_threshold": .70
7-
})
10+
})

app/commons/build_response.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
1-
from flask import Response
21
import json
32

3+
from flask import Response
4+
45

56
def build_json(result):
67
return Response(response=json.dumps(result),

app/commons/logger.py

+2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import logging.handlers
2+
23
import json_log_formatter
4+
35
formatter = json_log_formatter.JSONFormatter()
46

57
logger = logging.getLogger("query")

app/commons/utils.py

+14-10
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,13 @@
11
from datetime import datetime
2+
23
import parsedatetime as pdt
4+
from mongoengine.fields import EmbeddedDocumentField
5+
from mongoengine.fields import EmbeddedDocumentListField
6+
from mongoengine.fields import GenericEmbeddedDocumentField
7+
from mongoengine.fields import GenericReferenceField
8+
from mongoengine.fields import ListField
9+
from mongoengine.fields import ReferenceField
10+
from mongoengine.fields import SortedListField
311

412

513
def date_from_string(timeString):
@@ -8,11 +16,6 @@ def date_from_string(timeString):
816
result = str(cal.parseDT(timeString.strip(), now)[0])
917
return result
1018

11-
from mongoengine.fields import ListField, SortedListField,\
12-
EmbeddedDocumentListField, EmbeddedDocumentField,\
13-
GenericEmbeddedDocumentField, ReferenceField,\
14-
GenericReferenceField
15-
1619

1720
def update_document(document, data_dict):
1821
"""
@@ -33,10 +36,10 @@ def field_value(field, value):
3336
for item in value
3437
]
3538
if field.__class__ in (
36-
EmbeddedDocumentField,
37-
GenericEmbeddedDocumentField,
38-
ReferenceField,
39-
GenericReferenceField
39+
EmbeddedDocumentField,
40+
GenericEmbeddedDocumentField,
41+
ReferenceField,
42+
GenericReferenceField
4043
):
4144
return field.document_type(**value)
4245
else:
@@ -49,7 +52,8 @@ def field_value(field, value):
4952

5053
return document
5154

55+
5256
def is_list_empty(inList):
5357
if isinstance(inList, list): # Is a list
5458
return all(map(is_list_empty, inList))
55-
return False # Not a list
59+
return False # Not a list

app/endpoint/controllers.py

+28-21
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,31 @@
1-
from bson import ObjectId
1+
# -*- coding: utf-8 -*-
2+
23
import json
34

5+
from flask import Blueprint, request, abort
46
from jinja2 import Template
57

6-
from flask import Blueprint, request, abort
78
from app import app
8-
9-
from app.commons.logger import logger
9+
from app.agents.models import Bot
1010
from app.commons import build_response
11-
from app.nlu.entity_extractor import EntityExtractor
11+
from app.commons.logger import logger
12+
from app.endpoint.utils import SilentUndefined
13+
from app.endpoint.utils import call_api
14+
from app.endpoint.utils import get_synonyms
15+
from app.endpoint.utils import split_sentence
1216
from app.intents.models import Intent
13-
14-
from app.endpoint.utils import get_synonyms, SilentUndefined, split_sentence, call_api
17+
from app.nlu.classifiers.starspace_intent_classifier import \
18+
EmbeddingIntentClassifier
19+
from app.nlu.entity_extractor import EntityExtractor
20+
from app.nlu.tasks import model_updated_signal
1521

1622
endpoint = Blueprint('api', __name__, url_prefix='/api')
1723

18-
# Loading ML Models at app startup
19-
from app.nlu.classifiers.starspace_intent_classifier import EmbeddingIntentClassifier
20-
2124
sentence_classifier = None
2225
synonyms = None
2326
entity_extraction = None
2427

28+
2529
# Request Handler
2630
@endpoint.route('/v1', methods=['POST'])
2731
def api():
@@ -72,8 +76,8 @@ def api():
7276
logger.info(request_json.get("input"), extra=result_json)
7377
return build_response.build_json(result_json)
7478

75-
intent_id, confidence,suggetions = predict(request_json.get("input"))
76-
app.logger.info("intent_id => %s"%intent_id)
79+
intent_id, confidence, suggetions = predict(request_json.get("input"))
80+
app.logger.info("intent_id => %s" % intent_id)
7781
intent = Intent.objects.get(intentId=intent_id)
7882

7983
if intent.parameters:
@@ -86,7 +90,7 @@ def api():
8690
result_json["intent"] = {
8791
"object_id": str(intent.id),
8892
"confidence": confidence,
89-
"id": str(intent.intentId)
93+
"id": str(intent.intentId.encode('utf8'))
9094
}
9195

9296
if parameters:
@@ -163,7 +167,7 @@ def api():
163167
isJson = False
164168
parameters = result_json["extractedParameters"]
165169
headers = intent.apiDetails.get_headers()
166-
app.logger.info("headers %s"%headers)
170+
app.logger.info("headers %s" % headers)
167171
url_template = Template(
168172
intent.apiDetails.url, undefined=SilentUndefined)
169173
rendered_url = url_template.render(**context)
@@ -175,7 +179,7 @@ def api():
175179

176180
try:
177181
result = call_api(rendered_url,
178-
intent.apiDetails.requestType,headers,
182+
intent.apiDetails.requestType, headers,
179183
parameters, isJson)
180184
except Exception as e:
181185
app.logger.warn("API call failed", e)
@@ -195,6 +199,7 @@ def api():
195199
else:
196200
return abort(400)
197201

202+
198203
def update_model(app, message, **extra):
199204
"""
200205
Signal hook to be called after training is completed.
@@ -212,23 +217,25 @@ def update_model(app, message, **extra):
212217
entity_extraction = EntityExtractor(synonyms)
213218
app.logger.info("Intent Model updated")
214219

220+
215221
with app.app_context():
216-
update_model(app,"Modles updated")
222+
update_model(app, "Modles updated")
217223

218-
from app.nlu.tasks import model_updated_signal
219224
model_updated_signal.connect(update_model, app)
220225

221-
from app.agents.models import Bot
226+
222227
def predict(sentence):
223228
"""
224229
Predict Intent using Intent classifier
225230
:param sentence:
226231
:return:
227232
"""
228233
bot = Bot.objects.get(name="default")
229-
predicted,intents = sentence_classifier.process(sentence)
234+
predicted, intents = sentence_classifier.process(sentence)
230235
app.logger.info("predicted intent %s", predicted)
231236
if predicted["confidence"] < bot.config.get("confidence_threshold", .90):
232-
return Intent.objects(intentId=app.config["DEFAULT_FALLBACK_INTENT_NAME"]).first().intentId, 1.0,[]
237+
intents = Intent.objects(intentId=app.config["DEFAULT_FALLBACK_INTENT_NAME"])
238+
intents = intents.first().intentId
239+
return intents, 1.0, []
233240
else:
234-
return predicted["intent"], predicted["confidence"],intents[1:]
241+
return predicted["intent"], predicted["confidence"], intents[1:]

app/endpoint/utils.py

+28-12
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,16 @@
1-
from app import app
1+
import json
2+
23
import requests
34
from jinja2 import Undefined
4-
import json
5+
6+
from app import app
7+
from app.entities.models import Entity
8+
59

610
def split_sentence(sentence):
711
return sentence.split("###")
812

913

10-
from app.entities.models import Entity
1114
def get_synonyms():
1215
"""
1316
Build synonyms dict from DB
@@ -19,10 +22,11 @@ def get_synonyms():
1922
for value in entity.entity_values:
2023
for synonym in value.synonyms:
2124
synonyms[synonym] = value.value
22-
app.logger.info("loaded synonyms %s",synonyms)
25+
app.logger.info("loaded synonyms %s", synonyms)
2326
return synonyms
2427

25-
def call_api(url, type,headers={}, parameters = {}, is_json=False):
28+
29+
def call_api(url, type, headers={}, parameters={}, is_json=False):
2630
"""
2731
Call external API
2832
:param url:
@@ -31,27 +35,39 @@ def call_api(url, type,headers={}, parameters = {}, is_json=False):
3135
:param is_json:
3236
:return:
3337
"""
34-
app.logger.info("Initiating API Call with following info: url => {} payload => {}".format(url,parameters))
38+
app.logger.info("Initiating API Call with following info:"
39+
" url => {} payload => {}".format(url, parameters))
40+
3541
if "GET" in type:
36-
response = requests.get(url,headers=headers, params=parameters, timeout=5)
42+
response = requests.get(url, headers=headers,
43+
params=parameters, timeout=5)
3744
elif "POST" in type:
3845
if is_json:
39-
response = requests.post(url,headers=headers, json=parameters, timeout=5)
46+
response = requests.post(url, headers=headers,
47+
json=parameters, timeout=5)
4048
else:
41-
response = requests.post(url,headers=headers, params=parameters, timeout=5)
49+
response = requests.post(url, headers=headers,
50+
params=parameters, timeout=5)
4251
elif "PUT" in type:
4352
if is_json:
44-
response = requests.put(url,headers=headers, json=parameters, timeout=5)
53+
response = requests.put(url, headers=headers,
54+
json=parameters, timeout=5)
4555
else:
46-
response = requests.put(url,headers=headers, params=parameters, timeout=5)
56+
response = requests.put(url, headers=headers,
57+
params=parameters, timeout=5)
4758
elif "DELETE" in type:
48-
response = requests.delete(url,headers=headers, params=parameters, timeout=5)
59+
response = requests.delete(url, headers=headers,
60+
params=parameters, timeout=5)
4961
else:
5062
raise Exception("unsupported request method.")
63+
5164
result = json.loads(response.text)
65+
5266
app.logger.info("API response => %s", result)
67+
5368
return result
5469

70+
5571
class SilentUndefined(Undefined):
5672
"""
5773
Class to suppress jinja2 errors and warnings

0 commit comments

Comments
 (0)