Chanjeans commited on
Commit
fe634c4
·
verified ·
1 Parent(s): 15afab3

현진_답변 로직 변경

Browse files
Files changed (1) hide show
  1. app.py +33 -32
app.py CHANGED
@@ -1221,15 +1221,15 @@ class ChatRequest(BaseModel):
1221
  user_input: str
1222
  mode: str # "emotion" or "rational"
1223
 
 
1224
  RECOMMEND_KEYWORDS = ["추천", "추천해줘", "취미 추천"]
1225
 
1226
-
1227
  # (4) 챗봇 + 추천 자동 분기용 모델
1228
  class ChatOrRecommendRequest(BaseModel):
1229
  user_input: str # 사용자의 채팅 메시지
1230
  mode: str # "emotion" 또는 "rational"
1231
 
1232
- # 🟢 다중 선택 가능하도록 List[str]로 변경
1233
  extroversion: Optional[str] = None
1234
  feeling_thinking: Optional[str] = None
1235
  hobby: Optional[List[str]] = None
@@ -1239,40 +1239,41 @@ class ChatOrRecommendRequest(BaseModel):
1239
  # (5) 자동 분기 엔드포인트
1240
  @app.post("/chat_or_recommend")
1241
  def chat_or_recommend(req: ChatOrRecommendRequest):
 
1242
  depression_score, depression_label = predict_depression(req.user_input)
 
1243
  if depression_label == "상담 권장":
1244
  counseling_response = (
1245
  "입력하신 메시지에서 심각한 우울 신호가 감지되었습니다.\n"
1246
  "전문 상담을 받으실 것을 강력히 권장드립니다.\n"
1247
- "빠른 시일 내에 전문가와 상담하시길 바랍니다."
1248
  )
1249
- return {
1250
- "response": counseling_response,
1251
- "depression_label": depression_label
1252
- }
 
1253
  user_text = req.user_input
1254
  mode = req.mode.lower()
1255
-
1256
- # ▶ 1) "추천" 키워드 포함 → 추천
1257
  if any(keyword in user_text for keyword in RECOMMEND_KEYWORDS):
1258
- # 프로필 미입력 예외 처리
1259
- # (여기서는 hobby / detail_hobby가 최소한 1개 이상 있다고 가정)
1260
  if not req.hobby:
1261
  raise HTTPException(
1262
  status_code=400,
1263
  detail="추천을 위해 [hobby, detail_hobby, extroversion, feeling_thinking] 정보가 필요합니다."
1264
  )
1265
-
1266
- # (A) 추천 로직
1267
  user_profile = {
1268
  "extroversion": req.extroversion or "",
1269
  "feeling_thinking": req.feeling_thinking or "",
1270
- "hobby": req.hobby, # list
1271
  "detail_hobby": req.detail_hobby or [],
1272
  }
1273
  top_items = recommend_content_based(user_profile, top_n=5)
1274
  results = []
1275
- for (item, score) in top_items:
 
1276
  results.append({
1277
  "item_id": item["item_id"],
1278
  "title": item["title"],
@@ -1280,29 +1281,29 @@ def chat_or_recommend(req: ChatOrRecommendRequest):
1280
  "personality": item["personality"],
1281
  "score": round(score, 4)
1282
  })
1283
- # ① 부드러운 대화체로 가공
1284
- response_text = "당신을 위한 맞춤 추천을 가져왔어요! ☺️"
1285
- for i, (item, score) in enumerate(top_items, start=1):
1286
  clean_desc = re.sub(r"\(.*?\)", "", item["desc"]).strip()
1287
- response_text += (
1288
- f"{i}. **{item['title']}**"
1289
- f" - {clean_desc} "
1290
- )
1291
  response_text += "이 중에서 어떤 활동이 가장 끌리시나요? 🌟"
1292
- return {
1293
- "mode": "recommend",
1294
- "recommendations": results,
1295
- "response": response_text # 🔹 여기에 키를 추가
1296
- }
1297
-
1298
 
 
1299
  else:
1300
- # ▶ 2) 챗봇 로직
1301
  if mode not in ["emotion", "rational"]:
1302
  raise HTTPException(
1303
  status_code=400,
1304
  detail="mode는 'emotion' 또는 'rational'이어야 합니다."
1305
  )
1306
-
1307
- reply = chat_response(user_text, mode=mode)
1308
- return {"mode": "chat", "response": reply}
 
 
 
 
 
 
 
 
 
 
1221
  user_input: str
