Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,495 +1,507 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import pandas as pd
|
| 3 |
import numpy as np
|
| 4 |
import torch
|
| 5 |
-
|
| 6 |
-
from sentence_transformers import SentenceTransformer, util
|
| 7 |
import json
|
|
|
|
|
|
|
|
|
|
| 8 |
from datetime import datetime
|
| 9 |
-
import
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
-
# ===============================
|
| 12 |
# μ€μ
|
| 13 |
-
# ===============================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
device = 0 if torch.cuda.is_available() else -1
|
| 15 |
-
FEEDBACK_FILE = "feedback_data.jsonl"
|
| 16 |
-
BOOK_DB_FILE = "book_db_final.csv"
|
| 17 |
|
| 18 |
-
# ===============================
|
| 19 |
-
# λͺ¨λΈ λ‘
|
| 20 |
-
# ===============================
|
| 21 |
print("π λͺ¨λΈ λ‘λ© μ€...")
|
| 22 |
|
| 23 |
try:
|
| 24 |
-
stt_model =
|
| 25 |
"automatic-speech-recognition",
|
| 26 |
model="openai/whisper-large-v3-turbo",
|
| 27 |
-
device=device
|
| 28 |
)
|
| 29 |
print("β
STT λͺ¨λΈ λ‘λ μλ£")
|
| 30 |
except Exception as e:
|
| 31 |
-
print(f"β οΈ STT
|
| 32 |
stt_model = None
|
| 33 |
|
| 34 |
try:
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
device=device,
|
| 39 |
-
top_k=None
|
| 40 |
-
)
|
| 41 |
-
print("β
κ°μ λΆμ λͺ¨λΈ λ‘λ μλ£")
|
| 42 |
except Exception as e:
|
| 43 |
-
print(f"β οΈ
|
| 44 |
-
|
| 45 |
|
| 46 |
try:
|
| 47 |
-
|
| 48 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
except Exception as e:
|
| 50 |
-
print(f"β οΈ
|
| 51 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
|
| 53 |
-
|
| 54 |
|
| 55 |
-
# ===============================
|
| 56 |
-
#
|
| 57 |
-
# ===============================
|
| 58 |
def load_book_data():
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
df
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
return df, book_embeddings
|
| 84 |
|
| 85 |
df, book_embeddings = load_book_data()
|
| 86 |
|
| 87 |
-
# ===============================
|
| 88 |
-
#
|
| 89 |
-
# ===============================
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
"sadness": "μ¬ν",
|
| 93 |
-
"anger": "λΆλ
Έ",
|
| 94 |
-
"fear": "곡ν¬",
|
| 95 |
-
"surprise": "λλ",
|
| 96 |
-
"disgust": "νμ€",
|
| 97 |
-
"love": "μ λ’°",
|
| 98 |
-
"optimism": "κΈ°λ"
|
| 99 |
-
}
|
| 100 |
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
# ===============================
|
| 106 |
-
def save_feedback(user_text, emotion, books, feedback_type, book_title=None):
|
| 107 |
-
"""νΌλλ°± λ°μ΄ν°λ₯Ό JSONL νμμΌλ‘ μ μ₯"""
|
| 108 |
-
feedback_entry = {
|
| 109 |
-
"timestamp": datetime.now().isoformat(),
|
| 110 |
-
"user_text": user_text,
|
| 111 |
-
"detected_emotion": emotion,
|
| 112 |
-
"recommended_books": [b["title"] for b in books],
|
| 113 |
-
"feedback_type": feedback_type,
|
| 114 |
-
"selected_book": book_title
|
| 115 |
-
}
|
| 116 |
-
|
| 117 |
try:
|
| 118 |
-
|
| 119 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
except Exception as e:
|
| 121 |
-
print(f"β οΈ
|
|
|
|
| 122 |
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
feedback_data = []
|
| 129 |
try:
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
"""νΌλλ°± λ°μ΄ν° κΈ°λ° μΆμ² κ°μ€μΉ μ‘°μ """
|
| 143 |
-
feedback_data = load_feedback_data()
|
| 144 |
-
|
| 145 |
-
if not feedback_data:
|
| 146 |
-
return {}
|
| 147 |
-
|
| 148 |
-
weights = {}
|
| 149 |
-
|
| 150 |
-
for entry in feedback_data:
|
| 151 |
-
emotion = entry.get("detected_emotion")
|
| 152 |
-
selected_book = entry.get("selected_book")
|
| 153 |
-
feedback_type = entry.get("feedback_type")
|
| 154 |
-
|
| 155 |
-
if emotion and selected_book:
|
| 156 |
-
key = (emotion, selected_book)
|
| 157 |
-
|
| 158 |
-
if key not in weights:
|
| 159 |
-
weights[key] = 0
|
| 160 |
-
|
| 161 |
-
if feedback_type in ["like", "select"]:
|
| 162 |
-
weights[key] += 1.0
|
| 163 |
-
elif feedback_type == "dislike":
|
| 164 |
-
weights[key] -= 0.5
|
| 165 |
-
|
| 166 |
-
return weights
|
| 167 |
-
|
| 168 |
-
# ===============================
|
| 169 |
# κ°μ λΆμ
|
| 170 |
-
# ===============================
|
| 171 |
-
def
|
| 172 |
-
"""
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 179 |
try:
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
for
|
| 185 |
-
|
| 186 |
-
mapped = EMOTION_MAP.get(label)
|
| 187 |
-
|
| 188 |
if mapped:
|
| 189 |
-
scores[mapped] +=
|
| 190 |
-
|
| 191 |
-
# νκ΅μ΄ ν€μλ κΈ°λ° λ³΄μ
|
| 192 |
-
text_lower = text.lower()
|
| 193 |
-
|
| 194 |
-
keyword_boosts = {
|
| 195 |
-
"μ¬ν": ["μ¬ν", "μ°μΈ", "λλ¬Ό", "νλ€", "μΈλ‘"],
|
| 196 |
-
"λΆλ
Έ": ["νλ", "μ§μ¦", "μ΄λ°", "λΉ‘μΉ", "μ΅μΈ"],
|
| 197 |
-
"κΈ°μ¨": ["ν볡", "μ’λ€", "κΈ°μ", "μ¦κ²", "μ λ"],
|
| 198 |
-
"곡ν¬": ["무μ", "λλ ΅", "κ±±μ ", "λΆμ"],
|
| 199 |
-
"λλ": ["λλ", "κΉμ§", "좩격"],
|
| 200 |
-
"μ λ’°": ["λ―Ώμ", "μ¬λ", "λ°λ»", "κ³ λ§"],
|
| 201 |
-
"κΈ°λ": ["κΈ°λ", "ν¬λ§", "μ€λ "]
|
| 202 |
-
}
|
| 203 |
-
|
| 204 |
-
for emotion, keywords in keyword_boosts.items():
|
| 205 |
-
for keyword in keywords:
|
| 206 |
-
if keyword in text_lower:
|
| 207 |
-
scores[emotion] += 0.3
|
| 208 |
-
break
|
| 209 |
-
|
| 210 |
-
# μ κ·ν
|
| 211 |
-
total = sum(scores.values())
|
| 212 |
-
if total > 0:
|
| 213 |
-
scores = {k: v / total for k, v in scores.items()}
|
| 214 |
-
|
| 215 |
-
return scores
|
| 216 |
except Exception as e:
|
| 217 |
-
print(f"β οΈ κ°μ λΆμ μ€λ₯: {e}")
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 227 |
return []
|
| 228 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 229 |
try:
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
if
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
pool["sim"] = sims
|
| 243 |
-
|
| 244 |
-
feedback_weights = apply_feedback_learning()
|
| 245 |
-
|
| 246 |
-
def calculate_final_score(row):
|
| 247 |
-
base_score = row["sim"]
|
| 248 |
-
key = (emotion, row["title"])
|
| 249 |
-
feedback_boost = feedback_weights.get(key, 0) * 0.1
|
| 250 |
-
return base_score + feedback_boost
|
| 251 |
-
|
| 252 |
-
pool["final_score"] = pool.apply(calculate_final_score, axis=1)
|
| 253 |
-
pool = pool.sort_values("final_score", ascending=False).head(top_n)
|
| 254 |
-
|
| 255 |
-
books = []
|
| 256 |
-
for _, row in pool.iterrows():
|
| 257 |
-
books.append({
|
| 258 |
-
"title": row["title"],
|
| 259 |
-
"img_url": row.get("thumbnail", ""),
|
| 260 |
-
"content": str(row.get("contents", ""))[:150] + "...",
|
| 261 |
-
"similarity": round(float(row["sim"]), 3),
|
| 262 |
-
"final_score": round(float(row["final_score"]), 3)
|
| 263 |
-
})
|
| 264 |
-
|
| 265 |
-
return books
|
| 266 |
except Exception as e:
|
| 267 |
-
|
| 268 |
-
return []
|
| 269 |
|
| 270 |
-
# ===============================
|
| 271 |
# λ©μΈ μ²λ¦¬ ν¨μ
|
| 272 |
-
# ===============================
|
| 273 |
def process_voice(audio_input):
|
| 274 |
-
"""μμ± μ
λ ₯
|
| 275 |
-
|
| 276 |
-
empty_result = {
|
| 277 |
-
"status": "error",
|
| 278 |
-
"user_input": "",
|
| 279 |
-
"emotion_label": "",
|
| 280 |
-
"emotion_score": 0.0,
|
| 281 |
-
"books": [],
|
| 282 |
-
"message": ""
|
| 283 |
-
}
|
| 284 |
-
|
| 285 |
if audio_input is None:
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
if stt_model is None:
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
try:
|
| 294 |
sr, y = audio_input
|
| 295 |
-
y
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
stt_result = stt_model({"sampling_rate": sr, "raw": y})
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
if not
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 327 |
except Exception as e:
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
def record_book_selection(user_text, emotion, books, selected_title):
|
| 333 |
-
"""μ¬μ©μκ° μ±
μ μ ννμ λ νΌλλ°± μ μ₯"""
|
| 334 |
-
if selected_title and user_text:
|
| 335 |
-
save_feedback(user_text, emotion, books, "select", selected_title)
|
| 336 |
-
return f"β
'{selected_title}' μ νμ΄ κΈ°λ‘λμμ΅λλ€. νμ΅μ λ°μλ©λλ€!"
|
| 337 |
-
return "β οΈ μ ν κΈ°λ‘ μ€ν¨"
|
| 338 |
-
|
| 339 |
-
# ===============================
|
| 340 |
# Gradio UI
|
| 341 |
-
# ===============================
|
| 342 |
custom_css = """
|
| 343 |
-
.feedback-
|
| 344 |
-
|
| 345 |
-
padding: 20px;
|
| 346 |
-
border-radius: 10px;
|
| 347 |
-
}
|
| 348 |
"""
|
| 349 |
|
| 350 |
-
with gr.Blocks(theme=gr.themes.Soft(), css=custom_css) as demo:
|
| 351 |
-
|
| 352 |
-
gr.Markdown(
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
)
|
| 364 |
-
|
| 365 |
-
state_text = gr.State("")
|
| 366 |
state_emotion = gr.State("")
|
| 367 |
-
|
| 368 |
-
|
| 369 |
with gr.Row():
|
| 370 |
with gr.Column(scale=1):
|
| 371 |
gr.Markdown("### π€ μμ± μ
λ ₯")
|
| 372 |
audio_in = gr.Audio(
|
| 373 |
label="λ§μ΄ν¬λ‘ κ°μ νννκΈ°",
|
| 374 |
sources=["microphone"],
|
| 375 |
-
type="numpy"
|
| 376 |
-
)
|
| 377 |
-
|
| 378 |
-
analyze_btn = gr.Button(
|
| 379 |
-
"π λΆμνκΈ°",
|
| 380 |
-
variant="primary",
|
| 381 |
-
size="lg"
|
| 382 |
-
)
|
| 383 |
-
|
| 384 |
-
gr.Markdown(
|
| 385 |
-
"""
|
| 386 |
-
**π‘ ν:**
|
| 387 |
-
- "μ€λ λ무 μ¬νΌμ"
|
| 388 |
-
- "ν볡ν κΈ°λΆμ΄μμ"
|
| 389 |
-
- "νκ° λλ μΌμ΄ μμμ΄μ"
|
| 390 |
-
"""
|
| 391 |
)
|
| 392 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 393 |
with gr.Column(scale=1):
|
| 394 |
gr.Markdown("### π λΆμ κ²°κ³Ό")
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
with gr.Row():
|
| 405 |
-
book_display = gr.Markdown("λΆμ ν μΆμ² λμκ° νμλ©λλ€.")
|
| 406 |
-
|
| 407 |
-
with gr.Accordion("π¬ μ±
μ ν νΌλλ°± (νμ΅μ λ°μλ©λλ€)", open=True, elem_classes="feedback-section"):
|
| 408 |
-
gr.Markdown("λ§μμ λλ μ±
μ΄ μλ€λ©΄ μ λͺ©μ μ
λ ₯νκ³ κΈ°λ‘ν΄μ£ΌμΈμ!")
|
| 409 |
-
|
| 410 |
with gr.Row():
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
feedback_btn = gr.Button("β
μ ν κΈ°λ‘", scale=1)
|
| 417 |
-
|
| 418 |
-
feedback_result = gr.Textbox(label="νΌλλ°± κ²°κ³Ό", interactive=False)
|
| 419 |
-
|
| 420 |
with gr.Accordion("π νΌλλ°± ν΅κ³", open=False):
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
def show_stats():
|
| 424 |
-
feedback_data = load_feedback_data()
|
| 425 |
-
total = len(feedback_data)
|
| 426 |
-
|
| 427 |
-
if total == 0:
|
| 428 |
-
return "π μμ§ νΌλλ°± λ°μ΄ν°κ° μμ΅λλ€."
|
| 429 |
-
|
| 430 |
-
emotion_counts = {}
|
| 431 |
-
for entry in feedback_data:
|
| 432 |
-
emo = entry.get("detected_emotion", "Unknown")
|
| 433 |
-
emotion_counts[emo] = emotion_counts.get(emo, 0) + 1
|
| 434 |
-
|
| 435 |
-
stats_text = f"**μ΄ νΌλλ°± μ:** {total}\n\n"
|
| 436 |
-
stats_text += "**κ°μ λ³ λΆμ μμ²:**\n\n"
|
| 437 |
-
for emo, count in sorted(emotion_counts.items(), key=lambda x: x[1], reverse=True):
|
| 438 |
-
stats_text += f"- {emo}: {count}ν\n"
|
| 439 |
-
|
| 440 |
-
return stats_text
|
| 441 |
-
|
| 442 |
refresh_stats_btn = gr.Button("π ν΅κ³ μλ‘κ³ μΉ¨")
|
| 443 |
-
refresh_stats_btn.click(fn=
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
for i, book in enumerate(result["books"], 1):
|
| 451 |
-
books_md += f"""
|
| 452 |
-
### {i}. {book['title']}
|
| 453 |
-
- **μ μ¬λ μ μ:** {book['similarity']}
|
| 454 |
-
- **μ΅μ’
μ μ:** {book['final_score']} (νΌλλ°± λ°μ)
|
| 455 |
-
- **μ€κ±°λ¦¬:** {book['content']}
|
| 456 |
-
|
| 457 |
-
---
|
| 458 |
-
"""
|
| 459 |
-
else:
|
| 460 |
-
books_md += "μΆμ²ν μ±
μ μ°Ύμ§ λͺ»νμ΅λλ€."
|
| 461 |
-
|
| 462 |
-
return (
|
| 463 |
-
result,
|
| 464 |
-
books_md,
|
| 465 |
-
result["user_input"],
|
| 466 |
-
result["emotion_label"],
|
| 467 |
-
result["books"]
|
| 468 |
-
)
|
| 469 |
-
else:
|
| 470 |
-
return (
|
| 471 |
-
result,
|
| 472 |
-
f"β οΈ {result.get('message', 'μ€λ₯ λ°μ')}",
|
| 473 |
-
"",
|
| 474 |
-
"",
|
| 475 |
-
[]
|
| 476 |
-
)
|
| 477 |
-
|
| 478 |
analyze_btn.click(
|
| 479 |
-
fn=
|
| 480 |
inputs=audio_in,
|
| 481 |
-
outputs=
|
| 482 |
-
)
|
| 483 |
-
|
| 484 |
-
|
| 485 |
-
|
|
|
|
|
|
|
| 486 |
)
|
| 487 |
-
|
| 488 |
-
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
outputs=feedback_result
|
| 492 |
)
|
| 493 |
|
| 494 |
if __name__ == "__main__":
|
| 495 |
-
demo.launch()
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Boolook - μμ± κΈ°λ° κ°μ λΆμ μ±
μΆμ² (HuggingFace Spaces)
|
| 3 |
+
record_cat.py μκ³ λ¦¬μ¦ κΈ°λ° μ
κ·Έλ μ΄λ λ²μ
|
| 4 |
+
DB 컬λΌ: isbn, title, author, publisher, content, img_url
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
import gradio as gr
|
| 8 |
import pandas as pd
|
| 9 |
import numpy as np
|
| 10 |
import torch
|
| 11 |
+
import pickle
|
|
|
|
| 12 |
import json
|
| 13 |
+
import csv
|
| 14 |
+
import warnings
|
| 15 |
+
from pathlib import Path
|
| 16 |
from datetime import datetime
|
| 17 |
+
from collections import defaultdict
|
| 18 |
+
from transformers import pipeline as hf_pipeline
|
| 19 |
+
from sentence_transformers import SentenceTransformer, util as sbert_util
|
| 20 |
+
|
| 21 |
+
warnings.filterwarnings("ignore")
|
| 22 |
|
| 23 |
+
# ============================================================
|
| 24 |
# μ€μ
|
| 25 |
+
# ============================================================
|
| 26 |
+
BOOK_DB_PATH = Path("book_db_final.csv")
|
| 27 |
+
FEEDBACK_PATH = Path("user_feedback.csv")
|
| 28 |
+
SBERT_CACHE_PATH = Path("book_embeddings.pkl")
|
| 29 |
+
SAMPLE_RATE = 16000
|
| 30 |
+
MIN_FEEDBACK_FOR_TRAIN = 20
|
| 31 |
+
|
| 32 |
device = 0 if torch.cuda.is_available() else -1
|
|
|
|
|
|
|
| 33 |
|
| 34 |
+
# ============================================================
|
| 35 |
+
# λͺ¨λΈ λ‘λ©
|
| 36 |
+
# ============================================================
|
| 37 |
print("π λͺ¨λΈ λ‘λ© μ€...")
|
| 38 |
|
| 39 |
try:
|
| 40 |
+
stt_model = hf_pipeline(
|
| 41 |
"automatic-speech-recognition",
|
| 42 |
model="openai/whisper-large-v3-turbo",
|
| 43 |
+
device=device,
|
| 44 |
)
|
| 45 |
print("β
STT λͺ¨λΈ λ‘λ μλ£")
|
| 46 |
except Exception as e:
|
| 47 |
+
print(f"β οΈ STT λ‘λ μ€ν¨: {e}")
|
| 48 |
stt_model = None
|
| 49 |
|
| 50 |
try:
|
| 51 |
+
sbert_model = SentenceTransformer("jhgan/ko-sroberta-multitask")
|
| 52 |
+
sbert_model.max_seq_length = 384
|
| 53 |
+
print("β
SBERT λͺ¨λΈ λ‘λ μλ£")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
except Exception as e:
|
| 55 |
+
print(f"β οΈ SBERT λ‘λ μ€ν¨: {e}")
|
| 56 |
+
sbert_model = None
|
| 57 |
|
| 58 |
try:
|
| 59 |
+
audio_emotion_pipeline = hf_pipeline(
|
| 60 |
+
"audio-classification",
|
| 61 |
+
model="superb/wav2vec2-base-superb-er",
|
| 62 |
+
device=device,
|
| 63 |
+
)
|
| 64 |
+
print("β
μμ± κ°μ λͺ¨λΈ λ‘λ μλ£")
|
| 65 |
except Exception as e:
|
| 66 |
+
print(f"β οΈ μμ± κ°μ λͺ¨λΈ λ‘λ μ€ν¨: {e}")
|
| 67 |
+
audio_emotion_pipeline = None
|
| 68 |
+
|
| 69 |
+
print("β
λͺ¨λΈ λ‘λ© μλ£!")
|
| 70 |
+
|
| 71 |
+
# ============================================================
|
| 72 |
+
# κ°μ λ μ΄λΈ & μ€λͺ
|
| 73 |
+
# ============================================================
|
| 74 |
+
_EMOTION_DESCS = {
|
| 75 |
+
"κΈ°μ¨": "ν볡νκ³ μ¦κ²κ³ μ μΎν κΈ°λΆ",
|
| 76 |
+
"μ λ’°": "λ°λ»νκ³ μμ μ μ΄λ©° κ°μ‘±κ³Ό μ°μ κ°μ μ λκ°",
|
| 77 |
+
"곡ν¬": "무μκ³ κΈ΄μ₯λλ©° μ€λ¦΄ μλ 곡ν¬μ λΆμ",
|
| 78 |
+
"λλ": "λ°μ κ³Ό 좩격, μμμΉ λͺ»ν κ²½μ΄λ‘μ",
|
| 79 |
+
"μ¬ν": "μ¬νκ³ μΈλ‘κ³ μ΄λ³κ³Ό μμ€μ κ°μ ",
|
| 80 |
+
"νμ€": "λΆμ‘°λ¦¬μ λΆνλ±, μμ μ λν λΉνκ³Ό νμ",
|
| 81 |
+
"λΆλ
Έ": "λΆλ
Έμ μ ν, ν¬μκ³Ό κ°λ±",
|
| 82 |
+
"κΈ°λ": "μ±μ₯κ³Ό λμ , λͺ¨νκ³Ό ν¬λ§",
|
| 83 |
+
}
|
| 84 |
+
_EMOTION_LABELS = list(_EMOTION_DESCS.keys())
|
| 85 |
+
_LABEL_EMBS = sbert_model.encode(list(_EMOTION_DESCS.values()), convert_to_tensor=True) if sbert_model else None
|
| 86 |
+
|
| 87 |
+
_AUDIO_LABEL_MAP = {"hap": "κΈ°μ¨", "neu": "μ λ’°", "sad": "μ¬ν", "ang": "λΆλ
Έ"}
|
| 88 |
+
|
| 89 |
+
# νκ΅μ΄ ν€μλ κ°μ 보μ
|
| 90 |
+
_KEYWORD_BOOSTS = {
|
| 91 |
+
"μ¬ν": ["μ¬ν", "μ°μΈ", "λλ¬Ό", "νλ€", "μΈλ‘"],
|
| 92 |
+
"λΆλ
Έ": ["νλ", "μ§μ¦", "μ΄λ°", "λΉ‘μΉ", "μ΅μΈ"],
|
| 93 |
+
"κΈ°μ¨": ["ν볡", "μ’λ€", "κΈ°μ", "μ¦κ²", "μ λ"],
|
| 94 |
+
"곡ν¬": ["무μ", "λλ ΅", "κ±±μ ", "λΆμ"],
|
| 95 |
+
"λλ": ["λλ", "κΉμ§", "좩격"],
|
| 96 |
+
"μ λ’°": ["λ―Ώμ", "μ¬λ", "λ°λ»", "κ³ λ§"],
|
| 97 |
+
"κΈ°λ": ["κΈ°λ", "ν¬λ§", "μ€λ "],
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
# ============================================================
|
| 101 |
+
# μΈμ
νΌλλ°± (μ μ)
|
| 102 |
+
# ============================================================
|
| 103 |
+
class SessionFeedback:
|
| 104 |
+
def __init__(self):
|
| 105 |
+
self.accepted_counts = defaultdict(int)
|
| 106 |
+
self.rejected_counts = defaultdict(int)
|
| 107 |
+
|
| 108 |
+
def score_multiplier(self, emotion: str) -> float:
|
| 109 |
+
acc = self.accepted_counts[emotion]
|
| 110 |
+
rej = self.rejected_counts[emotion]
|
| 111 |
+
return max(0.5, 1.0 + (0.1 * acc) - (0.1 * rej))
|
| 112 |
|
| 113 |
+
_session = SessionFeedback()
|
| 114 |
|
| 115 |
+
# ============================================================
|
| 116 |
+
# λμ λ°μ΄ν° & μλ² λ© λ‘λ
|
| 117 |
+
# ============================================================
|
| 118 |
def load_book_data():
|
| 119 |
+
if not BOOK_DB_PATH.exists():
|
| 120 |
+
raise FileNotFoundError(f"β {BOOK_DB_PATH} νμΌμ΄ νμν©λλ€.")
|
| 121 |
+
|
| 122 |
+
df = pd.read_csv(BOOK_DB_PATH, encoding="utf-8-sig").fillna("")
|
| 123 |
+
print(f"π {len(df)}κΆ λ‘λ μλ£")
|
| 124 |
+
|
| 125 |
+
# μλ² λ© μΊμ
|
| 126 |
+
if SBERT_CACHE_PATH.exists():
|
| 127 |
+
print("β
μλ² λ© μΊμ λ‘λ")
|
| 128 |
+
with open(SBERT_CACHE_PATH, "rb") as f:
|
| 129 |
+
emb_cache = pickle.load(f)
|
| 130 |
+
else:
|
| 131 |
+
emb_cache = {}
|
| 132 |
+
|
| 133 |
+
# μΊμμ μλ μ±
λ§ μλ‘ κ³μ°
|
| 134 |
+
missing = [i for i, row in df.iterrows() if str(row["isbn"]) not in emb_cache]
|
| 135 |
+
if missing and sbert_model:
|
| 136 |
+
print(f"βοΈ μ κ· μλ² λ© κ³μ°: {len(missing)}κΆ")
|
| 137 |
+
texts = [
|
| 138 |
+
(str(df.at[i, "title"]) + " " + str(df.at[i, "content"]))[:500]
|
| 139 |
+
for i in missing
|
| 140 |
+
]
|
| 141 |
+
vecs = sbert_model.encode(texts, convert_to_tensor=False, show_progress_bar=True)
|
| 142 |
+
for i, vec in zip(missing, vecs):
|
| 143 |
+
emb_cache[str(df.at[i, "isbn"])] = vec
|
| 144 |
+
with open(SBERT_CACHE_PATH, "wb") as f:
|
| 145 |
+
pickle.dump(emb_cache, f)
|
| 146 |
+
print("β
μλ² λ© μ μ₯ μλ£")
|
| 147 |
+
|
| 148 |
+
# DataFrame μμμ λ§κ² μλ² λ© νλ ¬ ꡬμ±
|
| 149 |
+
emb_matrix = np.stack([
|
| 150 |
+
emb_cache.get(str(row["isbn"]), np.zeros(384))
|
| 151 |
+
for _, row in df.iterrows()
|
| 152 |
+
])
|
| 153 |
+
book_embeddings = torch.tensor(emb_matrix, dtype=torch.float32)
|
| 154 |
+
|
| 155 |
return df, book_embeddings
|
| 156 |
|
| 157 |
df, book_embeddings = load_book_data()
|
| 158 |
|
| 159 |
+
# ============================================================
|
| 160 |
+
# CatBoost κ°μΈν λͺ¨λΈ (μ νμ )
|
| 161 |
+
# ============================================================
|
| 162 |
+
_ml_model = None
|
| 163 |
+
_ml_feature_names = []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 164 |
|
| 165 |
+
def _try_load_catboost():
|
| 166 |
+
global _ml_model, _ml_feature_names
|
| 167 |
+
model_path = Path("catboost_recommender.cbm")
|
| 168 |
+
encoder_path = Path("feature_encoder.pkl")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
try:
|
| 170 |
+
from catboost import CatBoostClassifier
|
| 171 |
+
if model_path.exists():
|
| 172 |
+
_ml_model = CatBoostClassifier()
|
| 173 |
+
_ml_model.load_model(str(model_path))
|
| 174 |
+
if encoder_path.exists():
|
| 175 |
+
with open(encoder_path, "rb") as f:
|
| 176 |
+
enc = pickle.load(f)
|
| 177 |
+
print("β
CatBoost λͺ¨λΈ λ‘λ μλ£")
|
| 178 |
+
return True
|
| 179 |
except Exception as e:
|
| 180 |
+
print(f"β οΈ CatBoost λ‘λ μ€ν¨: {e}")
|
| 181 |
+
return False
|
| 182 |
|
| 183 |
+
_try_load_catboost()
|
| 184 |
+
|
| 185 |
+
def _ml_predict(isbn: str, emotion: str, content_len: int) -> float:
|
| 186 |
+
if _ml_model is None:
|
| 187 |
+
return 0.5
|
|
|
|
| 188 |
try:
|
| 189 |
+
X = pd.DataFrame([{
|
| 190 |
+
"emotion": emotion,
|
| 191 |
+
"rank": 1,
|
| 192 |
+
"input_mode": "1",
|
| 193 |
+
"content_length": min(content_len, 500),
|
| 194 |
+
"has_content": 1 if content_len > 50 else 0,
|
| 195 |
+
}])
|
| 196 |
+
return float(_ml_model.predict_proba(X)[0][1])
|
| 197 |
+
except Exception:
|
| 198 |
+
return 0.5
|
| 199 |
+
|
| 200 |
+
# ============================================================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 201 |
# κ°μ λΆμ
|
| 202 |
+
# ============================================================
|
| 203 |
+
def text_emotion_scores(text: str) -> dict:
|
| 204 |
+
"""SBERT μ λ‘μ· + ν€μλ 보μ νΌν©"""
|
| 205 |
+
scores = {emo: 0.0 for emo in _EMOTION_LABELS}
|
| 206 |
+
|
| 207 |
+
if sbert_model and _LABEL_EMBS is not None:
|
| 208 |
+
user_emb = sbert_model.encode(text, convert_to_tensor=True)
|
| 209 |
+
cos_scores = sbert_util.cos_sim(user_emb, _LABEL_EMBS)[0]
|
| 210 |
+
for i, label in enumerate(_EMOTION_LABELS):
|
| 211 |
+
scores[label] = cos_scores[i].item()
|
| 212 |
+
|
| 213 |
+
# ν€μλ 보μ
|
| 214 |
+
text_lower = text.lower()
|
| 215 |
+
for emotion, keywords in _KEYWORD_BOOSTS.items():
|
| 216 |
+
for kw in keywords:
|
| 217 |
+
if kw in text_lower:
|
| 218 |
+
scores[emotion] += 0.15
|
| 219 |
+
break
|
| 220 |
+
|
| 221 |
+
# μ κ·ν
|
| 222 |
+
total = sum(scores.values())
|
| 223 |
+
if total > 0:
|
| 224 |
+
scores = {k: v / total for k, v in scores.items()}
|
| 225 |
+
|
| 226 |
+
return scores
|
| 227 |
+
|
| 228 |
+
def audio_emotion_scores(audio_array: np.ndarray, sr: int) -> dict:
|
| 229 |
+
"""μμ± μ νΈ κ°μ λΆλ₯"""
|
| 230 |
+
scores = {emo: 0.0 for emo in _EMOTION_LABELS}
|
| 231 |
+
if audio_emotion_pipeline is None:
|
| 232 |
+
return scores
|
| 233 |
try:
|
| 234 |
+
import scipy.io.wavfile as wav_io
|
| 235 |
+
tmp = "/tmp/_gradio_voice.wav"
|
| 236 |
+
wav_io.write(tmp, sr, (audio_array * 32767).astype(np.int16))
|
| 237 |
+
results = audio_emotion_pipeline(tmp)
|
| 238 |
+
for item in results:
|
| 239 |
+
mapped = _AUDIO_LABEL_MAP.get(item["label"])
|
|
|
|
|
|
|
| 240 |
if mapped:
|
| 241 |
+
scores[mapped] += item["score"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 242 |
except Exception as e:
|
| 243 |
+
print(f"β οΈ μμ± κ°μ λΆμ μ€λ₯: {e}")
|
| 244 |
+
return scores
|
| 245 |
+
|
| 246 |
+
def fused_emotion(t_scores: dict, a_scores: dict) -> tuple:
|
| 247 |
+
a_max = max(a_scores.values()) or 1.0
|
| 248 |
+
a_norm = {e: v / a_max for e, v in a_scores.items()}
|
| 249 |
+
combined = {
|
| 250 |
+
emo: (t_scores[emo] * 0.6) + (a_norm[emo] * 0.4)
|
| 251 |
+
for emo in _EMOTION_LABELS
|
| 252 |
+
}
|
| 253 |
+
return max(combined, key=combined.get), combined
|
| 254 |
+
|
| 255 |
+
# ============================================================
|
| 256 |
+
# μΆμ²
|
| 257 |
+
# ============================================================
|
| 258 |
+
def get_recommendations(user_text: str, emotion: str, top_n: int = 3) -> list:
|
| 259 |
+
if sbert_model is None or df.empty:
|
| 260 |
return []
|
| 261 |
+
|
| 262 |
+
session_w = _session.score_multiplier(emotion)
|
| 263 |
+
user_vec = sbert_model.encode(user_text, convert_to_tensor=True)
|
| 264 |
+
cos_sims = sbert_util.cos_sim(user_vec, book_embeddings)[0].cpu().numpy()
|
| 265 |
+
|
| 266 |
+
# νΌλλ°± κ°μ€μΉ
|
| 267 |
+
fb_weights = _load_feedback_weights()
|
| 268 |
+
|
| 269 |
+
results = []
|
| 270 |
+
for idx, (_, row) in enumerate(df.iterrows()):
|
| 271 |
+
content_len = len(str(row.get("content", "")))
|
| 272 |
+
ml_score = _ml_predict(str(row["isbn"]), emotion, content_len)
|
| 273 |
+
fb_boost = fb_weights.get((emotion, str(row["title"])), 0) * 0.1
|
| 274 |
+
cosine = float(cos_sims[idx])
|
| 275 |
+
final = cosine * 0.6 * session_w + ml_score * 0.4 + fb_boost
|
| 276 |
+
|
| 277 |
+
results.append({
|
| 278 |
+
"isbn": str(row.get("isbn", "")),
|
| 279 |
+
"title": str(row.get("title", "")),
|
| 280 |
+
"author": str(row.get("author", "-")),
|
| 281 |
+
"publisher": str(row.get("publisher", "-")),
|
| 282 |
+
"content": str(row.get("content", ""))[:150],
|
| 283 |
+
"img_url": str(row.get("img_url", "")),
|
| 284 |
+
"cosine": round(cosine, 3),
|
| 285 |
+
"ml_score": round(ml_score, 3),
|
| 286 |
+
"final": round(final, 3),
|
| 287 |
+
})
|
| 288 |
+
|
| 289 |
+
results.sort(key=lambda x: x["final"], reverse=True)
|
| 290 |
+
return results[:top_n]
|
| 291 |
+
|
| 292 |
+
# ============================================================
|
| 293 |
+
# νΌλλ°± μ μ₯ & λ‘λ
|
| 294 |
+
# ============================================================
|
| 295 |
+
def _load_feedback_weights() -> dict:
|
| 296 |
+
if not FEEDBACK_PATH.exists():
|
| 297 |
+
return {}
|
| 298 |
+
try:
|
| 299 |
+
fb_df = pd.read_csv(FEEDBACK_PATH, encoding="utf-8-sig", on_bad_lines="skip")
|
| 300 |
+
weights = {}
|
| 301 |
+
for _, row in fb_df.iterrows():
|
| 302 |
+
key = (str(row.get("emotion", "")), str(row.get("title", "")))
|
| 303 |
+
accepted = int(row.get("accepted", 0))
|
| 304 |
+
weights[key] = weights.get(key, 0) + (1.0 if accepted == 1 else -0.5)
|
| 305 |
+
return weights
|
| 306 |
+
except Exception:
|
| 307 |
+
return {}
|
| 308 |
+
|
| 309 |
+
def save_feedback_csv(isbn: str, title: str, emotion: str, accepted: int, rank: int):
|
| 310 |
+
pd.DataFrame([{
|
| 311 |
+
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
| 312 |
+
"isbn": isbn,
|
| 313 |
+
"title": title.replace("\n", " ").replace("\r", " "),
|
| 314 |
+
"emotion": emotion,
|
| 315 |
+
"accepted": accepted,
|
| 316 |
+
"input_mode": "gradio",
|
| 317 |
+
"rank": rank,
|
| 318 |
+
}]).to_csv(
|
| 319 |
+
FEEDBACK_PATH, mode="a", index=False,
|
| 320 |
+
header=not FEEDBACK_PATH.exists(),
|
| 321 |
+
encoding="utf-8-sig",
|
| 322 |
+
quoting=csv.QUOTE_ALL,
|
| 323 |
+
)
|
| 324 |
+
if accepted == 1:
|
| 325 |
+
_session.accepted_counts[emotion] += 1
|
| 326 |
+
else:
|
| 327 |
+
_session.rejected_counts[emotion] += 1
|
| 328 |
+
|
| 329 |
+
def get_feedback_stats() -> str:
|
| 330 |
+
if not FEEDBACK_PATH.exists():
|
| 331 |
+
return "π μμ§ νΌλλ°± λ°μ΄ν°κ° μμ΅λλ€."
|
| 332 |
try:
|
| 333 |
+
fb_df = pd.read_csv(FEEDBACK_PATH, encoding="utf-8-sig", on_bad_lines="skip")
|
| 334 |
+
total = len(fb_df)
|
| 335 |
+
if total == 0:
|
| 336 |
+
return "π μμ§ νΌλλ°± λ°μ΄ν°κ° μμ΅λλ€."
|
| 337 |
+
|
| 338 |
+
emo_counts = fb_df.groupby("emotion")["accepted"].agg(["count", "sum"])
|
| 339 |
+
lines = [f"**μ΄ νΌλλ°±: {total}건**\n"]
|
| 340 |
+
for emo, row_s in emo_counts.iterrows():
|
| 341 |
+
rate = int(row_s["sum"]) / int(row_s["count"]) * 100
|
| 342 |
+
lines.append(f"- {emo}: {int(row_s['count'])}건 (μλ½λ₯ {rate:.0f}%)")
|
| 343 |
+
return "\n".join(lines)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 344 |
except Exception as e:
|
| 345 |
+
return f"β οΈ ν΅κ³ λ‘λ μ€ν¨: {e}"
|
|
|
|
| 346 |
|
| 347 |
+
# ============================================================
|
| 348 |
# λ©μΈ μ²λ¦¬ ν¨μ
|
| 349 |
+
# ============================================================
|
| 350 |
def process_voice(audio_input):
|
| 351 |
+
"""Gradio μμ± μ
λ ₯ β STT β κ°μ λΆμ β μΆμ²"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 352 |
if audio_input is None:
|
| 353 |
+
return "π€ μμ±μ λ
Ήμν΄μ£ΌμΈμ.", "", "", [], ""
|
| 354 |
+
|
|
|
|
| 355 |
if stt_model is None:
|
| 356 |
+
return "β STT λͺ¨λΈμ΄ λ‘λλμ§ μμμ΅λλ€.", "", "", [], ""
|
| 357 |
+
|
|
|
|
| 358 |
try:
|
| 359 |
sr, y = audio_input
|
| 360 |
+
y = y.astype(np.float32)
|
| 361 |
+
max_v = np.max(np.abs(y))
|
| 362 |
+
if max_v > 0:
|
| 363 |
+
y = y / max_v
|
| 364 |
+
|
| 365 |
+
# STT
|
| 366 |
stt_result = stt_model({"sampling_rate": sr, "raw": y})
|
| 367 |
+
user_text = stt_result["text"].strip()
|
| 368 |
+
|
| 369 |
+
if not user_text:
|
| 370 |
+
return "β μμ±μ΄ μΈμλμ§ μμμ΅λλ€.", "", "", [], ""
|
| 371 |
+
|
| 372 |
+
# κ°μ λΆμ (ν
μ€νΈ + μμ± μ΅ν©)
|
| 373 |
+
t_scores = text_emotion_scores(user_text)
|
| 374 |
+
a_scores = audio_emotion_scores(y, sr)
|
| 375 |
+
top_label, combined = fused_emotion(t_scores, a_scores)
|
| 376 |
+
top3 = sorted(combined.items(), key=lambda x: x[1], reverse=True)[:3]
|
| 377 |
+
emotion_str = " | ".join(f"{e} {p:.2f}" for e, p in top3)
|
| 378 |
+
|
| 379 |
+
# μΆμ²
|
| 380 |
+
books = get_recommendations(user_text, top_label, top_n=3)
|
| 381 |
+
|
| 382 |
+
# μΆμ² κ²°κ³Ό λ§ν¬λ€μ΄
|
| 383 |
+
books_md = _render_books_md(books, top_label)
|
| 384 |
+
|
| 385 |
+
return user_text, top_label, emotion_str, books, books_md
|
| 386 |
+
|
| 387 |
+
except Exception as e:
|
| 388 |
+
return f"β μ€λ₯: {e}", "", "", [], ""
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
def _render_books_md(books: list, emotion: str) -> str:
|
| 392 |
+
if not books:
|
| 393 |
+
return "μΆμ²ν μ±
μ μ°Ύμ§ λͺ»νμ΅λλ€."
|
| 394 |
+
|
| 395 |
+
md = f"### π [{emotion}] κ°μ μ μ΄μΈλ¦¬λ μ±
\n\n"
|
| 396 |
+
for i, b in enumerate(books, 1):
|
| 397 |
+
ml_icon = "π₯" if b["ml_score"] > 0.7 else ("β¨" if b["ml_score"] > 0.5 else "π‘")
|
| 398 |
+
md += f"**{ml_icon} {i}. {b['title']}**\n"
|
| 399 |
+
md += f"- μ μ: {b['author']} | μΆνμ¬: {b['publisher']}\n"
|
| 400 |
+
md += f"- {b['content']}...\n"
|
| 401 |
+
md += f"- μ μ¬λ: `{b['cosine']}` | ML: `{b['ml_score']}` | μ΅μ’
: `{b['final']}`\n"
|
| 402 |
+
if b["img_url"]:
|
| 403 |
+
md += f"- πΌοΈ [νμ§ λ³΄κΈ°]({b['img_url']})\n"
|
| 404 |
+
md += "\n---\n"
|
| 405 |
+
return md
|
| 406 |
+
|
| 407 |
+
|
| 408 |
+
def on_feedback(books_state: list, emotion: str, rank_str: str, liked: bool):
|
| 409 |
+
"""μ’μμ/μ«μ΄μ λ²νΌ ν΄λ¦"""
|
| 410 |
+
try:
|
| 411 |
+
rank = int(rank_str) - 1
|
| 412 |
+
if not books_state or rank < 0 or rank >= len(books_state):
|
| 413 |
+
return "β οΈ μ±
μ λ¨Όμ μΆμ²λ°μμ£ΌμΈμ."
|
| 414 |
+
book = books_state[rank]
|
| 415 |
+
accepted = 1 if liked else 0
|
| 416 |
+
save_feedback_csv(book["isbn"], book["title"], emotion, accepted, rank + 1)
|
| 417 |
+
icon = "π" if liked else "π"
|
| 418 |
+
return f"{icon} '{book['title']}' νΌλλ°±μ΄ μ μ₯λμμ΅λλ€. νμ΅μ λ°μλ©λλ€!"
|
| 419 |
except Exception as e:
|
| 420 |
+
return f"β οΈ νΌλλ°± μ μ₯ μ€ν¨: {e}"
|
| 421 |
+
|
| 422 |
+
# ============================================================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 423 |
# Gradio UI
|
| 424 |
+
# ============================================================
|
| 425 |
custom_css = """
|
| 426 |
+
.feedback-row { background: #f0f8ff; padding: 12px; border-radius: 8px; }
|
| 427 |
+
.book-card { border: 1px solid #ddd; border-radius: 8px; padding: 12px; margin: 8px 0; }
|
|
|
|
|
|
|
|
|
|
| 428 |
"""
|
| 429 |
|
| 430 |
+
with gr.Blocks(theme=gr.themes.Soft(), css=custom_css, title="Boolook π") as demo:
|
| 431 |
+
|
| 432 |
+
gr.Markdown("""
|
| 433 |
+
# π Boolook β μμ± κΈ°λ° κ°μ λΆμ μ±
μΆμ²
|
| 434 |
+
λΉμ μ κ°μ μ λ§λ‘ νννλ©΄, AIκ° λΆμνμ¬ λ± λ§λ μ±
μ μΆμ²ν΄λ립λλ€.
|
| 435 |
+
|
| 436 |
+
π€ **μ¬μ© λ°©λ²:**
|
| 437 |
+
1. λ§μ΄ν¬ λ²νΌμ λλ¬ νμ¬ κ°μ μ νννμΈμ
|
| 438 |
+
2. "λΆμνκΈ°" λ²νΌμ ν΄λ¦νμΈμ
|
| 439 |
+
3. μΆμ²λ μ±
μ π / π νΌλλ°±μ μ£ΌμΈμ (νμ΅μ λ°μλ©λλ€!)
|
| 440 |
+
""")
|
| 441 |
+
|
| 442 |
+
# μν μ μ₯
|
| 443 |
+
state_books = gr.State([])
|
|
|
|
|
|
|
| 444 |
state_emotion = gr.State("")
|
| 445 |
+
|
|
|
|
| 446 |
with gr.Row():
|
| 447 |
with gr.Column(scale=1):
|
| 448 |
gr.Markdown("### π€ μμ± μ
λ ₯")
|
| 449 |
audio_in = gr.Audio(
|
| 450 |
label="λ§μ΄ν¬λ‘ κ°μ νννκΈ°",
|
| 451 |
sources=["microphone"],
|
| 452 |
+
type="numpy",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 453 |
)
|
| 454 |
+
analyze_btn = gr.Button("π λΆμνκΈ°", variant="primary", size="lg")
|
| 455 |
+
gr.Markdown("""
|
| 456 |
+
**π‘ μμ:**
|
| 457 |
+
- "μ€λ λ무 μ¬νΌμ"
|
| 458 |
+
- "ν볡ν κΈ°λΆμ΄μμ"
|
| 459 |
+
- "νκ° λλ μΌμ΄ μμμ΄μ"
|
| 460 |
+
""")
|
| 461 |
+
|
| 462 |
with gr.Column(scale=1):
|
| 463 |
gr.Markdown("### π λΆμ κ²°κ³Ό")
|
| 464 |
+
out_text = gr.Textbox(label="μΈμλ ν
μ€νΈ", interactive=False)
|
| 465 |
+
out_emotion = gr.Textbox(label="κ°μ§λ μ£Όκ°μ ", interactive=False)
|
| 466 |
+
out_emo_all = gr.Textbox(label="κ°μ λΆν¬ TOP3", interactive=False)
|
| 467 |
+
|
| 468 |
+
gr.Markdown("### π μΆμ² λμ")
|
| 469 |
+
out_books_md = gr.Markdown("λΆμ ν μΆμ² λμκ° νμλ©λλ€.")
|
| 470 |
+
|
| 471 |
+
with gr.Accordion("π¬ νΌλλ°± (νμ΅μ λ°μ)", open=True, elem_classes="feedback-row"):
|
| 472 |
+
gr.Markdown("μΆμ²λ°μ μ±
λ²νΈλ₯Ό μ ννκ³ π / π λ‘ νκ°ν΄μ£ΌμΈμ!")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 473 |
with gr.Row():
|
| 474 |
+
rank_radio = gr.Radio(["1", "2", "3"], label="μ±
λ²νΈ", value="1")
|
| 475 |
+
like_btn = gr.Button("π μ’μμ", variant="primary")
|
| 476 |
+
dislike_btn = gr.Button("π μ«μ΄μ", variant="secondary")
|
| 477 |
+
feedback_out = gr.Textbox(label="νΌλοΏ½οΏ½οΏ½ κ²°κ³Ό", interactive=False)
|
| 478 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
| 479 |
with gr.Accordion("π νΌλλ°± ν΅κ³", open=False):
|
| 480 |
+
stats_md = gr.Markdown("μλ‘κ³ μΉ¨μ λλ¬ νμΈνμΈμ.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 481 |
refresh_stats_btn = gr.Button("π ν΅κ³ μλ‘κ³ μΉ¨")
|
| 482 |
+
refresh_stats_btn.click(fn=get_feedback_stats, outputs=stats_md)
|
| 483 |
+
|
| 484 |
+
# ββ μ΄λ²€νΈ μ°κ²° ββ
|
| 485 |
+
def run_analysis(audio):
|
| 486 |
+
user_text, emotion, emo_all, books, books_md = process_voice(audio)
|
| 487 |
+
return user_text, emotion, emo_all, books, emotion, books_md
|
| 488 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 489 |
analyze_btn.click(
|
| 490 |
+
fn=run_analysis,
|
| 491 |
inputs=audio_in,
|
| 492 |
+
outputs=[out_text, out_emotion, out_emo_all, state_books, state_emotion, out_books_md],
|
| 493 |
+
)
|
| 494 |
+
|
| 495 |
+
like_btn.click(
|
| 496 |
+
fn=lambda books, emo, rank: on_feedback(books, emo, rank, liked=True),
|
| 497 |
+
inputs=[state_books, state_emotion, rank_radio],
|
| 498 |
+
outputs=feedback_out,
|
| 499 |
)
|
| 500 |
+
dislike_btn.click(
|
| 501 |
+
fn=lambda books, emo, rank: on_feedback(books, emo, rank, liked=False),
|
| 502 |
+
inputs=[state_books, state_emotion, rank_radio],
|
| 503 |
+
outputs=feedback_out,
|
|
|
|
| 504 |
)
|
| 505 |
|
| 506 |
if __name__ == "__main__":
|
| 507 |
+
demo.launch()
|