Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,7 +1,6 @@
|
|
| 1 |
"""
|
| 2 |
-
Boolook - ์์ฑ ๊ธฐ๋ฐ ๊ฐ์ ๋ถ์ ์ฑ
์ถ์ฒ
|
| 3 |
-
|
| 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
|
| 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 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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": "
|
| 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 |
-
|
| 1040 |
-
|
| 1041 |
-
|
| 1042 |
-
|
| 1043 |
-
y
|
| 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 |
-
|
| 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 |
-
|
| 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.
|
| 1599 |
-
|
| 1600 |
-
|
| 1601 |
-
|
| 1602 |
-
|
| 1603 |
-
|
| 1604 |
-
|
| 1605 |
-
|
| 1606 |
-
|
| 1607 |
-
|
| 1608 |
-
|
| 1609 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1610 |
|
| 1611 |
-
|
| 1612 |
-
|
|
|
|
|
|
|
| 1613 |
|
| 1614 |
-
|
| 1615 |
-
|
| 1616 |
-
|
| 1617 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1618 |
|
| 1619 |
-
#
|
| 1620 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1621 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1622 |
|
| 1623 |
if __name__ == "__main__":
|
| 1624 |
-
demo.launch(
|
|
|
|
| 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()
|