Spaces:
Sleeping

minjune121 commited on
Commit
eab5bb6
ยท
verified ยท
1 Parent(s): abdb6f8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +123 -608
app.py CHANGED
@@ -1,7 +1,6 @@
1
  """
2
- Boolook - ์Œ์„ฑ ๊ธฐ๋ฐ˜ ๊ฐ์ • ๋ถ„์„ ์ฑ… ์ถ”์ฒœ
3
- ๋ฐฑ์—”๋“œ: CatBoost ์žฌ์ •๋ ฌ ํ†ตํ•ฉ ๋ฒ„์ „ (์ปค์Šคํ…€ ๊ฐ์ •๋ชจ๋ธ ๊ตฌ์กฐ ์ •์ƒ)
4
- UI: ์ปค์Šคํ…€ HTML/CSS/JS (Gradio sanitize ์šฐํšŒ, gradio_api ์ง์ ‘ ํ˜ธ์ถœ)
5
  """
6
 
7
  import gradio as gr
@@ -11,6 +10,7 @@ import torch
11
  import torch.nn as nn
12
  import torch.nn.functional as F
13
  import pickle
 
14
  import json
15
  import threading
16
  import warnings
@@ -41,11 +41,13 @@ CATBOOST_MODEL_PATH = Path("catboost_ranker.cbm")
41
  SAMPLE_RATE = 16000
42
  MAX_EMBEDDING_BATCH = 128
43
 
 
44
  N_MELS = 64
45
  N_FFT = 1024
46
  HOP_LEN = 512
47
  MAX_FRAMES = 128
48
 
 
49
  _CB_FEATURES = ["cosine", "session_w", "survey_mult", "fb_boost", "emotion", "rank_hint"]
50
  _CB_CAT_FEATURES = ["emotion"]
51
 
@@ -67,6 +69,7 @@ DB_TABLE = "user_feedback"
67
 
68
 
69
  def _get_db_conn():
 
70
  try:
71
  return psycopg2.connect(**DB_CONFIG)
72
  except Exception as e:
@@ -82,10 +85,10 @@ book_embeddings = torch.tensor([])
82
  _data_ready = False
83
  _data_lock = threading.Lock()
84
 
85
-
86
  # ============================================================
87
- # ์ปค์Šคํ…€ ๊ฐ์ • ๋ชจ๋ธ ์•„ํ‚คํ…์ฒ˜
88
  # ============================================================
 
89
  class SEBlock(nn.Module):
90
  """Squeeze-and-Excitation Block"""
91
  def __init__(self, channels: int, reduction: int = 16):
@@ -183,7 +186,7 @@ class EmotionResNet(nn.Module):
183
 
184
 
185
  # ============================================================
186
- # ์ปค์Šคํ…€ ๊ฐ์ • ๋ชจ๋ธ ๋กœ๋“œ
187
  # ============================================================
188
  _emotion_model = None
189
  _emotion_classes = ["Angry", "Happy", "Neutral", "Sad"]
@@ -227,7 +230,7 @@ _load_emotion_model()
227
 
228
 
229
  # ============================================================
230
- # Mel-spectrogram ์ „์ฒ˜๋ฆฌ
231
  # ============================================================
232
  def _compute_melspec(y: np.ndarray, sr: int) -> torch.Tensor:
233
  try:
@@ -261,7 +264,7 @@ def _compute_melspec(y: np.ndarray, sr: int) -> torch.Tensor:
261
 
262
 
263
  # ============================================================
264
- # TTA ์ถ”๋ก 
265
  # ============================================================
266
  def _tta_augment(spec: torch.Tensor) -> torch.Tensor:
