ABAO77 commited on
Commit
878a9aa
·
verified ·
1 Parent(s): 9173a54

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +44 -81
app.py CHANGED
@@ -1,28 +1,22 @@
1
  import os
2
  from typing import Any, Dict, List
3
  from dotenv import load_dotenv
4
-
5
  load_dotenv()
6
  import uvicorn
7
  from fastapi import APIRouter, FastAPI, HTTPException
8
  from fastapi.middleware.cors import CORSMiddleware
9
  from pydantic import BaseModel
10
  from model_predict_onnx import onnx_predictor
11
- from user_weights import (
12
- get_all_users,
13
- get_user_metadata,
14
- get_user_weights,
15
- track_question_tags,
16
- update_user_metadata,
17
- update_user_weights,
18
- update_weights_from_feedback,
19
- update_weights_from_query,
20
- )
21
- from get_destinations import get_destinations_list, get_question_vector, get_recent_tags
22
  from get_default_weight import feature_names, weights_bias_vector
23
  from database import db
24
- from loguru import logger
25
-
26
 
27
  # Define request models
28
  class WeightUpdateRequest(BaseModel):
@@ -30,16 +24,13 @@ class WeightUpdateRequest(BaseModel):
30
  new_weights: List[float]
31
  metadata: Dict[str, Any] = {}
32
 
33
-
34
  class FeedbackRequest(BaseModel):
35
  destination_id: int
36
  tag_id: int
37
  rating: int # 1-5 stars
38
 
39
-
40
  router = APIRouter(prefix="/model", tags=["Model"])
41
 
42
-
43
  @router.get("/get_question_tags/{question}")
44
  async def get_question_tags(question: str):
45
  # Get the prediction
@@ -50,9 +41,8 @@ async def get_question_tags(question: str):
50
  print("Predicted Tags:", predicted_tags)
51
  return {"question_tags": predicted_tags}
52
 
53
-
54
  @router.get("/get_destinations_list/{question_tags}/{top_k}")
55
- async def get_destinations_list_api(question_tags: str, top_k: str):
56
  # Get the prediction
57
  question_vector = get_question_vector(question_tags)
58
  destinations_list = get_destinations_list(question_vector, int(top_k))
@@ -60,21 +50,16 @@ async def get_destinations_list_api(question_tags: str, top_k: str):
60
  print("destinations_list:", destinations_list)
61
  return {"destinations_list": destinations_list}
62
 
63
-
64
  @router.get("/get_recommendation_destinations/{user_id}/{top_k}")
65
- async def get_recommendation_destinations(user_id: str, top_k: str):
66
  # Get the prediction
67
  recent_tags = get_recent_tags(user_id)
68
  question_tags = " ".join(recent_tags)
69
  question_vector = get_question_vector(question_tags)
70
- destinations_list = get_destinations_list(question_vector, int(top_k), user_id)
71
  destination_ids = db.get_destination_ids(destinations_list)
72
- return {
73
- "destination_ids": destination_ids,
74
- "destinations_list:": destinations_list,
75
- "recent_tags": recent_tags,
76
- }
77
-
78
 
79
  @router.get("/get_destinations_list_by_question/{question}/{top_k}")
80
  async def get_destinations_list_api(question: str, top_k: str):
@@ -92,17 +77,16 @@ async def get_destinations_list_api(question: str, top_k: str):
92
  print("destinations_list:", destinations_list)
93
  return {"destinations_list": destinations_list}
94
 
95
-
96
  @router.get("/get_destinations_list_by_question/{question}/{top_k}/{user_id}")
97
  def get_destinations_list_with_user_api(question: str, top_k: str, user_id: str):
98
  """
99
  Get a list of destinations based on a question and user-specific weights.
100
-
101
  Parameters:
102
  question (str): The question to get destinations for.
103
  top_k (str): The number of destinations to return.
104
  user_id (str): The ID of the user.
105
-
106
  Returns:
107
  dict: A dictionary containing the list of destinations.
108
  """
@@ -112,15 +96,13 @@ def get_destinations_list_with_user_api(question: str, top_k: str, user_id: str)
112
  # Print the sentence and its predicted tags
113
  print("Sentence:", original_sentence)
114
  print("Predicted Tags:", question_tags)