1222
  mode: str # "emotion" or "rational"
1223
 
1224
+ # 추천 키워드 목록
1225
  RECOMMEND_KEYWORDS = ["추천", "추천해줘", "취미 추천"]
1226
 
 
1227
  # (4) 챗봇 + 추천 자동 분기용 모델
1228
  class ChatOrRecommendRequest(BaseModel):
1229
  user_input: str # 사용자의 채팅 메시지
1230
  mode: str # "emotion" 또는 "rational"
1231
 
1232
+ # 다중 선택 가능하도록 List[str]로 변경
1233
  extroversion: Optional[str] = None
1234
  feeling_thinking: Optional[str] = None
1235
  hobby: Optional[List[str]] = None
 
1239
  # (5) 자동 분기 엔드포인트
1240
  @app.post("/chat_or_recommend")
1241
  def chat_or_recommend(req: ChatOrRecommendRequest):
1242
+ # 우울도 예측 및 상담 권장 메시지 준비
1243
  depression_score, depression_label = predict_depression(req.user_input)
1244
+ counseling_response = ""
1245
  if depression_label == "상담 권장":
1246
  counseling_response = (
1247
  "입력하신 메시지에서 심각한 우울 신호가 감지되었습니다.\n"
1248
  "전문 상담을 받으실 것을 강력히 권장드립니다.\n"
1249
+ "빠른 시일 내에 전문가와 상담하시길 바랍니다.\n\n"
1250
  )
1251
+
1252
+ # 기본 응답 (추천 또는 챗봇)
1253
+ base_response = ""
1254
+ mode_used = ""
1255
+ additional_data = {}
1256
  user_text = req.user_input
1257
  mode = req.mode.lower()
1258
+
1259
+ # ▶ 1) "추천" 키워드가 포함된 경우 → 추천 로직 수행
1260
  if any(keyword in user_text for keyword in RECOMMEND_KEYWORDS):
1261
+ # 프로필 정보가 없으면 예외 처리 (hobby 정보 등은 최소 1개 이상 필요)
 
1262
  if not req.hobby:
1263
  raise HTTPException(
1264
  status_code=400,
1265
  detail="추천을 위해 [hobby, detail_hobby, extroversion, feeling_thinking] 정보가 필요합니다."
1266
  )
 
 
1267
  user_profile = {
1268
  "extroversion": req.extroversion or "",
1269
  "feeling_thinking": req.feeling_thinking or "",
1270
+ "hobby": req.hobby, # 리스트 형태
1271
  "detail_hobby": req.detail_hobby or [],
1272
  }
1273
  top_items = recommend_content_based(user_profile, top_n=5)
1274
  results = []
1275
+ response_text = "당신을 위한 맞춤 추천을 가져왔어요! ☺️\n"
1276
+ for i, (item, score) in enumerate(top_items, start=1):
1277
  results.append({
1278
  "item_id": item["item_id"],
1279
  "title": item["title"],
 
1281
  "personality": item["personality"],
1282
  "score": round(score, 4)
1283
  })
 
 
 
1284
  clean_desc = re.sub(r"\(.*?\)", "", item["desc"]).strip()
1285
+ response_text += f"{i}. **{item['title']}** - {clean_desc}\n"
 
 
 
1286
  response_text += "이 중에서 어떤 활동이 가장 끌리시나요? 🌟"
1287
+ base_response = response_text
1288
+ mode_used = "recommend"
1289
+ additional_data["recommendations"] = results
 
 
 
1290
 
1291
+ # ▶ 2) 추천 키워드가 없는 경우 → 기본 챗봇 로직 수행
1292
  else:
 
1293
  if mode not in ["emotion", "rational"]:
1294
  raise HTTPException(
1295
  status_code=400,
1296
  detail="mode는 'emotion' 또는 'rational'이어야 합니다."
1297
  )
1298
+ base_response = chat_response(user_text, mode=mode)
1299
+ mode_used = "chat"
1300
+
1301
+ # 상담 메시지와 기본 응답을 결합하여 최종 응답 생성
1302
+ final_response = counseling_response + base_response
1303
+ response_dict = {
1304
+ "mode": mode_used,
1305
+ "response": final_response,
1306
+ "depression_label": depression_label
1307
+ }
1308
+ response_dict.update(additional_data)
1309
+ return response_dict