267
  shift = np.random.randint(-MAX_FRAMES // 8, MAX_FRAMES // 8)
@@ -295,7 +298,7 @@ def _infer_emotion_model(y: np.ndarray, sr: int) -> Dict[str, float]:
295
 
296
 
297
  # ============================================================
298
- # CatBoost ์žฌ์ •๋ ฌ ๋ชจ๋ธ
299
  # ============================================================
300
  _cb_model = None
301
 
@@ -666,7 +669,7 @@ def _apply_survey_to_weights(user_id: str, preferred_text: str, weights: Dict) -
666
 
667
 
668
  def _get_isbn_survey_multiplier(weights: Dict, user_id: str, isbn: str) -> float:
669
- if user_id not in weights.get("user_weights", {}):
670
  return 1.0
671
  entry = weights["user_weights"][user_id]["isbn_scores"].get(isbn)
672
  if not entry:
@@ -854,7 +857,40 @@ def get_recommendations(
854
 
855
 
856
  # ============================================================
857
- # API ํ•จ์ˆ˜
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
858
  # ============================================================
859
  def api_feedback(feedback_data) -> str:
860
  """
@@ -862,8 +898,9 @@ def api_feedback(feedback_data) -> str:
862
  {
863
  "user_id": "3422423",
864
  "books": [
865
- {"isbn": "...", "emotion": "๊ธฐ์จ", "accepted": 1, "rank": 1},
866
- ...
 
867
  ]
868
  }
869
  """
@@ -913,6 +950,9 @@ def api_feedback(feedback_data) -> str:
913
  return json.dumps({"error": str(e)}, ensure_ascii=False, indent=2)
914
 
915
 
 
 
 
916
  def api_survey(survey_data) -> str:
917
  """
918
  ํด๋ผ์ด์–ธํŠธ ์ „์†ก ํ˜•์‹:
@@ -970,56 +1010,8 @@ def api_survey(survey_data) -> str:
970
  return json.dumps({"error": str(e)}, ensure_ascii=False, indent=2)
971
 
972
 
973
- def api_recommend(recommend_data) -> str:
974
- """
975
- ํ…์ŠคํŠธ ์ž…๋ ฅ ๊ธฐ๋ฐ˜ ์ถ”์ฒœ (์Œ์„ฑ ์—†์ด ์ง์ ‘ ์ž…๋ ฅ)
976
- {
977
- "user_id": "...",
978
- "text": "์˜ค๋Š˜ ๋„ˆ๋ฌด ์Šฌํผ์š”",
979
- "emotion_override": "์Šฌํ””" # ์„ ํƒ
980
- }
981
- """
982
- try:
983
- data = json.loads(recommend_data) if isinstance(recommend_data, str) else recommend_data
984
- user_id = str(data.get("user_id", ""))
985
- text = str(data.get("text", "")).strip()
986
- emo_ov = data.get("emotion_override")
987
-
988
- if not text:
989
- return json.dumps({"error": "text๋Š” ํ•„์ˆ˜์ž…๋‹ˆ๋‹ค."}, ensure_ascii=False)
990
-
991
- t_scores = text_emotion_scores(text)
992
- a_scores = {emo: 0.0 for emo in _EMOTION_LABELS}
993
- top_label, combined = fused_emotion(t_scores, a_scores)
994
- if emo_ov and emo_ov in _EMOTION_LABELS:
995
- top_label = emo_ov
996
-
997
- books = get_recommendations(text, top_label, user_id=user_id or None, top_n=3)
998
- output = {
999
- "user_id": user_id,
1000
- "text": text,
1001
- "emotion": top_label,
1002
- "emotion_scores": {k: round(v, 3) for k, v in combined.items()},
1003
- "recommendation_books": [
1004
- {
1005
- "isbn": b["isbn"],
1006
- "title": b["title"],
1007
- "author": b["author"],
1008
- "publisher": b["publisher"],
1009
- "content": b["content"],
1010
- "img_url": b["img_url"],
1011
- }
1012
- for b in books
1013
- ],
1014
- }
1015
- return json.dumps(output, ensure_ascii=False, indent=2)
1016
- except Exception as e:
1017
- logger.error(f"api_recommend ์‹คํŒจ: {e}")
1018
- return json.dumps({"error": str(e)}, ensure_ascii=False)
1019
-
1020
-
1021
  # ============================================================
1022
- # ๋ฉ”์ธ ์ฒ˜๋ฆฌ (์Œ์„ฑ)
1023
  # ============================================================
1024
  def process_voice(audio_input, user_id: str = None):
1025
  if not _data_ready:
@@ -1036,18 +1028,11 @@ def process_voice(audio_input, user_id: str = None):
1036
 
1037
  try:
1038
  if isinstance(audio_input, str):
1039
- # soundfile(libsndfile)์ด webm/ogg ๋“ฑ์„ ๋ชป ์ฝ๋Š” ๊ฒฝ์šฐ
1040
- # librosa(ffmpeg ๋ฐฑ์—”๋“œ)๋กœ ํด๋ฐฑ
1041
- try:
1042
- import soundfile as sf
1043
- y, sr = sf.read(audio_input)
1044
- y = y.astype(np.float32)
1045
- if y.ndim > 1:
1046
- y = y.mean(axis=1)
1047
- except Exception:
1048
- import librosa
1049
- y, sr = librosa.load(audio_input, sr=None, mono=True)
1050
- y = y.astype(np.float32)
1051
  else:
1052
  sr, y = audio_input
1053
  y = y.astype(np.float32)
@@ -1071,554 +1056,84 @@ def process_voice(audio_input, user_id: str = None):
1071
  a_scores = audio_emotion_scores(y, sr)
1072
  top_label, combined = fused_emotion(t_scores, a_scores)
1073
  books = get_recommendations(user_input, top_label, user_id=user_id, top_n=3)
 
1074
 
1075
- output = {
1076
- "user_input": user_input,
1077
- "emotion": top_label,
1078
- "emotion_score": round(combined.get(top_label, 0.0), 3),
1079
- "emotion_scores": {k: round(v, 3) for k, v in combined.items()},
1080
- "recommendation_books": [
1081
- {
1082
- "isbn": b["isbn"],
1083
- "title": b["title"],
1084
- "author": b["author"],
1085
- "publisher": b["publisher"],
1086
- "content": b["content"],
1087
- "img_url": b["img_url"],
1088
- }
1089
- for b in books
1090
- ],
1091
- }
1092
- return json.dumps(output, ensure_ascii=False, indent=2), books
1093
 
1094
  except Exception as e:
1095
  logger.error(f"์ฒ˜๋ฆฌ ์˜ค๋ฅ˜: {e}")
1096
  return json.dumps({"error": str(e)}, ensure_ascii=False, indent=2), []
1097
 
1098
 
1099
- # ============================================================
1100
- # ์ปค์Šคํ…€ UI (HTML/CSS)
1101
- # ============================================================
1102
- CUSTOM_HTML = """<!DOCTYPE html>
1103
- <html lang="ko">
1104
- <head>
1105
- <meta charset="UTF-8">
1106
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
1107
- <title>Boolook</title>
1108
- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@tabler/icons-webfont@3.19.0/dist/tabler-icons.min.css">
1109
- <style>
1110
- *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
1111
- :root {
1112
- --purple-50:#EEEDFE; --purple-100:#CECBF6; --purple-200:#AFA9EC;
1113
- --purple-400:#7F77DD; --purple-600:#534AB7; --purple-800:#3C3489;
1114
- --teal-50:#E1F5EE; --teal-100:#9FE1CB; --teal-400:#1D9E75; --teal-600:#0F6E56;
1115
- --coral-50:#FAECE7; --coral-100:#F5C4B3; --coral-400:#D85A30; --coral-600:#993C1D;
1116
- --gray-50:#F1EFE8; --gray-100:#D3D1C7; --gray-400:#888780; --gray-600:#5F5E5A;
1117
- --bg:#ffffff; --bg2:#f8f8f6; --bg3:#f2f0eb;
1118
- --text:#1a1a18; --text2:#5a5956; --text3:#9a9894;
1119
- --border:rgba(0,0,0,0.1); --border2:rgba(0,0,0,0.18);
1120
- --radius:12px; --radius-sm:8px; --radius-full:9999px;
1121
- }
1122
- @media (prefers-color-scheme: dark) {
1123
- :root { --bg:#1c1c1a; --bg2:#242422; --bg3:#2c2c2a; --text:#f0ede8; --text2:#a8a5a0; --text3:#686560;
1124
- --border:rgba(255,255,255,0.1); --border2:rgba(255,255,255,0.18);
1125
- --purple-50:#1e1d3a; --purple-100:#2d2a5a; --purple-200:#3d3878; --teal-50:#0d2620; --teal-100:#1a4035; --coral-50:#2d1510; --coral-100:#4a2018; }
1126
- }
1127
- body { font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif; background:var(--bg3); color:var(--text); min-height:100vh; }
1128
- .app-shell { max-width:480px; margin:0 auto; background:var(--bg); min-height:100vh; display:flex; flex-direction:column; position:relative; }
1129
- header { padding:20px 20px 0; display:flex; align-items:center; justify-content:space-between; }
1130
- .logo { font-size:22px; font-weight:700; color:var(--purple-600); letter-spacing:-0.5px; }
1131
- .logo span { color:var(--text3); font-weight:400; }
1132
- .user-pill { font-size:11px; padding:4px 10px; border-radius:var(--radius-full); background:var(--bg2); border:0.5px solid var(--border); color:var(--text3); }
1133
- nav { display:flex; padding:16px 20px 0; gap:4px; border-bottom:0.5px solid var(--border); }
1134
- .nav-btn { flex:1; display:flex; flex-direction:column; align-items:center; gap:3px; padding:8px 4px; font-size:10px; color:var(--text3); background:none; border:none; cursor:pointer; border-radius:var(--radius-sm); transition:color 0.15s; border-bottom:2px solid transparent; margin-bottom:-1px; }
1135
- .nav-btn i { font-size:20px; }
1136
- .nav-btn.active { color:var(--purple-600); border-bottom-color:var(--purple-400); }
1137
- .nav-btn:hover:not(.active) { color:var(--text2); background:var(--bg2); }
1138
- .tab { display:none; flex:1; overflow-y:auto; padding:20px; }
1139
- .tab.active { display:block; }
1140
- .voice-card { background:var(--purple-50); border:1.5px dashed var(--purple-200); border-radius:var(--radius); padding:28px 20px; text-align:center; cursor:pointer; transition:all 0.2s; margin-bottom:16px; }
1141
- .voice-card:hover { border-color:var(--purple-400); }
1142
- .voice-card.recording { background:var(--coral-50); border-style:solid; border-color:var(--coral-400); animation:softPulse 1.8s ease-in-out infinite; }
1143
- @keyframes softPulse { 0%,100%{opacity:1} 50%{opacity:.75} }
1144
- .mic-btn { width:64px; height:64px; border-radius:50%; background:var(--purple-600); display:flex; align-items:center; justify-content:center; margin:0 auto 12px; transition:transform 0.15s,background 0.2s; cursor:pointer; border:none; }
1145
- .mic-btn:hover { transform:scale(1.06); }
1146
- .mic-btn.recording { background:var(--coral-400); }
1147
- .mic-btn i { font-size:28px; color:#fff; }
1148
- .voice-title { font-size:16px; font-weight:600; color:var(--text); margin-bottom:4px; }
1149
- .voice-sub { font-size:13px; color:var(--text2); }
1150
- .waveform { display:flex; align-items:center; justify-content:center; gap:3px; height:36px; margin:10px 0 0; }
1151
- .wb { width:3px; background:var(--coral-400); border-radius:2px; animation:wv 0.9s ease-in-out infinite; }
1152
- .wb:nth-child(1){height:8px;animation-delay:0s} .wb:nth-child(2){height:18px;animation-delay:.1s}
1153
- .wb:nth-child(3){height:28px;animation-delay:.2s} .wb:nth-child(4){height:20px;animation-delay:.3s}
1154
- .wb:nth-child(5){height:32px;animation-delay:.15s} .wb:nth-child(6){height:14px;animation-delay:.25s}
1155
- .wb:nth-child(7){height:24px;animation-delay:.05s}
1156
- @keyframes wv { 0%,100%{transform:scaleY(1)} 50%{transform:scaleY(.35)} }
1157
- .chips { display:flex; flex-wrap:wrap; gap:6px; margin-bottom:16px; }
1158
- .chip { font-size:12px; padding:6px 12px; border:0.5px solid var(--border); border-radius:var(--radius-full); background:var(--bg); color:var(--text2); cursor:pointer; transition:all 0.15s; }
1159
- .chip:hover { background:var(--purple-50); color:var(--purple-800); border-color:var(--purple-200); }
1160
- .chip.sel { background:var(--purple-50); color:var(--purple-800); border-color:var(--purple-400); }
1161
- .divider { display:flex; align-items:center; gap:10px; margin:4px 0 12px; }
1162
- .divider::before,.divider::after { content:''; flex:1; height:0.5px; background:var(--border); }
1163
- .divider span { font-size:11px; color:var(--text3); }
1164
- .input-row { display:flex; gap:8px; margin-bottom:16px; }
1165
- .input-row input { flex:1; padding:10px 14px; font-size:14px; border:0.5px solid var(--border2); border-radius:var(--radius-sm); background:var(--bg); color:var(--text); outline:none; transition:border-color 0.15s; }
1166
- .input-row input:focus { border-color:var(--purple-400); }
1167
- .icon-btn { width:40px; height:40px; border-radius:var(--radius-sm); border:0.5px solid var(--border); background:var(--bg); display:flex; align-items:center; justify-content:center; cursor:pointer; color:var(--text3); flex-shrink:0; transition:background 0.15s; }
1168
- .icon-btn:hover { background:var(--bg2); }
1169
- .primary-btn { width:100%; padding:13px; font-size:15px; font-weight:600; background:var(--purple-600); color:#fff; border:none; border-radius:var(--radius-sm); cursor:pointer; transition:background 0.15s,transform 0.1s; margin-bottom:20px; }
1170
- .primary-btn:hover { background:var(--purple-800); }
1171
- .primary-btn:active { transform:scale(0.98); }
1172
- .primary-btn:disabled { background:var(--gray-100); color:var(--gray-400); cursor:not-allowed; }
1173
- .section-label { font-size:11px; font-weight:600; letter-spacing:0.08em; text-transform:uppercase; color:var(--text3); margin-bottom:10px; }
1174
- .emotion-banner { display:flex; align-items:center; gap:10px; padding:12px 16px; background:var(--purple-50); border-radius:var(--radius-sm); border:0.5px solid var(--purple-100); margin-bottom:14px; }
1175
- .emotion-icon { font-size:28px; }
1176
- .emotion-name { font-size:18px; font-weight:700; color:var(--purple-800); }
1177
- .emotion-sub { font-size:12px; color:var(--text2); }
1178
- .emotion-bars { display:flex; flex-direction:column; gap:7px; margin-bottom:20px; }
1179
- .eb-row { display:flex; align-items:center; gap:10px; font-size:13px; }
1180
- .eb-name { width:36px; color:var(--text2); flex-shrink:0; }
1181
- .eb-track { flex:1; height:5px; background:var(--bg3); border-radius:3px; overflow:hidden; }
1182
- .eb-fill { height:100%; border-radius:3px; background:var(--purple-200); transition:width 0.7s ease; }
1183
- .eb-fill.top { background:var(--purple-600); }
1184
- .eb-val { font-size:12px; color:var(--text3); width:28px; text-align:right; flex-shrink:0; }
1185
- .book-list { display:flex; flex-direction:column; gap:12px; }
1186
- .book-item { display:flex; gap:14px; padding:14px; background:var(--bg); border:0.5px solid var(--border); border-radius:var(--radius); transition:border-color 0.15s; }
1187
- .book-item:hover { border-color:var(--purple-200); }
1188
- .book-cover { width:54px; height:70px; border-radius:4px; background:var(--purple-50); border:0.5px solid var(--purple-100); display:flex; align-items:center; justify-content:center; flex-shrink:0; overflow:hidden; }
1189
- .book-cover i { font-size:22px; color:var(--purple-400); }
1190
- .book-body { flex:1; min-width:0; }
1191
- .book-rank { font-size:10px; font-weight:600; color:var(--purple-600); margin-bottom:3px; }
1192
- .book-title { font-size:14px; font-weight:600; color:var(--text); white-space:nowrap; overflow:hidden; text-overflow:ellipsis; margin-bottom:3px; }
1193
- .book-meta { font-size:12px; color:var(--text3); margin-bottom:6px; }
1194
- .book-desc { font-size:12px; color:var(--text2); line-height:1.55; display:-webkit-box; -webkit-line-clamp:2; -webkit-box-orient:vertical; overflow:hidden; margin-bottom:8px; }
1195
- .book-actions { display:flex; gap:6px; }
1196
- .fb-btn { padding:5px 10px; font-size:12px; border:0.5px solid var(--border); border-radius:var(--radius-full); background:var(--bg2); color:var(--text2); cursor:pointer; display:flex; align-items:center; gap:4px; transition:all 0.15s; }
1197
- .fb-btn:hover { background:var(--bg3); }
1198
- .fb-btn.liked { background:var(--teal-50); color:var(--teal-600); border-color:var(--teal-100); }
1199
- .fb-btn.passed { background:var(--coral-50); color:var(--coral-600); border-color:var(--coral-100); }
1200
- .send-fb-btn { width:100%; padding:11px; margin-top:12px; font-size:14px; font-weight:600; border:1.5px solid var(--purple-400); color:var(--purple-800); background:var(--purple-50); border-radius:var(--radius-sm); cursor:pointer; display:none; transition:background 0.15s; }
1201
- .send-fb-btn:hover { background:var(--purple-100); }
1202
- .send-fb-btn.show { display:block; }
1203
- .card { background:var(--bg); border:0.5px solid var(--border); border-radius:var(--radius); padding:16px; margin-bottom:14px; }
1204
- .field { margin-bottom:16px; }
1205
- .field:last-child { margin-bottom:0; }
1206
- .field label { font-size:13px; font-weight:600; color:var(--text); display:block; margin-bottom:6px; }
1207
- .field .hint { font-size:11px; color:var(--text3); margin-top:4px; }
1208
- .field textarea { width:100%; padding:10px 12px; font-size:14px; border:0.5px solid var(--border2); border-radius:var(--radius-sm); background:var(--bg); color:var(--text); resize:vertical; min-height:80px; font-family:inherit; outline:none; }
1209
- .field textarea:focus { border-color:var(--purple-400); }
1210
- .field input[type=text] { width:100%; padding:10px 12px; font-size:14px; border:0.5px solid var(--border2); border-radius:var(--radius-sm); background:var(--bg); color:var(--text); font-family:inherit; outline:none; }
1211
- .field input[type=text]:focus { border-color:var(--purple-400); }
1212
- .slider-row { display:flex; align-items:center; gap:10px; }
1213
- .slider-row input[type=range] { flex:1; accent-color:var(--purple-600); }
1214
- .slider-end { font-size:11px; color:var(--text3); }
1215
- .slider-val { font-size:12px; font-weight:600; color:var(--purple-800); min-width:56px; text-align:right; }
1216
- .success-msg { display:none; align-items:center; gap:8px; padding:12px 14px; background:var(--teal-50); border:0.5px solid var(--teal-100); border-radius:var(--radius-sm); font-size:13px; color:var(--teal-600); margin-bottom:14px; }
1217
- .success-msg.show { display:flex; }
1218
- .teal-btn { width:100%; padding:13px; font-size:15px; font-weight:600; background:var(--teal-400); color:#fff; border:none; border-radius:var(--radius-sm); cursor:pointer; }
1219
- .teal-btn:hover { background:var(--teal-600); }
1220
- .stat-row { display:grid; grid-template-columns:repeat(3,1fr); gap:10px; margin-bottom:16px; }
1221
- .stat-box { background:var(--bg2); border-radius:var(--radius-sm); padding:14px; text-align:center; }
1222
- .stat-n { font-size:28px; font-weight:700; color:var(--text); line-height:1; }
1223
- .stat-l { font-size:11px; color:var(--text3); margin-top:4px; }
1224
- .history-list { display:flex; flex-direction:column; }
1225
- .h-item { display:flex; align-items:center; justify-content:space-between; padding:12px 0; border-bottom:0.5px solid var(--border); gap:12px; }
1226
- .h-item:last-child { border-bottom:none; }
1227
- .h-title { font-size:14px; font-weight:500; color:var(--text); }
1228
- .h-meta { font-size:12px; color:var(--text3); margin-top:2px; }
1229
- .h-badge { font-size:11px; font-weight:600; padding:3px 9px; border-radius:var(--radius-full); flex-shrink:0; }
1230
- .h-badge.like { background:var(--teal-50); color:var(--teal-600); }
1231
- .h-badge.pass { background:var(--gray-50); color:var(--gray-600); }
1232
- .empty { text-align:center; padding:40px 20px; color:var(--text3); font-size:14px; }
1233
- .empty i { font-size:40px; display:block; margin-bottom:10px; color:var(--gray-100); }
1234
- .toast { position:fixed; bottom:24px; left:50%; transform:translateX(-50%) translateY(12px); background:var(--text); color:var(--bg); padding:10px 20px; border-radius:var(--radius-full); font-size:13px; opacity:0; transition:all 0.3s; z-index:999; white-space:nowrap; pointer-events:none; }
1235
- .toast.show { opacity:1; transform:translateX(-50%) translateY(0); }
1236
- .loading-dots::after { content:''; animation:dots 1.2s steps(4) infinite; }
1237
- @keyframes dots { 0%{content:'.'} 33%{content:'..'} 66%{content:'...'} 100%{content:''} }
1238
- </style>
1239
- </head>
1240
- <body>
1241
- <div class="app-shell">
1242
- <header>
1243
- <div class="logo">Boolook <span>๋ถ๋ฃฉ</span></div>
1244
- <div class="user-pill" id="uid-pill">uid: ...</div>
1245
- </header>
1246
- <nav>
1247
- <button class="nav-btn active" data-tab="recommend"><i class="ti ti-book-2"></i>์ถ”์ฒœ</button>
1248
- <button class="nav-btn" data-tab="survey"><i class="ti ti-adjustments-horizontal"></i>์ทจํ–ฅ ์„ค์ •</button>
1249
- <button class="nav-btn" data-tab="history"><i class="ti ti-history"></i>๋‚ด ํ™œ๋™</button>
1250
- </nav>
1251
- <div id="tab-recommend" class="tab active">
1252
- <div class="voice-card" id="voice-card">
1253
- <button class="mic-btn" id="mic-btn" aria-label="๋…น์Œ ์‹œ์ž‘"><i class="ti ti-microphone" id="mic-icon"></i></button>
1254
- <div class="voice-title" id="v-title">์˜ค๋Š˜ ๊ธฐ๋ถ„์„ ๋งํ•ด๋ณด์„ธ์š”</div>
1255
- <div class="voice-sub" id="v-sub">๋ฒ„ํŠผ์„ ๋ˆŒ๋Ÿฌ ๋…น์Œ ์‹œ์ž‘</div>
1256
- <div class="waveform" id="waveform" style="display:none">
1257
- <div class="wb"></div><div class="wb"></div><div class="wb"></div><div class="wb"></div><div class="wb"></div><div class="wb"></div><div class="wb"></div>
1258
- </div>
1259
- </div>
1260
- <div class="chips" id="example-chips">
1261
- <div class="chip" data-ex>๐Ÿ˜ข ์Šฌํผ์š”</div>
1262
- <div class="chip" data-ex>๐Ÿ˜Š ํ–‰๋ณตํ•ด์š”</div>
1263
- <div class="chip" data-ex>๐Ÿ˜ค ํ™”๊ฐ€ ๋‚˜์š”</div>
1264
- <div class="chip" data-ex>๐Ÿ˜Œ ํ‰์˜จํ•ด์š”</div>
1265
- <div class="chip" data-ex>๐Ÿ˜ฐ ๋ถˆ์•ˆํ•ด์š”</div>
1266
- <div class="chip" data-ex>๐ŸŽ‰ ์„ค๋ ˆ์–ด์š”</div>
1267
- </div>
1268
- <div class="divider"><span>๋˜๋Š” ์ง์ ‘ ์ž…๋ ฅ</span></div>
1269
- <div class="input-row">
1270
- <input type="text" id="txt-input" placeholder="์ง€๊ธˆ ๊ธฐ๋ถ„์„ ๊ธ€๋กœ ํ‘œํ˜„ํ•ด๋ณด์„ธ์š”..." />
1271
- <button class="icon-btn" id="clear-btn" aria-label="์ง€์šฐ๊ธฐ"><i class="ti ti-x"></i></button>
1272
- </div>
1273
- <button class="primary-btn" id="analyze-btn">๊ฐ์ • ๋ถ„์„ํ•˜๊ณ  ์ฑ… ์ถ”์ฒœ๋ฐ›๊ธฐ</button>
1274
- <div id="emo-section" style="display:none">
1275
- <div class="section-label">๊ฐ์ • ๋ถ„์„</div>
1276
- <div class="emotion-banner">
1277
- <div class="emotion-icon" id="emo-icon">๐Ÿ˜Š</div>
1278
- <div><div class="emotion-name" id="emo-name">๊ธฐ์จ</div><div class="emotion-sub" id="emo-sub"></div></div>
1279
- </div>
1280
- <div class="emotion-bars" id="emo-bars"></div>
1281
- <div class="section-label">์ถ”์ฒœ ๋„์„œ</div>
1282
- <div class="book-list" id="book-list"></div>
1283
- <button class="send-fb-btn" id="send-fb-btn"><i class="ti ti-send"></i> ํ”ผ๋“œ๋ฐฑ ์ „์†กํ•˜๊ธฐ</button>
1284
- </div>
1285
- </div>
1286
- <div id="tab-survey" class="tab">
1287
- <div class="success-msg" id="survey-ok"><i class="ti ti-circle-check"></i> ์ทจํ–ฅ์ด ์ €์žฅ๋์–ด์š”. ๋‹ค์Œ ์ถ”์ฒœ๋ถ€ํ„ฐ ๋ฐ˜์˜๋ฉ๋‹ˆ๋‹ค.</div>
1288
- <div class="card">
1289
- <div class="section-label" style="margin-bottom:12px">์„ ํ˜ธํ•˜๋Š” ์ฑ… ์Šคํƒ€์ผ</div>
1290
- <div class="field"><label>์ž์œ ๋กญ๊ฒŒ ์„ค๋ช…ํ•ด์ฃผ์„ธ์š”</label>
1291
- <textarea id="pref-text" placeholder="์˜ˆ: ์—ญ๊ฒฝ์„ ๊ทน๋ณตํ•˜๋Š” ์„ฑ์žฅ ์ด์•ผ๊ธฐ๋ฅผ ์ข‹์•„ํ•ด์š”. ํ•ดํ”ผ์—”๋”ฉ์ด๋ฉด ๋” ์ข‹๊ณ ์š”."></textarea>
1292
- <div class="hint">๊ตฌ์ฒด์ ์ผ์ˆ˜๋ก ์ถ”์ฒœ์ด ๋” ์ •ํ™•ํ•ด์ง‘๋‹ˆ๋‹ค</div></div>
1293
- <div class="field" style="margin-bottom:0"><label>์„ ํ˜ธ ์žฅ๋ฅด</label>
1294
- <div class="chips" id="genre-chips" style="margin-bottom:0">
1295
- <div class="chip" data-genre>์†Œ์„ค</div><div class="chip" data-genre>์ž๊ธฐ๊ณ„๋ฐœ</div>
1296
- <div class="chip" data-genre>์—์„ธ์ด</div><div class="chip" data-genre>์—ญ์‚ฌ</div>
1297
- <div class="chip" data-genre>๊ณผํ•™</div><div class="chip" data-genre>์ฒ ํ•™</div>
1298
- <div class="chip" data-genre>์ถ”๋ฆฌ/์Šค๋ฆด๋Ÿฌ</div><div class="chip" data-genre>ํŒํƒ€์ง€</div>
1299
- <div class="chip" data-genre>๋กœ๋งจ์Šค</div><div class="chip" data-genre>๊ฒฝ์ œ/๊ฒฝ์˜</div>
1300
- </div></div>
1301
- </div>
1302
- <div class="card">
1303
- <div class="section-label" style="margin-bottom:12px">๋…์„œ ์Šคํƒ€์ผ</div>
1304
- <div class="field"><label>์„ ํ˜ธํ•˜๋Š” ์ฑ… ๋‘๊ป˜</label>
1305
- <div class="slider-row"><span class="slider-end">์–‡์€</span>
1306
- <input type="range" min="1" max="5" value="3" step="1" id="thickness">
1307
- <span class="slider-end">๋‘๊บผ์šด</span><span class="slider-val" id="thickness-val">๋ณดํ†ต</span></div></div>
1308
- <div class="field"><label>๋…์„œ ๋ชฉ์ </label>
1309
- <div class="chips" id="purpose-chips" style="margin-bottom:0">
1310
- <div class="chip" data-purpose>์œ„๋กœ๋ฐ›๊ณ  ์‹ถ์–ด์š”</div><div class="chip" data-purpose>์ง€์‹์„ ์Œ“๊ณ  ์‹ถ์–ด์š”</div>
1311
- <div class="chip" data-purpose>ํ˜„์‹ค์„ ์žŠ๊ณ  ์‹ถ์–ด์š”</div><div class="chip" data-purpose>์˜๊ฐ์„ ์–ป๊ณ  ์‹ถ์–ด์š”</div>
1312
- <div class="chip" data-purpose>์žฌ๋ฏธ๋งŒ ์žˆ์œผ๋ฉด ๋ผ์š”</div></div></div>
1313
- <div class="field" style="margin-bottom:0"><label>์ตœ๊ทผ ์ธ์ƒ ๊นŠ๊ฒŒ ์ฝ์€ ์ฑ…</label>
1314
- <input type="text" id="last-book" placeholder="์ฑ… ์ œ๋ชฉ์„ ์ž…๋ ฅํ•˜์„ธ์š”"></div>
1315
- </div>
1316
- <button class="teal-btn" id="survey-btn"><i class="ti ti-check"></i> ์ทจํ–ฅ ์ €์žฅํ•˜๊ธฐ</button>
1317
- </div>
1318
- <div id="tab-history" class="tab">
1319
- <div class="stat-row">
1320
- <div class="stat-box"><div class="stat-n" id="s-total">0</div><div class="stat-l">์ถ”์ฒœ๋ฐ›์Œ</div></div>
1321
- <div class="stat-box"><div class="stat-n" id="s-liked">0</div><div class="stat-l">์ข‹์•„์š”</div></div>
1322
- <div class="stat-box"><div class="stat-n" id="s-sessions">0</div><div class="stat-l">๋ถ„์„ ํšŸ์ˆ˜</div></div>
1323
- </div>
1324
- <div class="section-label">์ตœ๊ทผ ๊ฐ์ • ๋ถ„ํฌ</div>
1325
- <div class="card" style="margin-bottom:16px"><div id="emo-history" class="empty"><i class="ti ti-mood-empty"></i>์•„์ง ๊ธฐ๋ก์ด ์—†์–ด์š”</div></div>
1326
- <div class="section-label">์ถ”์ฒœ ๊ธฐ๋ก</div>
1327
- <div class="card"><div class="history-list" id="hist-list"><div class="empty"><i class="ti ti-books"></i>์ถ”์ฒœ๋ฐ›์€ ์ฑ…์ด ์—†์–ด์š”</div></div></div>
1328
- </div>
1329
- </div>
1330
- <div class="toast" id="toast"></div>
1331
- </body>
1332
- </html>"""
1333
-
1334
-
1335
- CUSTOM_JS = """
1336
- () => {
1337
- const EMOTIONS = ['๊ธฐ์จ','ํ‰์˜จ','๊ณตํฌ','๋†€๋žŒ','์Šฌํ””','ํ˜์˜ค','๋ถ„๋…ธ','๊ธฐ๋Œ€'];
1338
- const EMO_ICONS = {๊ธฐ์จ:'๐Ÿ˜Š',ํ‰์˜จ:'๐Ÿ˜Œ',๊ณตํฌ:'๐Ÿ˜ฑ',๋†€๋žŒ:'๐Ÿ˜ฒ',์Šฌํ””:'๐Ÿ˜ข',ํ˜์˜ค:'๐Ÿ˜ ',๋ถ„๋…ธ:'๐Ÿ˜ค',๊ธฐ๋Œ€:'๐ŸŽ‰'};
1339
- const st = { uid:'U'+String(Math.floor(Math.random()*90000+10000)),
1340
- recording:false, mr:null, chunks:[], rtimer:null,
1341
- curEmo:null, curBooks:[], feedbacks:{}, history:[], emoCounts:{}, sessions:0 };
1342
-
1343
- const $ = id => document.getElementById(id);
1344
- const pill = $('uid-pill'); if (pill) pill.textContent = 'uid: ' + st.uid;
1345
-
1346
- function toast(msg){ const el=$('toast'); if(!el) return; el.textContent=msg; el.classList.add('show'); setTimeout(()=>el.classList.remove('show'),2600); }
1347
-
1348
- function go(tab, btn){
1349
- document.querySelectorAll('.tab').forEach(t=>t.classList.remove('active'));
1350
- document.querySelectorAll('.nav-btn').forEach(b=>b.classList.remove('active'));
1351
- $('tab-'+tab).classList.add('active');
1352
- btn.classList.add('active');
1353
- if(tab==='history') renderHistory();
1354
- }
1355
-
1356
- // ===== Gradio API ํ—ฌํผ =====
1357
- async function gradioCall(name, dataArr){
1358
- const r = await fetch('/gradio_api/call/'+name, {
1359
- method:'POST', headers:{'Content-Type':'application/json'},
1360
- body: JSON.stringify({data: dataArr})
1361
- });
1362
- if(!r.ok) throw new Error('api '+name+' failed');
1363
- const j = await r.json();
1364
- const sr = await fetch('/gradio_api/call/'+name+'/'+j.event_id);
1365
- const txt = await sr.text();
1366
- const line = txt.split('\\n').find(l=>l.startsWith('data:'));
1367
- return JSON.parse(line.slice(5));
1368
- }
1369
-
1370
- // ํŒŒ์ผ ์—…๋กœ๋“œ -> Gradio ๊ฐ€ ์ธ์‹ํ•˜๋Š” ํŒŒ์ผ ์ฐธ์กฐ ๊ฐ์ฒด ๋ฐ˜ํ™˜
1371
- async function uploadBlob(blob, filename){
1372
- const fd = new FormData();
1373
- fd.append('files', blob, filename);
1374
- const r = await fetch('/gradio_api/upload', {method:'POST', body:fd});
1375
- if(!r.ok) throw new Error('upload failed');
1376
- const paths = await r.json(); // ["/tmp/gradio/xxx/rec.webm"]
1377
- const p = paths[0];
1378
- return { path: p, meta: {_type:'gradio.FileData'}, orig_name: filename, url:null, size:blob.size, mime_type:blob.type };
1379
- }
1380
-
1381
- // ===== ๋…น์Œ =====
1382
- async function toggleRec(){ st.recording ? stopRec() : await startRec(); }
1383
- async function startRec(){
1384
- try{
1385
- const stream = await navigator.mediaDevices.getUserMedia({audio:true});
1386
- st.mr = new MediaRecorder(stream); st.chunks=[];
1387
- st.mr.ondataavailable = e => { if(e.data.size>0) st.chunks.push(e.data); };
1388
- st.mr.onstop = () => { processAudio(); stream.getTracks().forEach(t=>t.stop()); };
1389
- st.mr.start(); st.recording=true;
1390
- $('voice-card').classList.add('recording');
1391
- $('mic-btn').classList.add('recording');
1392
- $('mic-icon').className='ti ti-player-stop';
1393
- $('v-title').textContent='๋…น์Œ ์ค‘...';
1394
- $('v-sub').textContent='๋‹ค์‹œ ๋ˆ„๋ฅด๋ฉด ๋ถ„์„ ์‹œ์ž‘';
1395
- $('waveform').style.display='flex';
1396
- st.rtimer=setTimeout(()=>{ if(st.recording) stopRec(); },15000);
1397
- }catch(e){ toast('๋งˆ์ดํฌ ์ ‘๊ทผ ๊ถŒํ•œ์ด ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค'); }
1398
- }
1399
- function stopRec(){
1400
- clearTimeout(st.rtimer); st.recording=false;
1401
- if(st.mr) st.mr.stop();
1402
- $('voice-card').classList.remove('recording');
1403
- $('mic-btn').classList.remove('recording');
1404
- $('mic-icon').className='ti ti-microphone';
1405
- $('v-title').textContent='๋ถ„์„ ์ค‘...';
1406
- $('v-sub').textContent='์Œ์„ฑ์„ ์„œ๋ฒ„๋กœ ์ „์†กํ•˜๊ณ  ์žˆ์–ด์š”';
1407
- $('waveform').style.display='none';
1408
- }
1409
-
1410
- // ๋…น์Œ blob -> ์—…๋กœ๋“œ -> voice_recommend(STT+๊ฐ์ •+์ถ”์ฒœ)
1411
- async function processAudio(){
1412
- const btn=$('analyze-btn');
1413
- try{
1414
- if(!st.chunks.length){ throw new Error('๋นˆ ๋…น์Œ'); }
1415
- const blob = new Blob(st.chunks, {type: st.mr.mimeType || 'audio/webm'});
1416
- const ext = (blob.type.includes('ogg')?'ogg':(blob.type.includes('wav')?'wav':'webm'));
1417
- btn.disabled=true; btn.innerHTML='<span class="loading-dots">์Œ์„ฑ ๋ถ„์„ ์ค‘</span>';
1418
-
1419
- const fileRef = await uploadBlob(blob, 'rec.'+ext);
1420
- const out = await gradioCall('voice_recommend', [fileRef, st.uid]);
1421
- // voice_recommend -> [json_str, books_state]; json_str ์‚ฌ์šฉ
1422
- const res = JSON.parse(out[0]);
1423
- $('v-title').textContent='์˜ค๋Š˜ ๊ธฐ๋ถ„์„ ๋งํ•ด๋ณด์„ธ์š”';
1424
- $('v-sub').textContent='๋ฒ„ํŠผ์„ ๋ˆŒ๋Ÿฌ ๋…น์Œ ์‹œ์ž‘';
1425
-
1426
- if(res.error){ toast(res.error); fallbackText(); return; }
1427
- if(res.user_input){ $('txt-input').value = res.user_input; }
1428
- applyResult(res.emotion, res.emotion_scores || buildScores(res),
1429
- (res.recommendation_books||[]).map((b,i)=>({t:b.title,a:b.author,p:b.publisher,d:b.content,isbn:b.isbn,rank:i+1})));
1430
- btn.disabled=false; btn.textContent='๊ฐ์ • ๋ถ„์„ํ•˜๊ณ  ์ฑ… ์ถ”์ฒœ๋ฐ›๊ธฐ';
1431
- }catch(e){
1432
- $('v-title').textContent='์˜ค๋Š˜ ๊ธฐ๋ถ„์„ ๋งํ•ด๋ณด์„ธ์š”';
1433
- $('v-sub').textContent='๋ฒ„ํŠผ์„ ๋ˆŒ๋Ÿฌ ๋…น์Œ ์‹œ์ž‘';
1434
- btn.disabled=false; btn.textContent='๊ฐ์ • ๋ถ„์„ํ•˜๊ณ  ์ฑ… ์ถ”์ฒœ๋ฐ›๊ธฐ';
1435
- toast('์„œ๋ฒ„ ์Œ์„ฑ ๋ถ„์„ ์‹คํŒจ โ€” ํ…์ŠคํŠธ๋กœ ์ž…๋ ฅํ•ด๋ณด์„ธ์š”');
1436
- }
1437
- }
1438
- function buildScores(res){ const s={}; EMOTIONS.forEach(e=>s[e]= e===res.emotion ? (res.emotion_score||1):0.05); return s; }
1439
- function fallbackText(){ if($('txt-input').value.trim()) analyze(); }
1440
-
1441
- function applyResult(top, scores, books){
1442
- if(!top){ toast('๊ฐ์ •์„ ์ธ์‹ํ•˜์ง€ ๋ชปํ–ˆ์–ด์š”'); return; }
1443
- if(!books || !books.length){ books = getBooks(top); }
1444
- st.curEmo=top; st.sessions++;
1445
- st.emoCounts[top]=(st.emoCounts[top]||0)+1;
1446
- renderEmo(top, scores);
1447
- st.curBooks=books; st.feedbacks={};
1448
- renderBooks(books);
1449
- $('emo-section').style.display='block';
1450
- $('emo-section').scrollIntoView({behavior:'smooth',block:'start'});
1451
- }
1452
-
1453
- function useEx(el){ $('txt-input').value = el.textContent.replace(/^[^๊ฐ€-ํžฃa-zA-Z]+/,'').trim(); }
1454
- function clearTxt(){ $('txt-input').value=''; }
1455
-
1456
- async function callRecommend(text){
1457
- try{
1458
- const out = await gradioCall('recommend', [JSON.stringify({user_id: st.uid, text: text})]);
1459
- return JSON.parse(out[0]);
1460
- }catch(e){ return null; }
1461
- }
1462
-
1463
- async function analyze(){
1464
- const txt = $('txt-input').value.trim();
1465
- if(!txt){ toast('๊ฐ์ •์„ ์ž…๋ ฅํ•˜๊ฑฐ๋‚˜ ๋งํ•ด์ฃผ์„ธ์š”'); return; }
1466
- const btn=$('analyze-btn');
1467
- btn.disabled=true; btn.innerHTML='<span class="loading-dots">๋ถ„์„ ์ค‘</span>';
1468
- const res = await callRecommend(txt);
1469
- let top, scores, books;
1470
- if(res && res.emotion && res.recommendation_books && res.recommendation_books.length){
1471
- top=res.emotion; scores=res.emotion_scores||{};
1472
- books=res.recommendation_books.map((b,i)=>({t:b.title,a:b.author,p:b.publisher,d:b.content,isbn:b.isbn,rank:i+1}));
1473
- }else{
1474
- scores=simEmo(txt); top=Object.entries(scores).sort((a,b)=>b[1]-a[1])[0][0]; books=getBooks(top);
1475
- }
1476
- applyResult(top, scores, books);
1477
- btn.disabled=false; btn.textContent='๊ฐ์ • ๋ถ„์„ํ•˜๊ณ  ์ฑ… ์ถ”์ฒœ๋ฐ›๊ธฐ';
1478
- }
1479
-
1480
- function simEmo(txt){
1481
- const kw={๊ธฐ์จ:['๊ธฐ์˜','ํ–‰๋ณต','์ข‹','์ฆ','์‹ ๋‚˜'],์Šฌํ””:['์Šฌํ”„','์šฐ์šธ','๋ˆˆ๋ฌผ','ํž˜๋“ค','์™ธ๋กœ'],๋ถ„๋…ธ:['ํ™”๋‚˜','์งœ์ฆ','์—ด๋ฐ›','์–ต์šธ'],๊ณตํฌ:['๋ฌด์„ญ','๋‘๋ ต','๊ฑฑ์ •','๋ถˆ์•ˆ'],๋†€๋žŒ:['๋†€๋ž','๊นœ์ง','์ถฉ๊ฒฉ'],ํ‰์˜จ:['ํ‰์˜จ','๋”ฐ๋œป','์ฐจ๋ถ„','๊ดœ์ฐฎ'],๊ธฐ๋Œ€:['๊ธฐ๋Œ€','ํฌ๋ง','์„ค๋ ˆ'],ํ˜์˜ค:['์‹ซ','๋ณ„๋กœ','์ง€๊ฒจ']};
1482
- const s={}; EMOTIONS.forEach(e=>s[e]=0.05+Math.random()*0.08);
1483
- Object.entries(kw).forEach(([e,ks])=>ks.forEach(k=>{ if(txt.includes(k)) s[e]+=0.4; }));
1484
- const tot=Object.values(s).reduce((a,b)=>a+b,0); Object.keys(s).forEach(k=>s[k]/=tot); return s;
1485
- }
1486
- function renderEmo(top, scores){
1487
- $('emo-icon').textContent=EMO_ICONS[top]||'๐Ÿ’ญ';
1488
- $('emo-name').textContent=top;
1489
- $('emo-sub').textContent=top+' ๊ฐ์ •์„ ๊ธฐ๋ฐ˜์œผ๋กœ ์ฑ…์„ ๊ณจ๋ž์–ด์š”';
1490
- const sorted=Object.entries(scores).sort((a,b)=>b[1]-a[1]).slice(0,5);
1491
- $('emo-bars').innerHTML=sorted.map(([e,v])=>
1492
- `<div class="eb-row"><span class="eb-name">${e}</span><div class="eb-track"><div class="eb-fill ${e===top?'top':''}" style="width:${Math.round(v*100)}%"></div></div><span class="eb-val">${Math.round(v*100)}%</span></div>`).join('');
1493
- }
1494
-
1495
- const BOOKS_DB = {
1496
- ๊ธฐ์จ:[{t:'์•„๋ชฌ๋“œ',a:'์†์›ํ‰',p:'์ฐฝ๋น„',d:'๊ฐ์ •์„ ๋А๋ผ์ง€ ๋ชปํ•˜๋Š” ์†Œ๋…„์˜ ๋”ฐ๋œปํ•œ ์„ฑ์žฅ ์ด์•ผ๊ธฐ'},{t:'82๋…„์ƒ ๊น€์ง€์˜',a:'์กฐ๋‚จ์ฃผ',p:'๋ฏผ์Œ์‚ฌ',d:'ํ‰๋ฒ”ํ•œ ์—ฌ์„ฑ์˜ ์‚ถ์„ ํ†ตํ•ด ์šฐ๋ฆฌ ์‚ฌํšŒ๋ฅผ ๋“ค์—ฌ๋‹ค๋ณด๋Š” ์ด์•ผ๊ธฐ'},{t:'์ฑ„์‹์ฃผ์˜์ž',a:'ํ•œ๊ฐ•',p:'์ฐฝ๋น„',d:'์ž์œ ์™€ ์ €ํ•ญ, ์ธ๊ฐ„ ์กด์—„์„ ๋‹ค๋ฃฌ ์—ฐ์ž‘ ์†Œ์„ค'}],
1497
- ์Šฌํ””:[{t:'์†Œ๋…„์ด ์˜จ๋‹ค',a:'ํ•œ๊ฐ•',p:'์ฐฝ๋น„',d:'1980๋…„ ๊ด‘์ฃผ๋ฅผ ๋ฐฐ๊ฒฝ์œผ๋กœ ํ•œ ์•„ํ””๊ณผ ์ธ๊ฐ„ ์กด์—„์˜ ์ด์•ผ๊ธฐ'},{t:'์—„๋งˆ๋ฅผ ๋ถ€ํƒํ•ด',a:'์‹ ๊ฒฝ์ˆ™',p:'์ฐฝ๋น„',d:'์‹ค์ข…๋œ ์—„๋งˆ๋ฅผ ์ฐพ์œผ๋ฉฐ ๊นจ๋‹ซ๋Š” ๊ฐ€์กฑ์˜ ์‚ฌ๋ž‘๊ณผ ์ƒ์‹ค'},{t:'๋‚˜๋Š” ๋‚˜๋ฅผ ํŒŒ๊ดดํ•  ๊ถŒ๋ฆฌ๊ฐ€ ์žˆ๋‹ค',a:'๊น€์˜ํ•˜',p:'๋ฌธํ•™๋™๋„ค',d:'์‚ถ๊ณผ ์ฃฝ์Œ์˜ ๊ฒฝ๊ณ„์— ์„  ์ธ๊ฐ„ ์ด์•ผ๊ธฐ'}],
1498
- ๋ถ„๋…ธ:[{t:'ํŒŒ์นœ์ฝ”',a:'์ด๋ฏผ์ง„',p:'์ธํ”Œ๋ฃจ์—”์…œ',d:'์žฌ์ผ๊ตํฌ 4๋Œ€ ๊ฐ€์กฑ์˜ ์–ต์••๊ณผ ์ €ํ•ญ์„ ๊ทธ๋ฆฐ ๋Œ€์„œ์‚ฌ์‹œ'},{t:'๋„๊ฐ€๋‹ˆ',a:'๊ณต์ง€์˜',p:'์ฐฝ๋น„',d:'์‚ฌํšŒ ๋ถ€์กฐ๋ฆฌ์— ๋งž์„œ ์‹ธ์šฐ๋Š” ์ด์•ผ๊ธฐ'},{t:'1984',a:'์กฐ์ง€ ์˜ค์›ฐ',p:'๋ฏผ์Œ์‚ฌ',d:'์ „์ฒด์ฃผ์˜ ์‚ฌํšŒ์˜ ๊ฐ์‹œ์™€ ํ†ต์ œ๋ฅผ ๋‹ค๋ฃฌ ๋””์Šคํ† ํ”ผ์•„ ์†Œ์„ค'}],
1499
- ํ‰์˜จ:[{t:'๋‹น์‹ ์ด ์˜ณ๋‹ค',a:'์ •ํ˜œ์‹ ',p:'ํ•ด๋ƒ„',d:'๊ณต๊ฐ๊ณผ ์œ„๋กœ์˜ ์‹ฌ๋ฆฌ ์—์„ธ์ด'},{t:'๋ฐ๋ฏธ์•ˆ',a:'ํ—ค๋ฅด๋งŒ ํ—ค์„ธ',p:'๋ฏผ์Œ์‚ฌ',d:'์ž์•„๋ฅผ ์ฐพ๋Š” ์ฒญ๋…„์˜ ์„ฑ์žฅ๊ณผ ๋‚ด๋ฉด ํƒ๊ตฌ๋ฅผ ๋‹ด์€ ๊ณ ์ „'},{t:'์—ฐ์„ ์ซ“๋Š” ์•„์ด',a:'ํ• ๋ ˆ๋“œ ํ˜ธ์„ธ์ด๋‹ˆ',p:'์—ด๋ฆฐ์ฑ…๋“ค',d:'์•„ํ”„๊ฐ€๋‹ˆ์Šคํƒ„์„ ๋ฐฐ๊ฒฝ์œผ๋กœ ํ•œ ์šฐ์ •๊ณผ ์†์ฃ„์˜ ์ด์•ผ๊ธฐ'}],
1500
- ๊ธฐ๋Œ€:[{t:'์–ด๋ฆฐ ์™•์ž',a:'์ƒํ…์ฅํŽ˜๋ฆฌ',p:'์—ด๋ฆฐ์ฑ…๋“ค',d:'๋‹ค๋ฅธ ๋ณ„์—์„œ ์˜จ ์™•์ž์™€ ์กฐ์ข…์‚ฌ์˜ ๋”ฐ๋œปํ•œ ๋งŒ๋‚จ'},{t:'ํ•ด๋ฆฌ ํฌํ„ฐ',a:'J.K. ๋กค๋ง',p:'๋ฌธํ•™์ˆ˜์ฒฉ',d:'๋งˆ๋ฒ• ์„ธ๊ณ„์—์„œ ํŽผ์ณ์ง€๋Š” ์„ฑ์žฅ๊ณผ ๋ชจํ—˜์˜ ์ด์•ผ๊ธฐ'},{t:'์™„์ „ํ•œ ํ–‰๋ณต',a:'์ •์œ ์ •',p:'์€ํ–‰๋‚˜๋ฌด',d:'์ธ๊ฐ„์˜ ํ–‰๋ณต๊ณผ ์š•๋ง์˜ ๊ฒฝ๊ณ„๋ฅผ ํƒ์ƒ‰ํ•˜๋Š” ์‹ฌ๋ฆฌ ์Šค๋ฆด๋Ÿฌ'}],
1501
- ๊ณตํฌ:[{t:'์ข…์˜ ๊ธฐ์›',a:'์ •์œ ์ •',p:'์€ํ–‰๋‚˜๋ฌด',d:'์ธ๊ฐ„์˜ ๋ณธ์„ฑ๊ณผ ์•…์— ๋Œ€ํ•ด ํƒ๊ตฌํ•˜๋Š” ์‹ฌ๋ฆฌ ์Šค๋ฆด๋Ÿฌ'},{t:'28',a:'์ •์œ ์ •',p:'์€ํ–‰๋‚˜๋ฌด',d:'์ „์—ผ๋ณ‘์ด ์ฐฝ๊ถํ•˜๋Š” ์ƒํ™ฉ์˜ ๊ณตํฌ์™€ ์ƒ์กด ์ด์•ผ๊ธฐ'},{t:'์…”ํ„ฐ ์•„์ผ๋žœ๋“œ',a:'๋ฐ๋‹ˆ์Šค ๋ฃจํ—ค์ธ',p:'ํ™ฉ๊ธˆ๊ฐ€์ง€',d:'์ •์‹ ๋ณ‘์›์—์„œ ๋ฒŒ์–ด์ง€๋Š” ๋ฏธ์Šคํ„ฐ๋ฆฌ ์Šค๋ฆด๋Ÿฌ'}],
1502
- ๋†€๋žŒ:[{t:'์…œ๋ก ํ™ˆ์ฆˆ ์ „์ง‘',a:'์ฝ”๋‚œ ๋„์ผ',p:'ํ™ฉ๊ธˆ๊ฐ€์ง€',d:'์ฒœ์žฌ ํƒ์ •์˜ ๋†€๋ผ์šด ์ถ”๋ฆฌ ์ด์•ผ๊ธฐ'},{t:'๊ธฐ์–ต ์ „๋‹ฌ์ž',a:'๋กœ์ด์Šค ๋กœ๋ฆฌ',p:'๋น„๋ฃก์†Œ',d:'์œ ํ† ํ”ผ์•„ ์‚ฌํšŒ์˜ ๋น„๋ฐ€์„ ํŒŒํ—ค์น˜๋Š” ์ด์•ผ๊ธฐ'},{t:'๋ฐ˜์ง€์˜ ์ œ์™•',a:'ํ†จํ‚จ',p:'์”จ์•—์„๋ฟŒ๋ฆฌ๋Š”์‚ฌ๋žŒ',d:'์ค‘๊ฐ„๊ณ„๋ฅผ ๊ตฌํ•˜๊ธฐ ์œ„ํ•œ ํŒํƒ€์ง€ ๋Œ€์„œ์‚ฌ์‹œ'}],
1503
- ํ˜์˜ค:[{t:'๋™๋ฌผ ๋†์žฅ',a:'์กฐ์ง€ ์˜ค์›ฐ',p:'๋ฏผ์Œ์‚ฌ',d:'๊ถŒ๋ ฅ์˜ ๋ถ€ํŒจ์™€ ๋…์žฌ๋ฅผ ์šฐํ™”์ ์œผ๋กœ ๊ทธ๋ฆฐ ์†Œ์„ค'},{t:'๋ฉ‹์ง„ ์‹ ์„ธ๊ณ„',a:'์˜ฌ๋”์Šค ํ—‰์Šฌ๋ฆฌ',p:'๋ฌธ์˜ˆ์ถœํŒ์‚ฌ',d:'์พŒ๋ฝ์œผ๋กœ ํ†ต์ œ๋˜๋Š” ๋ฏธ๋ž˜ ์‚ฌํšŒ๋ฅผ ํ’์žํ•œ ์†Œ์„ค'},{t:'ํ™”์”จ 451',a:'๋ ˆ์ด ๋ธŒ๋ž˜๋“œ๋ฒ„๋ฆฌ',p:'ํ™ฉ๊ธˆ๊ฐ€์ง€',d:'์ฑ…์ด ๊ธˆ์ง€๋œ ๋ฏธ๋ž˜ ์‚ฌํšŒ์—์„œ ๋…์„œ์™€ ์ž์œ ๋ฅผ ์ง€ํ‚ค๋Š” ์ด์•ผ๊ธฐ'}]
1504
- };
1505
- function getBooks(emo){ return (BOOKS_DB[emo]||BOOKS_DB['๊ธฐ์จ']).map((b,i)=>({...b,rank:i+1,isbn:`isbn_${emo}_${i}`})); }
1506
-
1507
- function renderBooks(books){
1508
- $('book-list').innerHTML = books.map((b,i)=>`
1509
- <div class="book-item">
1510
- <div class="book-cover"><i class="ti ti-book-2"></i></div>
1511
- <div class="book-body">
1512
- <div class="book-rank">์ถ”์ฒœ ${b.rank}์œ„</div>
1513
- <div class="book-title">${b.t}</div>
1514
- <div class="book-meta">${b.a} ยท ${b.p}</div>
1515
- <div class="book-desc">${b.d}</div>
1516
- <div class="book-actions">
1517
- <button class="fb-btn" id="like-${i}" data-fb="${i}" data-acc="1"><i class="ti ti-thumb-up"></i> ์ฝ๊ณ  ์‹ถ์–ด์š”</button>
1518
- <button class="fb-btn" id="pass-${i}" data-fb="${i}" data-acc="0"><i class="ti ti-thumb-down"></i> ๋‹ค์Œ์—</button>
1519
- </div>
1520
- </div>
1521
- </div>`).join('');
1522
- $('send-fb-btn').classList.remove('show');
1523
- }
1524
- function setFb(i, acc){
1525
- const b=st.curBooks[i];
1526
- st.feedbacks[i]={isbn:b.isbn,title:b.t,author:b.a,accepted:acc,rank:b.rank};
1527
- $('like-'+i).className='fb-btn'+(acc===1?' liked':'');
1528
- $('pass-'+i).className='fb-btn'+(acc===0?' passed':'');
1529
- const allDone=st.curBooks.every((_,j)=>st.feedbacks[j]!==undefined);
1530
- $('send-fb-btn').className='send-fb-btn'+(allDone?' show':'');
1531
- if(acc===1) st.history.unshift({t:b.t,a:b.a,emo:st.curEmo,liked:true,date:new Date().toLocaleDateString('ko-KR')});
1532
- }
1533
- async function submitFb(){
1534
- const payload={user_id:st.uid,books:Object.values(st.feedbacks).map(f=>({isbn:f.isbn,emotion:st.curEmo,accepted:f.accepted,rank:f.rank}))};
1535
- try{ await gradioCall('feedback',[JSON.stringify(payload)]); }catch(e){}
1536
- toast('ํ”ผ๋“œ๋ฐฑ์ด ์ „์†ก๋์Šต๋‹ˆ๋‹ค. ๊ฐ์‚ฌํ•ด์š”!');
1537
- $('send-fb-btn').classList.remove('show');
1538
- }
1539
-
1540
- function sliderChange(){ const labels=['๋งค์šฐ ์–‡๊ฒŒ','์–‡๊ฒŒ','๋ณดํ†ต','๋‘๊ป๊ฒŒ','์•„์ฃผ ๋‘๊ป๊ฒŒ']; $('thickness-val').textContent=labels[parseInt($('thickness').value)-1]; }
1541
- function singleSel(group, el){ document.querySelectorAll(group+' .chip').forEach(c=>c.classList.remove('sel')); el.classList.add('sel'); }
1542
- async function submitSurvey(){
1543
- const text=$('pref-text').value.trim();
1544
- if(!text){ toast('์„ ํ˜ธํ•˜๋Š” ์ฑ… ์Šคํƒ€์ผ์„ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”'); return; }
1545
- const genres=[...document.querySelectorAll('#genre-chips .chip.sel')].map(e=>e.textContent);
1546
- const purpose=document.querySelector('#purpose-chips .chip.sel');
1547
- const lastBook=$('last-book').value.trim();
1548
- const preferText=[text, genres.length?'์žฅ๋ฅด: '+genres.join(', '):'', purpose?'๋ชฉ์ : '+purpose.textContent:'', lastBook?'์ตœ๊ทผ ์ฝ์€ ์ฑ…: '+lastBook:''].filter(Boolean).join(' | ');
1549
- try{ await gradioCall('survey',[JSON.stringify({user_id:st.uid,prefer_text:preferText})]); }catch(e){}
1550
- $('survey-ok').classList.add('show');
1551
- toast('์ทจํ–ฅ์ด ์ €์žฅ๋์–ด์š”!');
1552
- setTimeout(()=>$('survey-ok').classList.remove('show'),4000);
1553
- }
1554
-
1555
- function renderHistory(){
1556
- $('s-total').textContent=st.history.length;
1557
- $('s-liked').textContent=st.history.filter(h=>h.liked).length;
1558
- $('s-sessions').textContent=st.sessions;
1559
- const counts=st.emoCounts; const maxC=Math.max(...Object.values(counts),1);
1560
- const emoEl=$('emo-history');
1561
- if(Object.keys(counts).length>0){
1562
- emoEl.className='emotion-bars';
1563
- emoEl.innerHTML=Object.entries(counts).sort((a,b)=>b[1]-a[1]).map(([e,c])=>
1564
- `<div class="eb-row"><span class="eb-name">${e}</span><div class="eb-track"><div class="eb-fill" style="width:${Math.round(c/maxC*100)}%"></div></div><span class="eb-val">${c}ํšŒ</span></div>`).join('');
1565
- }
1566
- const listEl=$('hist-list');
1567
- if(st.history.length>0){
1568
- listEl.className='history-list';
1569
- listEl.innerHTML=st.history.slice(0,10).map(h=>`
1570
- <div class="h-item"><div><div class="h-title">${h.t}</div><div class="h-meta">${h.a} ยท ${h.emo} ยท ${h.date}</div></div>
1571
- <span class="h-badge ${h.liked?'like':'pass'}">${h.liked?'์ฝ๊ณ  ์‹ถ์–ด์š”':'๋‹ค์Œ์—'}</span></div>`).join('');
1572
- }
1573
- }
1574
-
1575
- // ===== ์ด๋ฒคํŠธ ๋ฐ”์ธ๋”ฉ =====
1576
- document.querySelectorAll('.nav-btn').forEach(b=>b.addEventListener('click',()=>go(b.dataset.tab,b)));
1577
- $('mic-btn').addEventListener('click', toggleRec);
1578
- $('clear-btn').addEventListener('click', clearTxt);
1579
- $('analyze-btn').addEventListener('click', analyze);
1580
- $('send-fb-btn').addEventListener('click', submitFb);
1581
- $('survey-btn').addEventListener('click', submitSurvey);
1582
- $('thickness').addEventListener('input', sliderChange);
1583
- document.querySelectorAll('#example-chips .chip').forEach(c=>c.addEventListener('click',()=>useEx(c)));
1584
- document.querySelectorAll('#genre-chips .chip').forEach(c=>c.addEventListener('click',()=>c.classList.toggle('sel')));
1585
- document.querySelectorAll('#purpose-chips .chip').forEach(c=>c.addEventListener('click',()=>singleSel('#purpose-chips',c)));
1586
- $('book-list').addEventListener('click', e=>{
1587
- const btn=e.target.closest('[data-fb]'); if(!btn) return;
1588
- setFb(parseInt(btn.dataset.fb), parseInt(btn.dataset.acc));
1589
- });
1590
- }
1591
- """
1592
 
1593
 
1594
  # ============================================================
1595
- # Gradio ์•ฑ
1596
  # ============================================================
1597
- with gr.Blocks(title="Boolook") as demo:
1598
- gr.HTML(CUSTOM_HTML)
1599
-
1600
- # ์ˆจ๊ฒจ์ง„ API ์—”๋“œํฌ์ธํŠธ (์ปค์Šคํ…€ UI ์˜ fetch ๊ฐ€ ํ˜ธ๏ฟฝ๏ฟฝ๏ฟฝ)
1601
- with gr.Row(visible=False):
1602
- fb_in = gr.Textbox(); fb_out = gr.Textbox(); fb_btn = gr.Button()
1603
- fb_btn.click(fn=api_feedback, inputs=fb_in, outputs=fb_out, api_name="feedback")
1604
-
1605
- sv_in = gr.Textbox(); sv_out = gr.Textbox(); sv_btn = gr.Button()
1606
- sv_btn.click(fn=api_survey, inputs=sv_in, outputs=sv_out, api_name="survey")
1607
-
1608
- rc_in = gr.Textbox(); rc_out = gr.Textbox(); rc_btn = gr.Button()
1609
- rc_btn.click(fn=api_recommend, inputs=rc_in, outputs=rc_out, api_name="recommend")
 
 
 
 
 
 
 
 
 
 
 
 
 
1610
 
1611
- au_in = gr.Audio(type="filepath"); au_out_json = gr.Textbox(); au_out_books = gr.State([]); au_btn = gr.Button()
1612
- au_btn.click(fn=process_voice, inputs=au_in, outputs=[au_out_json, au_out_books], api_name="voice_recommend")
 
 
1613
 
1614
- with gr.Accordion("์šด์˜์ž ํ†ต๊ณ„", open=False):
1615
- stats_md = gr.Markdown("์ƒˆ๋กœ๊ณ ์นจ์„ ๋ˆŒ๋Ÿฌ ํ†ต๊ณ„๋ฅผ ๋ถˆ๋Ÿฌ์˜ต๋‹ˆ๋‹ค.")
1616
- stats_btn = gr.Button("ํ†ต๊ณ„ ์ƒˆ๋กœ๊ณ ์นจ")
1617
- stats_btn.click(fn=get_feedback_stats, outputs=stats_md)
 
 
 
 
 
 
 
1618
 
1619
- # ํ•ต์‹ฌ: gr.HTML ์€ <script>/onclick ์„ ์ œ๊ฑฐํ•˜๋ฏ€๋กœ JS ๋Š” load(js=...) ๋กœ ์ฃผ์ž…
1620
- demo.load(None, None, None, js=CUSTOM_JS)
 
 
 
 
 
 
 
 
 
1621
 
 
 
 
 
 
1622
 
1623
  if __name__ == "__main__":
1624
- demo.launch(share=False)
 
1
  """
2
+ Boolook - ์Œ์„ฑ ๊ธฐ๋ฐ˜ ๊ฐ์ • ๋ถ„์„ ์ฑ… ์ถ”์ฒœ (HuggingFace Spaces)
3
+ + CatBoost ์žฌ์ •๋ ฌ(re-ranking) ํ†ตํ•ฉ ๋ฒ„์ „
 
4
  """
5
 
6
  import gradio as gr
 
10
  import torch.nn as nn
11
  import torch.nn.functional as F
12
  import pickle
13
+ import csv
14
  import json
15
  import threading
16
  import warnings
 
41
  SAMPLE_RATE = 16000
42
  MAX_EMBEDDING_BATCH = 128
43
 
44
+ # Mel-spectrogram ํŒŒ๋ผ๋ฏธํ„ฐ (ํ•™์Šต ์‹œ ์‚ฌ์šฉํ•œ ๊ฐ’๊ณผ ๋™์ผํ•˜๊ฒŒ ๋งž์ถœ ๊ฒƒ)
45
  N_MELS = 64
46
  N_FFT = 1024
47
  HOP_LEN = 512
48
  MAX_FRAMES = 128
49
 
50
+ # CatBoost ํ”ผ์ฒ˜ ์ •์˜ (ํ•™์Šต/์ถ”๋ก  ๋™์ผํ•˜๊ฒŒ ์œ ์ง€)
51
  _CB_FEATURES = ["cosine", "session_w", "survey_mult", "fb_boost", "emotion", "rank_hint"]
52
  _CB_CAT_FEATURES = ["emotion"]
53
 
 
69
 
70
 
71
  def _get_db_conn():
72
+ """DB ์—ฐ๊ฒฐ ๋ฐ˜ํ™˜. ์‹คํŒจ ์‹œ None ๋ฐ˜ํ™˜."""
73
  try:
74
  return psycopg2.connect(**DB_CONFIG)
75
  except Exception as e:
 
85
  _data_ready = False
86
  _data_lock = threading.Lock()
87
 
 
88
  # ============================================================
89
+ # โ‘  ์ปค์Šคํ…€ ๊ฐ์ • ๋ชจ๋ธ ์•„ํ‚คํ…์ฒ˜ ์ •์˜
90
  # ============================================================
91
+
92
  class SEBlock(nn.Module):
93
  """Squeeze-and-Excitation Block"""
94
  def __init__(self, channels: int, reduction: int = 16):
 
186
 
187
 
188
  # ============================================================
189
+ # โ‘ก ์ปค์Šคํ…€ ๊ฐ์ • ๋ชจ๋ธ ๋กœ๋“œ
190
  # ============================================================
191
  _emotion_model = None
192
  _emotion_classes = ["Angry", "Happy", "Neutral", "Sad"]
 
230
 
231
 
232
  # ============================================================
233
+ # โ‘ข Mel-spectrogram ์ „์ฒ˜๋ฆฌ
234
  # ============================================================
235
  def _compute_melspec(y: np.ndarray, sr: int) -> torch.Tensor:
236
  try:
 
264
 
265
 
266
  # ============================================================
267
+ # โ‘ฃ TTA ์ถ”๋ก 
268
  # ============================================================
269
  def _tta_augment(spec: torch.Tensor) -> torch.Tensor:
270
  shift = np.random.randint(-MAX_FRAMES // 8, MAX_FRAMES // 8)
 
298
 
299
 
300
  # ============================================================
301
+ # โ‘ค CatBoost ์žฌ์ •๋ ฌ ๋ชจ๋ธ
302
  # ============================================================
303
  _cb_model = None
304
 
 
669
 
670
 
671
  def _get_isbn_survey_multiplier(weights: Dict, user_id: str, isbn: str) -> float:
672
+ if user_id not in weights["user_weights"]:
673
  return 1.0
674
  entry = weights["user_weights"][user_id]["isbn_scores"].get(isbn)
675
  if not entry:
 
857
 
858
 
859
  # ============================================================
860
+ # ์ถ”์ฒœ ๊ฒฐ๊ณผ โ†’ JSON ๋ Œ๋”๋ง
861
+ # ============================================================
862
+ def _render_books_json(
863
+ user_input: str,
864
+ emotion: str,
865
+ combined: Dict[str, float],
866
+ books: List[Dict],
867
+ ) -> str:
868
+ if not books:
869
+ return json.dumps(
870
+ {"error": "์ถ”์ฒœํ•  ์ฑ…์„ ์ฐพ์ง€ ๋ชปํ–ˆ์Šต๋‹ˆ๋‹ค."}, ensure_ascii=False, indent=2
871
+ )
872
+
873
+ output = {
874
+ "user_input": user_input,
875
+ "emotion": emotion,
876
+ "emotion_score": round(combined.get(emotion, 0.0), 3),
877
+ "recommendation_books": [
878
+ {
879
+ "isbn": b["isbn"],
880
+ "title": b["title"],
881
+ "author": b["author"],
882
+ "publisher": b["publisher"],
883
+ "content": b["content"],
884
+ "img_url": b["img_url"],
885
+ }
886
+ for b in books
887
+ ],
888
+ }
889
+ return json.dumps(output, ensure_ascii=False, indent=2)
890
+
891
+
892
+ # ============================================================
893
+ # ํ”ผ๋“œ๋ฐฑ API
894
  # ============================================================
895
  def api_feedback(feedback_data) -> str:
896
  """
 
898
  {
899
  "user_id": "3422423",
900
  "books": [
901
+ {"isbn": "9788901234567", "emotion": "๊ธฐ์จ", "accepted": 1, "rank": 1},
902
+ {"isbn": "9788901234568", "emotion": "๊ธฐ์จ", "accepted": 0, "rank": 2},
903
+ {"isbn": "9788901234569", "emotion": "๊ธฐ์จ", "accepted": 0, "rank": 3}
904
  ]
905
  }
906
  """
 
950
  return json.dumps({"error": str(e)}, ensure_ascii=False, indent=2)
951
 
952
 
953
+ # ============================================================
954
+ # ์„ค๋ฌธ API
955
+ # ============================================================
956
  def api_survey(survey_data) -> str:
957
  """
958
  ํด๋ผ์ด์–ธํŠธ ์ „์†ก ํ˜•์‹:
 
1010
  return json.dumps({"error": str(e)}, ensure_ascii=False, indent=2)
1011
 
1012
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1013
  # ============================================================
1014
+ # ๋ฉ”์ธ ์ฒ˜๋ฆฌ
1015
  # ============================================================
1016
  def process_voice(audio_input, user_id: str = None):
1017
  if not _data_ready:
 
1028
 
1029
  try:
1030
  if isinstance(audio_input, str):
1031
+ import soundfile as sf
1032
+ y, sr = sf.read(audio_input)
1033
+ y = y.astype(np.float32)
1034
+ if y.ndim > 1:
1035
+ y = y.mean(axis=1)
 
 
 
 
 
 
 
1036
  else:
1037
  sr, y = audio_input
1038
  y = y.astype(np.float32)
 
1056
  a_scores = audio_emotion_scores(y, sr)
1057
  top_label, combined = fused_emotion(t_scores, a_scores)
1058
  books = get_recommendations(user_input, top_label, user_id=user_id, top_n=3)
1059
+ books_json = _render_books_json(user_input, top_label, combined, books)
1060
 
1061
+ return books_json, books
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1062
 
1063
  except Exception as e:
1064
  logger.error(f"์ฒ˜๋ฆฌ ์˜ค๋ฅ˜: {e}")
1065
  return json.dumps({"error": str(e)}, ensure_ascii=False, indent=2), []
1066
 
1067
 
1068
+ def run_analysis(audio):
1069
+ books_json, books = process_voice(audio)
1070
+ return books_json, books
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1071
 
1072
 
1073
  # ============================================================
1074
+ # Gradio UI
1075
  # ============================================================
1076
+ with gr.Blocks(theme=gr.themes.Soft(), title="Boolook") as demo:
1077
+ gr.Markdown("""
1078
+ # Boolook โ€” ์Œ์„ฑ ๊ธฐ๋ฐ˜ ๊ฐ์ • ๋ถ„์„ ์ฑ… ์ถ”์ฒœ
1079
+ ๋‹น์‹ ์˜ ๊ฐ์ •์„ ๋ง๋กœ ํ‘œํ˜„ํ•˜๋ฉด, AI๊ฐ€ ๋”ฑ ๋งž๋Š” ์ฑ…์„ ์ถ”์ฒœํ•ด๋“œ๋ฆฝ๋‹ˆ๋‹ค.
1080
+ **์‚ฌ์šฉ๋ฒ•:** ๋งˆ์ดํฌ๋กœ ๊ฐ์ • ํ‘œํ˜„ โ†’ ๋ถ„์„ํ•˜๊ธฐ
1081
+ """)
1082
+
1083
+ state_books = gr.State([])
1084
+
1085
+ with gr.Row():
1086
+ with gr.Column(scale=1):
1087
+ gr.Markdown("### ์Œ์„ฑ ์ž…๋ ฅ")
1088
+ audio_in = gr.Audio(
1089
+ sources=["microphone", "upload"],
1090
+ type="filepath",
1091
+ label="๋งˆ์ดํฌ ๋˜๋Š” ํŒŒ์ผ ์—…๋กœ๋“œ",
1092
+ )
1093
+ analyze_btn = gr.Button("๋ถ„์„ํ•˜๊ธฐ", variant="primary", size="lg")
1094
+ gr.Markdown("์˜ˆ: '์˜ค๋Š˜ ๋„ˆ๋ฌด ์Šฌํผ์š”', 'ํ–‰๋ณตํ•œ ๊ธฐ๋ถ„์ด์—์š”'")
1095
+
1096
+ with gr.Column(scale=1):
1097
+ out_books_json = gr.Code(
1098
+ label="๋ถ„์„ ๊ฒฐ๊ณผ & ์ถ”์ฒœ ๋„์„œ",
1099
+ language="json",
1100
+ interactive=False,
1101
+ )
1102
 
1103
+ with gr.Accordion("ํ†ต๊ณ„", open=False):
1104
+ stats_md = gr.Markdown("์ƒˆ๋กœ๊ณ ์นจ์„ ๋ˆŒ๋Ÿฌ์ฃผ์„ธ์š”.")
1105
+ refresh_btn = gr.Button("ํ†ต๊ณ„ ์ƒˆ๋กœ๊ณ ์นจ")
1106
+ refresh_btn.click(fn=get_feedback_stats, outputs=stats_md)
1107
 
1108
+ # ํ”ผ๋“œ๋ฐฑ API ์—”๋“œํฌ์ธํŠธ (ํด๋ผ์ด์–ธํŠธ ์ „์šฉ, UI ๋ฏธ๋…ธ์ถœ)
1109
+ with gr.Row(visible=False):
1110
+ fb_api_in = gr.Textbox()
1111
+ fb_api_out = gr.Textbox()
1112
+ fb_api_btn = gr.Button()
1113
+ fb_api_btn.click(
1114
+ fn=api_feedback,
1115
+ inputs=fb_api_in,
1116
+ outputs=fb_api_out,
1117
+ api_name="feedback",
1118
+ )
1119
 
1120
+ # ์„ค๋ฌธ API ์—”๋“œํฌ์ธํŠธ (ํด๋ผ์ด์–ธํŠธ ์ „์šฉ, UI ๋ฏธ๋…ธ์ถœ)
1121
+ with gr.Row(visible=False):
1122
+ survey_api_in = gr.Textbox()
1123
+ survey_api_out = gr.Textbox()
1124
+ survey_api_btn = gr.Button()
1125
+ survey_api_btn.click(
1126
+ fn=api_survey,
1127
+ inputs=survey_api_in,
1128
+ outputs=survey_api_out,
1129
+ api_name="survey",
1130
+ )
1131
 
1132
+ analyze_btn.click(
1133
+ fn=run_analysis,
1134
+ inputs=audio_in,
1135
+ outputs=[out_books_json, state_books],
1136
+ )
1137
 
1138
  if __name__ == "__main__":
1139
+ demo.launch()