115
-
116
  # Track the question tags for the user
117
  track_question_tags(user_id, question_tags)
118
-
119
  # Update weights based on query tags
120
- update_weights_from_query(
121
- user_id, question_tags, feature_names, weights_bias_vector
122
- )
123
-
124
  # Get the prediction
125
  question_tags_str = " ".join(question_tags)
126
  question_vector = get_question_vector(question_tags_str)
@@ -129,34 +111,31 @@ def get_destinations_list_with_user_api(question: str, top_k: str, user_id: str)
129
  print("destinations_list:", destinations_list)
130
  return {"destinations_list": destinations_list}
131
 
132
-
133
  @router.get("/users")
134
  def get_users():
135
  """
136
  Get a list of all users.
137
-
138
  Returns:
139
  dict: A dictionary containing the list of users.
140
  """
141
  users = get_all_users()
142
  return {"users": users}
143
 
144
-
145
  @router.get("/users/{user_id}")
146
  def get_user(user_id: str):
147
  """
148
  Get the metadata for a user.
149
-
150
  Parameters:
151
  user_id (str): The ID of the user.
152
-
153
  Returns:
154
  dict: A dictionary containing the user's metadata.
155
  """
156
  metadata = get_user_metadata(user_id)
157
  return {"metadata": metadata}
158
 
159
-
160
  @router.get("/users/{user_id}/weights")
161
  def get_user_weights_api(user_id: str):
162
  """
@@ -173,100 +152,86 @@ def get_user_weights_api(user_id: str):
173
  weights_list = weights.tolist() if weights is not None else None
174
  return {"user_id": user_id, "weights": weights_list}
175
 
176
-
177
  @router.post("/users/{user_id}/weights")
178
  def update_user_weights_api(user_id: str, request: WeightUpdateRequest):
179
  """
180
  Update the weights for a user.
181
-
182
  Parameters:
183
  user_id (str): The ID of the user.
184
  request (WeightUpdateRequest): The request containing the tag indices, new weights, and metadata.
185
-
186
  Returns:
187
  dict: A dictionary indicating whether the update was successful.
188
  """
189
  # Validate the request
190
  if len(request.tag_indices) != len(request.new_weights):
191
- raise HTTPException(
192
- status_code=400,
193
- detail="Tag indices and new weights must have the same length",
194
- )
195
-
196
  # Update the weights
197
- success = update_user_weights(
198
- user_id, request.tag_indices, request.new_weights, weights_bias_vector
199
- )
200
-
201
  # Update the metadata
202
  if success and request.metadata:
203
  update_user_metadata(user_id, request.metadata)
204
-
205
  return {"success": success}
206
 
207
-
208
  @router.post("/users/{user_id}/feedback")
209
  def record_user_feedback(user_id: str, request: FeedbackRequest):
210
  """
211
  Record user feedback on a specific tag for a specific destination.
212
-
213
  Parameters:
214
  user_id (str): The ID of the user.
215
  request (FeedbackRequest): The request containing the destination ID, tag ID, and rating.
216
-
217
  Returns:
218
  dict: A dictionary indicating whether the feedback was recorded successfully.
219
  """
220
  # Validate the request
221
  if request.rating < 1 or request.rating > 5:
222
  raise HTTPException(status_code=400, detail="Rating must be between 1 and 5")
223
-
224
  # Update weights based on feedback
225
  success = update_weights_from_feedback(
226
- user_id,
227
- request.destination_id,
228
- request.tag_id,
229
- request.rating,
230
- weights_bias_vector,
231
  )
232
-
233
  return {"success": success}
234
 
235
-
236
  @router.get("/tags")
237
  def get_tags():
238
  """
239
  Get a list of all tags.
240
-
241
  Returns:
242
  dict: A dictionary containing the list of tags.
243
  """
244
- return {"tags": [tag.upper() for tag in feature_names.tolist()]}
245
-
246
 
247
  app = FastAPI(docs_url="/")
248
  app.add_middleware(
249
  CORSMiddleware,
250
- allow_origins=["*"],
251
  allow_credentials=True,
252
- allow_methods=["*"],
253
- allow_headers=["*"],
254
- expose_headers=[
255
- "*",
256
- ],
257
  )
258
 
259
  app.include_router(router)
260
 
261
-
262
  @app.on_event("startup")
263
  def startup_event():
264
  """
