· 6 years ago · Nov 29, 2019, 12:06 PM
1import falcon
2
3"""
4The goal of this project is to create a small HTTP API to serve two machine learning models:
5- a model that predicts a set of tags associated from a text
6- a model to generate texts given these tags and other parameters
7
81. Create a status endpoint
9GET /status
10
11 Returns the following JSON response:
12
13{
14 "status": "up",
15}
16
17
182. Create an endpoint to predict tags (=categories) from a review
19The TagClassifier class with the .predict(review) method should be used for prediction.
20
21POST /reviews/tags
22Content-Type: application/x-www-form-urlencoded
23
24content (str): the content of the review
25
26The format of the response must be:
27
28{
29 "tags": [
30 "tag1",
31 "tag2",
32 "tag3"
33 ]
34}
35
36
37
383. Generate a review
39The ResponseGenerator class with the .generate(tags, rating, reviewer_first_name, reviewer_last_name)
40method should be used for generation.
41
42POST /reviews/generate
43Content-Type: application/x-www-form-urlencoded
44
45tags (list of string): the tags extracted from the review
46rating (int): rating of the review (from 1 to 5)
47reviewer_first_name (str): first name of the reviewer (optional)
48reviewer_last_name (str): last name of the reviewer (optional)
49
50The format of the response must be:
51{
52 "response": "This is a generated text"
53}
54
55
564. Add an authentication mechanism
57We now require an API key to be included in the request in the 'X-AUTH' header. Make sure that the
58key value is equal to the variable API_KEY for all endpoints.
59If no key is submitted or if the key is incorrect, return a 403 Forbidden response.
60"""
61
62API_KEY = 'qv4ggSWHLVpWWo'
63
64
65class TagClassifier:
66 def __init__(self):
67 pass
68
69 def predict(self, review):
70 return [
71 'tag1',
72 'tag2',
73 'tag3',
74 ]
75
76
77class ResponseGenerator:
78 def __init__(self):
79 pass
80
81 def generate(self,
82 tags,
83 rating,
84 reviewer_first_name,
85 reviewer_last_name):
86 if reviewer_first_name and reviewer_last_name:
87 return "Hello {} {}".format(reviewer_first_name, reviewer_last_name)
88 if reviewer_first_name:
89 return "Hello {}".format(reviewer_first_name)
90 elif reviewer_last_name:
91 return "Hello {}".format(reviewer_last_name)
92
93 return "This is a generated text"
94
95
96api = falcon.API()
97api.req_options.auto_parse_form_urlencoded = True # Needed to parse correctly lists in URLs
98application = api
99
100# To launch the web server, use:
101# gunicorn --reload server