265
  Connect to the database when the API starts.
266
  """
267
  db.connect()
268
- logger.info("Database connected")
269
-
270
 
271
  @app.on_event("shutdown")
272
  def shutdown_event():
@@ -274,8 +239,6 @@ def shutdown_event():
274
  Close the database connection when the API shuts down.
275
  """
276
  db.close()
277
- logger.info("Database closed")
278
-
279
 
280
  if __name__ == "__main__":
281
  uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", 7880)))
 
1
  import os
2
  from typing import Any, Dict, List
3
  from dotenv import load_dotenv
 
4
  load_dotenv()
5
  import uvicorn
6
  from fastapi import APIRouter, FastAPI, HTTPException
7
  from fastapi.middleware.cors import CORSMiddleware
8
  from pydantic import BaseModel
9
  from model_predict_onnx import onnx_predictor
10
+ from user_weights import (get_all_users, get_user_metadata,
11
+ get_user_weights,
12
+ track_question_tags,
13
+ update_user_metadata,
14
+ update_user_weights,
15
+ update_weights_from_feedback,
16
+ update_weights_from_query)
17
+ from get_destinations import (get_destinations_list,get_question_vector,get_recent_tags)
 
 
 
18
  from get_default_weight import feature_names, weights_bias_vector
19
  from database import db
 
 
20
 
21
  # Define request models
22
  class WeightUpdateRequest(BaseModel):
 
24
  new_weights: List[float]
25
  metadata: Dict[str, Any] = {}
26
 
 
27
  class FeedbackRequest(BaseModel):
28
  destination_id: int
29
  tag_id: int
30
  rating: int # 1-5 stars
31
 
 
32
  router = APIRouter(prefix="/model", tags=["Model"])
33
 
 
34
  @router.get("/get_question_tags/{question}")
35
  async def get_question_tags(question: str):
36
  # Get the prediction
 
41
  print("Predicted Tags:", predicted_tags)
42
  return {"question_tags": predicted_tags}
43
 
 
44
  @router.get("/get_destinations_list/{question_tags}/{top_k}")
45
+ async def get_destinations_list_api(question_tags: str, top_k:str):
46
  # Get the prediction
47
  question_vector = get_question_vector(question_tags)
48
  destinations_list = get_destinations_list(question_vector, int(top_k))
 
50
  print("destinations_list:", destinations_list)
51
  return {"destinations_list": destinations_list}
52
 
 
53
  @router.get("/get_recommendation_destinations/{user_id}/{top_k}")
54
+ async def get_recommendation_destinations(user_id: str, top_k:str):
55
  # Get the prediction
56
  recent_tags = get_recent_tags(user_id)
57
  question_tags = " ".join(recent_tags)
58
  question_vector = get_question_vector(question_tags)
59
+ destinations_list = get_destinations_list(question_vector, int(top_k))
60
  destination_ids = db.get_destination_ids(destinations_list)
61
+ print("destinations_list:", destinations_list)
62
+ return {"destination_ids": destination_ids,"destinations_list":destinations_list,"recent_tags": recent_tags}
 
 
 
 
63
 
64
  @router.get("/get_destinations_list_by_question/{question}/{top_k}")
65
  async def get_destinations_list_api(question: str, top_k: str):
 
77
  print("destinations_list:", destinations_list)
78
  return {"destinations_list": destinations_list}
79
 
 
80
  @router.get("/get_destinations_list_by_question/{question}/{top_k}/{user_id}")
81
  def get_destinations_list_with_user_api(question: str, top_k: str, user_id: str):
82
  """
83
  Get a list of destinations based on a question and user-specific weights.
84
+
85
  Parameters:
86
  question (str): The question to get destinations for.
87
  top_k (str): The number of destinations to return.
88
  user_id (str): The ID of the user.
89
+
90
  Returns:
91
  dict: A dictionary containing the list of destinations.
92
  """
 
96
  # Print the sentence and its predicted tags
97
  print("Sentence:", original_sentence)
98
  print("Predicted Tags:", question_tags)
99
+
100
  # Track the question tags for the user
101
  track_question_tags(user_id, question_tags)
102
+
103
  # Update weights based on query tags
104
+ update_weights_from_query(user_id, question_tags, feature_names, weights_bias_vector)
105
+
 
 
106
  # Get the prediction
107
  question_tags_str = " ".join(question_tags)
108
  question_vector = get_question_vector(question_tags_str)
 
111
  print("destinations_list:", destinations_list)
112
  return {"destinations_list": destinations_list}
113
 
 
114
  @router.get("/users")
115
  def get_users():
116
  """
117
  Get a list of all users.
118
+
119
  Returns:
120
  dict: A dictionary containing the list of users.
121
  """
122
  users = get_all_users()
123
  return {"users": users}
124
 
 
125
  @router.get("/users/{user_id}")
126
  def get_user(user_id: str):
127
  """
128
  Get the metadata for a user.
129
+
130
  Parameters:
131
  user_id (str): The ID of the user.
132
+
133
  Returns:
134
  dict: A dictionary containing the user's metadata.
135
  """
136
  metadata = get_user_metadata(user_id)
137
  return {"metadata": metadata}
138
 
 
139
  @router.get("/users/{user_id}/weights")
140
  def get_user_weights_api(user_id: str):
141
  """
 
152
  weights_list = weights.tolist() if weights is not None else None
153
  return {"user_id": user_id, "weights": weights_list}
154
 
 
155
  @router.post("/users/{user_id}/weights")
156
  def update_user_weights_api(user_id: str, request: WeightUpdateRequest):
157
  """
158
  Update the weights for a user.
159
+
160
  Parameters:
161
  user_id (str): The ID of the user.
162
  request (WeightUpdateRequest): The request containing the tag indices, new weights, and metadata.
163
+
164
  Returns:
165
  dict: A dictionary indicating whether the update was successful.
166
  """
167
  # Validate the request
168
  if len(request.tag_indices) != len(request.new_weights):
169
+ raise HTTPException(status_code=400, detail="Tag indices and new weights must have the same length")
170
+
 
 
 
171
  # Update the weights
172
+ success = update_user_weights(user_id, request.tag_indices, request.new_weights, weights_bias_vector)
173
+
 
 
174
  # Update the metadata
175
  if success and request.metadata:
176
  update_user_metadata(user_id, request.metadata)
177
+
178
  return {"success": success}
179
 
 
180
  @router.post("/users/{user_id}/feedback")
181
  def record_user_feedback(user_id: str, request: FeedbackRequest):
182
  """
183
  Record user feedback on a specific tag for a specific destination.
184
+
185
  Parameters:
186
  user_id (str): The ID of the user.
187
  request (FeedbackRequest): The request containing the destination ID, tag ID, and rating.
188
+
189
  Returns:
190
  dict: A dictionary indicating whether the feedback was recorded successfully.
191
  """
192
  # Validate the request
193
  if request.rating < 1 or request.rating > 5:
194
  raise HTTPException(status_code=400, detail="Rating must be between 1 and 5")
195
+
196
  # Update weights based on feedback
197
  success = update_weights_from_feedback(
198
+ user_id,
199
+ request.destination_id,
200
+ request.tag_id,
201
+ request.rating,
202
+ weights_bias_vector
203
  )
204
+
205
  return {"success": success}
206
 
 
207
  @router.get("/tags")
208
  def get_tags():
209
  """
210
  Get a list of all tags.
211
+
212
  Returns:
213
  dict: A dictionary containing the list of tags.
214
  """
215
+ return {"tags": feature_names.tolist()}
 
216
 
217
  app = FastAPI(docs_url="/")
218
  app.add_middleware(
219
  CORSMiddleware,
220
+ allow_origins=['*'],
221
  allow_credentials=True,
222
+ allow_methods=['*'],
223
+ allow_headers=['*'],
224
+ expose_headers=['*',]
 
 
225
  )
226
 
227
  app.include_router(router)
228
 
 
229
  @app.on_event("startup")
230
  def startup_event():
231
  """
232
  Connect to the database when the API starts.
233
  """
234
  db.connect()
 
 
235
 
236
  @app.on_event("shutdown")
237
  def shutdown_event():
 
239
  Close the database connection when the API shuts down.
240
  """
241
  db.close()
 
 
242
 
243
  if __name__ == "__main__":
244
  uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", 7880)))