File size: 28,913 Bytes
a4acd69
 
a8f1c4e
46301e8
 
 
 
 
a4acd69
 
4feabfc
 
062c63f
8a1d76f
46301e8
 
a4acd69
 
f428a77
a8f1c4e
a4acd69
5f89afc
a4acd69
bc11a33
a4acd69
5f89afc
a4acd69
 
 
 
5f89afc
 
4feabfc
a4acd69
0ce3b2b
a4acd69
46301e8
 
 
 
 
f428a77
a4acd69
46301e8
 
 
 
 
 
8a1d76f
46301e8
4a3afe3
bc11a33
a4acd69
a8f1c4e
 
 
 
 
 
 
 
46301e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a4acd69
4a3afe3
bc11a33
5f89afc
bc11a33
a4acd69
bc11a33
a8f1c4e
a4acd69
5f89afc
bc11a33
4a3afe3
bc11a33
4a3afe3
bc11a33
5f89afc
bc11a33
a4acd69
 
5f89afc
a8f1c4e
4a3afe3
bc11a33
4a3afe3
ca68191
4a3afe3
a4acd69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5f89afc
 
 
 
 
 
 
a8f1c4e
5f89afc
 
4a3afe3
a4acd69
46301e8
 
 
 
 
 
 
a4acd69
 
 
 
 
 
 
 
 
 
 
 
5f89afc
a4acd69
 
 
 
 
 
 
5f89afc
 
 
b9098cc
a4acd69
0ce3b2b
a4acd69
a8f1c4e
a4acd69
a8f1c4e
 
 
a4acd69
4a3afe3
a8f1c4e
a4acd69
5f89afc
a8f1c4e
4a3afe3
5f89afc
4a3afe3
a8f1c4e
a4acd69
5f89afc
a4acd69
5f89afc
 
 
4a3afe3
5f89afc
4a3afe3
5f89afc
a8f1c4e
a4acd69
4a3afe3
5f89afc
 
 
 
a8f1c4e
5f89afc
 
a8f1c4e
 
 
 
5f89afc
a8f1c4e
 
 
5f89afc
 
 
4a3afe3
5f89afc
4a3afe3
5f89afc
bc11a33
5f89afc
 
a8f1c4e
5f89afc
a8f1c4e
5f89afc
a8f1c4e
bc11a33
4a3afe3
a8f1c4e
 
 
 
 
 
0ce3b2b
4a3afe3
a4acd69
a8f1c4e
a4acd69
 
bc11a33
a4acd69
5f89afc
a4acd69
5f89afc
 
a4acd69
5f89afc
f428a77
a4acd69
 
5f89afc
 
4a3afe3
a4acd69
 
 
 
 
 
 
 
 
 
 
 
 
f428a77
46301e8
 
 
 
 
 
5f89afc
46301e8
 
 
 
 
 
 
 
 
 
a4acd69
f428a77
5f89afc
 
 
 
a8f1c4e
5f89afc
 
41a5227
5f89afc
 
 
 
a4acd69
46301e8
a4acd69
 
 
845db5f
a8f1c4e
 
 
 
 
 
bc11a33
a4acd69
5f89afc
 
845db5f
a8f1c4e
5f89afc
 
 
 
 
 
a8f1c4e
5f89afc
 
 
a8f1c4e
 
5f89afc
a8f1c4e
 
 
5f89afc
a8f1c4e
 
 
5f89afc
 
 
 
 
4a3afe3
5f89afc
a4acd69
46301e8
f428a77
 
 
845db5f
f428a77
 
 
 
4a3afe3
f428a77
 
845db5f
f428a77
 
 
 
 
 
 
 
 
 
 
 
 
46301e8
a4acd69
5f89afc
a4acd69
5f89afc
a4acd69
 
 
a8f1c4e
a4acd69
 
6a318c2
a8f1c4e
a4acd69
 
 
 
 
f428a77
a4acd69
5f89afc
 
 
a8f1c4e
 
 
 
 
5f89afc
 
 
 
 
 
 
 
 
 
 
4a3afe3
a4acd69
f428a77
6a318c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a4acd69
 
46301e8
bc11a33
a4acd69
 
 
46301e8
a4acd69
 
 
a8f1c4e
5f89afc
a8f1c4e
5f89afc
a4acd69
bc11a33
4a3afe3
0ce3b2b
46301e8
a4acd69
5f89afc
a4acd69
bc11a33
a8f1c4e
6a318c2
ca68191
6a318c2
bc11a33
6a318c2
a4acd69
8a1d76f
6a318c2
 
 
 
 
 
 
 
 
 
 
5f89afc
6a318c2
5f89afc
a4acd69
 
 
 
bc11a33
4a3afe3
a4acd69
845db5f
6a318c2
a4acd69
845db5f
46301e8
a4acd69
845db5f
 
a4acd69
6a318c2
a4acd69
 
4a3afe3
6a318c2
a4acd69
b9098cc
a8f1c4e
6a318c2
 
a8f1c4e
46301e8
f428a77
 
 
46301e8
a4acd69
46301e8
5f89afc
46301e8
a4acd69
 
6a318c2
a4acd69
062c63f
bc11a33
46301e8
6a318c2
 
 
 
 
46301e8
 
a4acd69
bc11a33
f428a77
46301e8
f428a77
 
 
a4acd69
46301e8
a8f1c4e
46301e8
5f89afc
a4acd69
6a318c2
 
 
 
 
 
 
 
 
 
 
 
bc11a33
a4acd69
0ce3b2b
6a318c2
062c63f
bc11a33
 
46301e8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
"""
Boolook - ์Œ์„ฑ ๊ธฐ๋ฐ˜ ๊ฐ์ • ๋ถ„์„ ์ฑ… ์ถ”์ฒœ (HuggingFace Spaces)
์ˆ˜์ •์‚ฌํ•ญ:
  - final_emotion_model_v3.pth (ResNet-SE + BiLSTM + Attention) ์ปค์Šคํ…€ ๋ชจ๋ธ ํ†ตํ•ฉ
  - superb/wav2vec2-base-superb-er ๋Œ€์‹  ์ปค์Šคํ…€ ๋ชจ๋ธ๋กœ ์Œ์„ฑ ๊ฐ์ • ๋ถ„๋ฅ˜
  - ๋ชจ๋ธ ํด๋ž˜์Šค ์ •์˜ (SEBlock, ResBlock, AttentionPooling, EmotionResNet) ํฌํ•จ
  - Mel-spectrogram ์ „์ฒ˜๋ฆฌ + TTA(n_tta=8) ์ถ”๋ก  + temperature scaling ์ ์šฉ
  - 4ํด๋ž˜์Šค(Angry/Happy/Neutral/Sad) โ†’ ํ•œ๊ตญ์–ด ๊ฐ์ • ๋ ˆ์ด๋ธ” ๋งคํ•‘
"""

import gradio as gr
import pandas as pd
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import pickle
import csv
import json
import threading
import warnings
import logging
from pathlib import Path
from datetime import datetime
from collections import defaultdict
from typing import Dict, List, Tuple
from transformers import pipeline as hf_pipeline
from sentence_transformers import SentenceTransformer, util as sbert_util

warnings.filterwarnings("ignore")
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# ============================================================
# ์„ค์ •
# ============================================================
BOOK_DB_PATH        = Path("book_db_final.csv")
FEEDBACK_PATH       = Path("user_feedback.csv")
SBERT_CACHE_PATH    = Path("book_embeddings.pkl")
EMOTION_MODEL_PATH  = Path("final_emotion_model_v3.pth")
SAMPLE_RATE         = 16000
MAX_EMBEDDING_BATCH = 128

# Mel-spectrogram ํŒŒ๋ผ๋ฏธํ„ฐ (ํ•™์Šต ์‹œ ์‚ฌ์šฉํ•œ ๊ฐ’๊ณผ ๋™์ผํ•˜๊ฒŒ ๋งž์ถœ ๊ฒƒ)
N_MELS    = 64
N_FFT     = 1024
HOP_LEN   = 512
MAX_FRAMES = 128   # ์‹œ๊ฐ„ ์ถ• ๊ณ ์ • ๊ธธ์ด

device = 0 if torch.cuda.is_available() else -1
torch_device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
logger.info(f"๋””๋ฐ”์ด์Šค: {'GPU' if device == 0 else 'CPU'}")

# ============================================================
# ์ „์—ญ ์ƒํƒœ (๋ฐฑ๊ทธ๋ผ์šด๋“œ ๋กœ๋”ฉ์šฉ)
# ============================================================
df              = pd.DataFrame()
book_embeddings = torch.tensor([])
_data_ready     = False
_data_lock      = threading.Lock()

# ============================================================
# โ‘  ์ปค์Šคํ…€ ๊ฐ์ • ๋ชจ๋ธ ์•„ํ‚คํ…์ฒ˜ ์ •์˜
# ============================================================

class SEBlock(nn.Module):
    """Squeeze-and-Excitation Block"""
    def __init__(self, channels: int, reduction: int = 16):
        super().__init__()
        self.excitation = nn.Sequential(
            nn.Linear(channels, channels // reduction, bias=False),
            nn.ReLU(inplace=True),
            nn.Linear(channels // reduction, channels, bias=False),
            nn.Sigmoid(),
        )

    def forward(self, x):
        # x: (B, C, H, W)
        b, c, _, _ = x.shape
        w = x.mean(dim=[2, 3])          # global avg pool
        w = self.excitation(w).view(b, c, 1, 1)
        return x * w


class ResBlock(nn.Module):
    """ResNet Basic Block with SE"""
    def __init__(self, in_ch: int, out_ch: int, stride: int = 1):
        super().__init__()
        self.conv1 = nn.Conv2d(in_ch, out_ch, 3, stride=stride, padding=1, bias=False)
        self.bn1   = nn.BatchNorm2d(out_ch)
        self.conv2 = nn.Conv2d(out_ch, out_ch, 3, padding=1, bias=False)
        self.bn2   = nn.BatchNorm2d(out_ch)
        self.se    = SEBlock(out_ch, reduction=max(1, out_ch // 16))

        self.shortcut = nn.Sequential()
        if stride != 1 or in_ch != out_ch:
            self.shortcut = nn.Sequential(
                nn.Conv2d(in_ch, out_ch, 1, stride=stride, bias=False),
                nn.BatchNorm2d(out_ch),
            )

    def forward(self, x):
        out = F.relu(self.bn1(self.conv1(x)), inplace=True)
        out = self.bn2(self.conv2(out))
        out = self.se(out)
        out = F.relu(out + self.shortcut(x), inplace=True)
        return out


class AttentionPooling(nn.Module):
    """Temporal Attention Pooling"""
    def __init__(self, hidden: int):
        super().__init__()
        self.attn = nn.Linear(hidden, 1)

    def forward(self, x):
        # x: (B, T, H)
        w = torch.softmax(self.attn(x), dim=1)   # (B, T, 1)
        return (x * w).sum(dim=1)                 # (B, H)


class EmotionResNet(nn.Module):
    """
    ResNet-SE + 2-layer BiLSTM + Attention Pooling + Classifier
    ์ž…๋ ฅ: (B, 1, N_MELS, T) Mel-spectrogram
    ์ถœ๋ ฅ: (B, num_classes) logits
    """
    def __init__(self, num_classes: int = 4):
        super().__init__()
        # CNN stem
        self.conv1 = nn.Sequential(
            nn.Conv2d(1, 64, 7, stride=2, padding=3, bias=False),
            nn.BatchNorm2d(64),
        )
        # ResNet layers
        self.layer1 = nn.Sequential(ResBlock(64,  64),  ResBlock(64,  64))
        self.layer2 = nn.Sequential(ResBlock(64,  128, stride=2), ResBlock(128, 128))
        self.layer3 = nn.Sequential(ResBlock(128, 256, stride=2), ResBlock(256, 256))

        # BiLSTM (2 layers)
        self.bilstm = nn.LSTM(
            input_size=256, hidden_size=256,
            num_layers=2, batch_first=True,
            bidirectional=True, dropout=0.3,
        )

        # Attention
        self.attention = AttentionPooling(hidden=512)

        # Classifier
        self.classifier = nn.Sequential(
            nn.Linear(512, 256),
            nn.BatchNorm1d(256),
            nn.ReLU(inplace=True),
            nn.Dropout(0.5),
            nn.Linear(256, num_classes),
        )

    def forward(self, x):
        # CNN
        x = F.relu(self.conv1(x), inplace=True)
        x = self.layer1(x)
        x = self.layer2(x)
        x = self.layer3(x)

        # (B, C, H, W) โ†’ temporal sequence: global-avg over freq axis
        x = x.mean(dim=2)          # (B, C, W)
        x = x.permute(0, 2, 1)    # (B, T, C)

        # BiLSTM
        x, _ = self.bilstm(x)     # (B, T, 512)

        # Attention pooling
        x = self.attention(x)     # (B, 512)

        return self.classifier(x)


# ============================================================
# โ‘ก ์ปค์Šคํ…€ ๊ฐ์ • ๋ชจ๋ธ ๋กœ๋“œ
# ============================================================
_emotion_model      = None
_emotion_classes    = ["Angry", "Happy", "Neutral", "Sad"]
_emotion_label_enc  = None
_emotion_temp       = 1.0
_emotion_n_tta      = 1

def _load_emotion_model():
    global _emotion_model, _emotion_classes, _emotion_label_enc, _emotion_temp, _emotion_n_tta
    if not EMOTION_MODEL_PATH.exists():
        logger.error(f"{EMOTION_MODEL_PATH} ํŒŒ์ผ์ด ์—†์Šต๋‹ˆ๋‹ค. ์ปค์Šคํ…€ ๊ฐ์ • ๋ชจ๋ธ์„ ์‚ฌ์šฉํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.")
        return

    try:
        ckpt = torch.load(EMOTION_MODEL_PATH, map_location="cpu", weights_only=False)

        _emotion_classes   = [str(c) for c in ckpt.get("classes", _emotion_classes)]
        _emotion_label_enc = ckpt.get("label_encoder", None)
        _emotion_temp      = float(ckpt.get("temperature", 1.0))
        _emotion_n_tta     = int(ckpt.get("n_tta", 1))

        model = EmotionResNet(num_classes=len(_emotion_classes))
        model.load_state_dict(ckpt["model_state_dict"])
        model.to(torch_device)
        model.eval()

        _emotion_model = model
        logger.info(
            f"์ปค์Šคํ…€ ๊ฐ์ • ๋ชจ๋ธ ๋กœ๋“œ ์™„๋ฃŒ | "
            f"ํด๋ž˜์Šค: {_emotion_classes} | "
            f"val_acc: {ckpt.get('val_accuracy', 'N/A')} | "
            f"val_f1: {ckpt.get('best_val_f1', 'N/A'):.4f} | "
            f"temp: {_emotion_temp} | TTA: {_emotion_n_tta}"
        )
    except Exception as e:
        logger.error(f"์ปค์Šคํ…€ ๊ฐ์ • ๋ชจ๋ธ ๋กœ๋“œ ์‹คํŒจ: {e}")

_load_emotion_model()

# ============================================================
# โ‘ข Mel-spectrogram ์ „์ฒ˜๋ฆฌ
# ============================================================
def _compute_melspec(y: np.ndarray, sr: int) -> torch.Tensor:
    """
    ์˜ค๋””์˜ค ๋ฐฐ์—ด โ†’ (1, 1, N_MELS, MAX_FRAMES) ํ…์„œ
    librosa ์—†์ด torch๋งŒ ์‚ฌ์šฉํ•˜๋Š” ๊ฐ„์ด ๊ตฌํ˜„
    """
    try:
        import librosa
        mel = librosa.feature.melspectrogram(
            y=y, sr=sr,
            n_mels=N_MELS, n_fft=N_FFT, hop_length=HOP_LEN,
        )
        mel_db = librosa.power_to_db(mel, ref=np.max)
    except ImportError:
        # librosa ์—†์„ ๋•Œ torch STFT๋กœ ๋Œ€์ฒด
        wav = torch.tensor(y, dtype=torch.float32)
        window = torch.hann_window(N_FFT)
        stft = torch.stft(wav, N_FFT, HOP_LEN, return_complex=True, window=window)
        power = stft.abs() ** 2                         # (freq, T)
        # ๊ฐ„์ด mel filterbank (์‚ผ๊ฐํ˜• ๊ทผ์‚ฌ)
        mel_fb = torch.zeros(N_MELS, power.shape[0])
        for m in range(N_MELS):
            mel_fb[m, m * (power.shape[0] // N_MELS):
                       (m + 1) * (power.shape[0] // N_MELS)] = 1.0
        mel = mel_fb @ power                            # (N_MELS, T)
        mel_db = (mel + 1e-6).log().numpy()

    # ์ •๊ทœํ™”
    mel_db = (mel_db - mel_db.mean()) / (mel_db.std() + 1e-6)

    # ์‹œ๊ฐ„ ์ถ• ํŒจ๋”ฉ/์ž๋ฅด๊ธฐ
    T = mel_db.shape[1]
    if T < MAX_FRAMES:
        mel_db = np.pad(mel_db, ((0, 0), (0, MAX_FRAMES - T)), mode="constant")
    else:
        mel_db = mel_db[:, :MAX_FRAMES]

    # (1, 1, N_MELS, MAX_FRAMES)
    tensor = torch.tensor(mel_db, dtype=torch.float32).unsqueeze(0).unsqueeze(0)
    return tensor.to(torch_device)


# ============================================================
# โ‘ฃ TTA ์ถ”๋ก 
# ============================================================
def _tta_augment(spec: torch.Tensor) -> torch.Tensor:
    """๋‹จ์ˆœ ์‹œ๊ฐ„ ์ด๋™ augmentation for TTA"""
    shift = np.random.randint(-MAX_FRAMES // 8, MAX_FRAMES // 8)
    return torch.roll(spec, shift, dims=-1)


def _infer_emotion_model(y: np.ndarray, sr: int) -> Dict[str, float]:
    """์ปค์Šคํ…€ ๋ชจ๋ธ ์ถ”๋ก  โ†’ ํด๋ž˜์Šค๋ณ„ ํ™•๋ฅ  dict (์›๋ณธ ์˜์–ด ๋ ˆ์ด๋ธ”)"""
    if _emotion_model is None:
        return {c: 0.0 for c in _emotion_classes}

    try:
        spec = _compute_melspec(y, sr)   # (1, 1, N_MELS, T)

        logits_list = []
        with torch.no_grad():
            n = max(1, _emotion_n_tta)
            for i in range(n):
                inp = _tta_augment(spec) if i > 0 else spec
                logits = _emotion_model(inp)              # (1, num_classes)
                logits_list.append(logits)

        avg_logits = torch.stack(logits_list).mean(dim=0)          # (1, C)
        probs = torch.softmax(avg_logits / _emotion_temp, dim=-1)  # temperature scaling
        probs = probs[0].cpu().numpy()

        return {cls: float(p) for cls, p in zip(_emotion_classes, probs)}

    except Exception as e:
        logger.error(f"์ปค์Šคํ…€ ๋ชจ๋ธ ์ถ”๋ก  ์‹คํŒจ: {e}")
        return {c: 0.0 for c in _emotion_classes}


# ============================================================
# ๋ชจ๋ธ ๋กœ๋”ฉ (STT, SBERT)
# ============================================================
logger.info("๋ชจ๋ธ ๋กœ๋”ฉ ์ค‘...")

stt_model = None
try:
    stt_model = hf_pipeline(
        "automatic-speech-recognition",
        model="openai/whisper-small",
        device=device,
        chunk_length_s=30,
    )
    logger.info("STT ๋ชจ๋ธ ๋กœ๋“œ ์™„๋ฃŒ (whisper-small)")
except Exception as e:
    logger.error(f"STT ๋กœ๋“œ ์‹คํŒจ: {e}")

sbert_model = None
try:
    sbert_model = SentenceTransformer("jhgan/ko-sroberta-multitask")
    sbert_model.max_seq_length = 384
    if torch.cuda.is_available():
        sbert_model = sbert_model.to("cuda")
    logger.info("SBERT ๋ชจ๋ธ ๋กœ๋“œ ์™„๋ฃŒ")
except Exception as e:
    logger.error(f"SBERT ๋กœ๋“œ ์‹คํŒจ: {e}")

logger.info("๋ชจ๋ธ ๋กœ๋”ฉ ์™„๋ฃŒ!")

# ============================================================
# ๊ฐ์ • ๋ ˆ์ด๋ธ” & ์„ค๋ช…
# ============================================================
_EMOTION_DESCS = {
    "๊ธฐ์จ": "ํ–‰๋ณตํ•˜๊ณ  ์ฆ๊ฒ๊ณ  ์œ ์พŒํ•œ ๊ธฐ๋ถ„",
    "์‹ ๋ขฐ": "๋”ฐ๋œปํ•˜๊ณ  ์•ˆ์ •์ ์ด๋ฉฐ ๊ฐ€์กฑ๊ณผ ์šฐ์ • ๊ฐ™์€ ์œ ๋Œ€๊ฐ",
    "๊ณตํฌ": "๋ฌด์„ญ๊ณ  ๊ธด์žฅ๋˜๋ฉฐ ์Šค๋ฆด ์žˆ๋Š” ๊ณตํฌ์™€ ๋ถˆ์•ˆ",
    "๋†€๋žŒ": "๋ฐ˜์ „๊ณผ ์ถฉ๊ฒฉ, ์˜ˆ์ƒ์น˜ ๋ชปํ•œ ๊ฒฝ์ด๋กœ์›€",
    "์Šฌํ””": "์Šฌํ”„๊ณ  ์™ธ๋กญ๊ณ  ์ด๋ณ„๊ณผ ์ƒ์‹ค์˜ ๊ฐ์ •",
    "ํ˜์˜ค": "๋ถ€์กฐ๋ฆฌ์™€ ๋ถˆํ‰๋“ฑ, ์œ„์„ ์— ๋Œ€ํ•œ ๋น„ํŒ๊ณผ ํ’์ž",
    "๋ถ„๋…ธ": "๋ถ„๋…ธ์™€ ์ €ํ•ญ, ํˆฌ์Ÿ๊ณผ ๊ฐˆ๋“ฑ",
    "๊ธฐ๋Œ€": "์„ฑ์žฅ๊ณผ ๋„์ „, ๋ชจํ—˜๊ณผ ํฌ๋ง",
}
_EMOTION_LABELS = list(_EMOTION_DESCS.keys())

_LABEL_EMBS = None
if sbert_model:
    try:
        _LABEL_EMBS = sbert_model.encode(
            list(_EMOTION_DESCS.values()),
            convert_to_tensor=True,
            show_progress_bar=False,
        )
    except Exception as e:
        logger.error(f"๊ฐ์ • ๋ ˆ์ด๋ธ” ์ž„๋ฒ ๋”ฉ ์‹คํŒจ: {e}")

# ์ปค์Šคํ…€ ๋ชจ๋ธ ์˜์–ด ๋ ˆ์ด๋ธ” โ†’ ํ•œ๊ตญ์–ด ๋งคํ•‘
_CUSTOM_LABEL_MAP: Dict[str, str] = {
    "Happy":   "๊ธฐ์จ",
    "Sad":     "์Šฌํ””",
    "Angry":   "๋ถ„๋…ธ",
    "Neutral": "์‹ ๋ขฐ",
}

_KEYWORD_BOOSTS = {
    "์Šฌํ””": ["์Šฌํ”„", "์šฐ์šธ", "๋ˆˆ๋ฌผ", "ํž˜๋“ค", "์™ธ๋กœ"],
    "๋ถ„๋…ธ": ["ํ™”๋‚˜", "์งœ์ฆ", "์—ด๋ฐ›", "๋นก์น˜", "์–ต์šธ"],
    "๊ธฐ์จ": ["ํ–‰๋ณต", "์ข‹๋‹ค", "๊ธฐ์˜", "์ฆ๊ฒ", "์‹ ๋‚˜"],
    "๊ณตํฌ": ["๋ฌด์„ญ", "๋‘๋ ต", "๊ฑฑ์ •", "๋ถˆ์•ˆ"],
    "๋†€๋žŒ": ["๋†€๋ž", "๊นœ์ง", "์ถฉ๊ฒฉ"],
    "์‹ ๋ขฐ": ["๋ฏฟ์Œ", "์‚ฌ๋ž‘", "๋”ฐ๋œป", "๊ณ ๋งˆ"],
    "๊ธฐ๋Œ€": ["๊ธฐ๋Œ€", "ํฌ๋ง", "์„ค๋ ˆ"],
}

# ============================================================
# ์„ธ์…˜ ํ”ผ๋“œ๋ฐฑ
# ============================================================
class SessionFeedback:
    def __init__(self):
        self.accepted_counts = defaultdict(int)
        self.rejected_counts = defaultdict(int)

    def score_multiplier(self, emotion: str) -> float:
        acc = self.accepted_counts.get(emotion, 0)
        rej = self.rejected_counts.get(emotion, 0)
        return max(0.5, min(2.0, 1.0 + (0.1 * acc) - (0.1 * rej)))

_session = SessionFeedback()

# ============================================================
# ๋„์„œ ๋ฐ์ดํ„ฐ ๋กœ๋“œ (๋ฐฑ๊ทธ๋ผ์šด๋“œ ์ „์šฉ)
# ============================================================
def load_book_data():
    global df, book_embeddings, _data_ready

    if not BOOK_DB_PATH.exists():
        logger.error(f"{BOOK_DB_PATH} ํŒŒ์ผ์ด ์—†์Šต๋‹ˆ๋‹ค.")
        return

    try:
        _df = pd.read_csv(BOOK_DB_PATH, encoding="utf-8-sig").fillna("")
        logger.info(f"{len(_df)}๊ถŒ ๋กœ๋“œ ์™„๋ฃŒ")
    except Exception as e:
        logger.error(f"CSV ๋กœ๋“œ ์‹คํŒจ: {e}")
        return

    emb_cache = {}
    if SBERT_CACHE_PATH.exists():
        try:
            with open(SBERT_CACHE_PATH, "rb") as f:
                emb_cache = pickle.load(f)
            logger.info(f"์ž„๋ฒ ๋”ฉ ์บ์‹œ: {len(emb_cache)}๊ฐœ")
        except Exception as e:
            logger.warning(f"์บ์‹œ ๋กœ๋“œ ์‹คํŒจ: {e}")

    missing = [i for i, row in _df.iterrows() if str(row["isbn"]) not in emb_cache]
    if missing and sbert_model:
        logger.info(f"์‹ ๊ทœ ์ž„๋ฒ ๋”ฉ ๊ณ„์‚ฐ: {len(missing)}๊ถŒ")
        try:
            for start in range(0, len(missing), MAX_EMBEDDING_BATCH):
                batch = missing[start:start + MAX_EMBEDDING_BATCH]
                texts = [
                    (str(_df.at[i, "title"]) + " " + str(_df.at[i, "content"]))[:500]
                    for i in batch
                ]
                vecs = sbert_model.encode(
                    texts, convert_to_tensor=False, show_progress_bar=False,
                    batch_size=MAX_EMBEDDING_BATCH,
                )
                for i, vec in zip(batch, vecs):
                    emb_cache[str(_df.at[i, "isbn"])] = vec
                if (start // MAX_EMBEDDING_BATCH) % 10 == 0:
                    logger.info(f"  ์ง„ํ–‰: {start}/{len(missing)}")

            with open(SBERT_CACHE_PATH, "wb") as f:
                pickle.dump(emb_cache, f)
            logger.info("์ž„๋ฒ ๋”ฉ ์ €์žฅ ์™„๋ฃŒ")
        except Exception as e:
            logger.error(f"์ž„๋ฒ ๋”ฉ ๊ณ„์‚ฐ ์‹คํŒจ: {e}")

    try:
        emb_matrix = np.stack([
            emb_cache.get(str(row["isbn"]), np.zeros(384))
            for _, row in _df.iterrows()
        ])
        _book_emb = torch.tensor(emb_matrix, dtype=torch.float32)
        if torch.cuda.is_available():
            _book_emb = _book_emb.to("cuda")
    except Exception as e:
        logger.error(f"์ž„๋ฒ ๋”ฉ ํ–‰๋ ฌ ์ƒ์„ฑ ์‹คํŒจ: {e}")
        _book_emb = torch.tensor([])

    with _data_lock:
        df              = _df
        book_embeddings = _book_emb
        _data_ready     = True

    logger.info("๋ฐฑ๊ทธ๋ผ์šด๋“œ ๋ฐ์ดํ„ฐ ๋กœ๋“œ ์™„๋ฃŒ!")

threading.Thread(target=load_book_data, daemon=True).start()

# ============================================================
# ๊ฐ์ • ๋ถ„์„
# ============================================================
def text_emotion_scores(text: str) -> Dict[str, float]:
    scores = {emo: 0.0 for emo in _EMOTION_LABELS}
    if not text or not sbert_model or _LABEL_EMBS is None:
        return scores

    try:
        user_emb   = sbert_model.encode(text, convert_to_tensor=True, show_progress_bar=False)
        cos_scores = sbert_util.cos_sim(user_emb, _LABEL_EMBS)[0]
        for i, label in enumerate(_EMOTION_LABELS):
            scores[label] = float(cos_scores[i].item())
    except Exception as e:
        logger.error(f"ํ…์ŠคํŠธ ๊ฐ์ • ์‹คํŒจ: {e}")

    text_lower = text.lower()
    for emotion, keywords in _KEYWORD_BOOSTS.items():
        for kw in keywords:
            if kw in text_lower:
                scores[emotion] += 0.15
                break

    total = sum(scores.values())
    if total > 0:
        scores = {k: v / total for k, v in scores.items()}
    return scores


def audio_emotion_scores(y: np.ndarray, sr: int) -> Dict[str, float]:
    """
    ์ปค์Šคํ…€ ๋ชจ๋ธ(final_emotion_model_v3.pth)๋กœ ์Œ์„ฑ ๊ฐ์ • ์ ์ˆ˜ ๋ฐ˜ํ™˜.
    ์˜์–ด 4ํด๋ž˜์Šค ํ™•๋ฅ ์„ ํ•œ๊ตญ์–ด 8ํด๋ž˜์Šค ๊ณต๊ฐ„์œผ๋กœ ๋งคํ•‘.
    """
    base = {emo: 0.0 for emo in _EMOTION_LABELS}

    raw = _infer_emotion_model(y, sr)   # {"Happy": 0.6, "Sad": 0.2, ...}
    if not raw or all(v == 0 for v in raw.values()):
        return base

    for eng_label, prob in raw.items():
        kor_label = _CUSTOM_LABEL_MAP.get(eng_label)
        if kor_label and kor_label in base:
            base[kor_label] += prob

    return base


def fused_emotion(t_scores: Dict[str, float], a_scores: Dict[str, float]) -> Tuple[str, Dict[str, float]]:
    if all(v == 0 for v in a_scores.values()):
        combined = t_scores
    else:
        a_max  = max(a_scores.values()) or 1.0
        a_norm = {e: v / a_max for e, v in a_scores.items()}
        combined = {
            emo: (t_scores[emo] * 0.6) + (a_norm[emo] * 0.4)
            for emo in _EMOTION_LABELS
        }
    top_emotion = max(combined, key=combined.get)
    return top_emotion, combined


# ============================================================
# ์ถ”์ฒœ
# ============================================================
def get_recommendations(user_input: str, emotion: str, top_n: int = 3) -> List[Dict]:
    with _data_lock:
        ready = _data_ready
        _df   = df
        _emb  = book_embeddings

    if not ready or sbert_model is None or _df.empty or len(_emb) == 0:
        return []

    try:
        session_w = _session.score_multiplier(emotion)
        user_vec  = sbert_model.encode(user_input, convert_to_tensor=True, show_progress_bar=False)
        cos_sims  = sbert_util.cos_sim(user_vec, _emb)[0]
        if torch.cuda.is_available():
            cos_sims = cos_sims.cpu()
        cos_sims = cos_sims.numpy()

        fb_weights = _load_feedback_weights()
        results = []
        for idx, (_, row) in enumerate(_df.iterrows()):
            if idx >= len(cos_sims):
                break
            fb_boost = fb_weights.get((emotion, str(row["title"])), 0) * 0.1
            cosine   = float(cos_sims[idx])
            final    = cosine * session_w + fb_boost
            results.append({
                "isbn":      str(row.get("isbn", "")),
                "title":     str(row.get("title", "")),
                "author":    str(row.get("author", "-")),
                "publisher": str(row.get("publisher", "-")),
                "content":   str(row.get("content", ""))[:150],
                "img_url":   str(row.get("img_url", "")),
                "score":     round(final, 3),
            })

        results.sort(key=lambda x: x["score"], reverse=True)
        return results[:top_n]
    except Exception as e:
        logger.error(f"์ถ”์ฒœ ์‹คํŒจ: {e}")
        return []


# ============================================================
# ์ถ”์ฒœ ๊ฒฐ๊ณผ โ†’ JSON ๋ Œ๋”๋ง
# ============================================================
def _render_books_json(user_input: str, emotion: str, combined: Dict[str, float], books: List[Dict]) -> str:
    if not books:
        return json.dumps({"error": "์ถ”์ฒœํ•  ์ฑ…์„ ์ฐพ์ง€ ๋ชปํ–ˆ์Šต๋‹ˆ๋‹ค."}, ensure_ascii=False, indent=2)

    output = {
        "user_input":    user_input,
        "emotion":       emotion,
        "emotion_score": round(combined.get(emotion, 0.0), 3),
        "recommendation_books": [
            {
                "isbn":      b["isbn"],
                "title":     b["title"],
                "author":    b["author"],
                "publisher": b["publisher"],
                "content":   b["content"],
                "img_url":   b["img_url"],
            }
            for b in books
        ],
    }
    return json.dumps(output, ensure_ascii=False, indent=2)


# ============================================================
# ํ”ผ๋“œ๋ฐฑ
# ============================================================
def _load_feedback_weights() -> Dict[Tuple[str, str], float]:
    if not FEEDBACK_PATH.exists():
        return {}
    try:
        fb_df   = pd.read_csv(FEEDBACK_PATH, encoding="utf-8-sig", on_bad_lines="skip")
        weights = {}
        for _, row in fb_df.iterrows():
            key          = (str(row.get("emotion", "")), str(row.get("title", "")))
            accepted     = int(row.get("accepted", 0))
            weights[key] = weights.get(key, 0) + (1.0 if accepted == 1 else -0.5)
        return weights
    except Exception:
        return {}


def save_feedback_csv(isbn: str, title: str, emotion: str, accepted: int, rank: int):
    try:
        data = {
            "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            "isbn":      isbn,
            "title":     title.replace("\n", " ").replace("\r", " "),
            "emotion":   emotion,
            "accepted":  accepted,
            "rank":      rank,
        }
        pd.DataFrame([data]).to_csv(
            FEEDBACK_PATH, mode="a", index=False,
            header=not FEEDBACK_PATH.exists(),
            encoding="utf-8-sig", quoting=csv.QUOTE_ALL,
        )
        if accepted == 1:
            _session.accepted_counts[emotion] += 1
        else:
            _session.rejected_counts[emotion] += 1
    except Exception as e:
        logger.error(f"ํ”ผ๋“œ๋ฐฑ ์ €์žฅ ์‹คํŒจ: {e}")


def api_feedback(feedback_data) -> str:
    """
    ํด๋ผ์ด์–ธํŠธ ์ „์†ก ํ˜•์‹:
    {
      "9788901234567": {"emotion": "๊ธฐ์จ", "accepted": 1, "rank": 1},
      "9788907654321": {"emotion": "๊ธฐ์จ", "accepted": 0, "rank": 2}
    }
    """
    try:
        data = json.loads(feedback_data) if isinstance(feedback_data, str) else feedback_data
        with _data_lock:
            _df = df

        saved = []
        for isbn, info in data.items():
            emotion  = str(info.get("emotion", ""))
            accepted = int(info.get("accepted", 0))
            rank     = int(info.get("rank", 1))

            row   = _df[_df["isbn"].astype(str) == isbn]
            title = row["title"].iloc[0] if not row.empty else isbn

            save_feedback_csv(isbn, title, emotion, accepted, rank)
            saved.append(isbn)

        return json.dumps({"status": "ok", "saved": saved}, ensure_ascii=False, indent=2)
    except Exception as e:
        logger.error(f"API ํ”ผ๋“œ๋ฐฑ ์‹คํŒจ: {e}")
        return json.dumps({"error": str(e)}, ensure_ascii=False, indent=2)

def get_feedback_stats() -> str:
    if not FEEDBACK_PATH.exists():
        return "์•„์ง ํ”ผ๋“œ๋ฐฑ์ด ์—†์Šต๋‹ˆ๋‹ค."
    try:
        fb_df = pd.read_csv(FEEDBACK_PATH, encoding="utf-8-sig", on_bad_lines="skip")
        total = len(fb_df)
        if total == 0:
            return "์•„์ง ํ”ผ๋“œ๋ฐฑ์ด ์—†์Šต๋‹ˆ๋‹ค."
        emo_counts = fb_df.groupby("emotion")["accepted"].agg(["count", "sum"])
        lines = [f"**์ด ํ”ผ๋“œ๋ฐฑ: {total}๊ฑด**\n"]
        for emo, row_s in emo_counts.iterrows():
            count    = int(row_s["count"])
            accepted = int(row_s["sum"])
            rate     = (accepted / count * 100) if count > 0 else 0
            lines.append(f"- {emo}: {count}๊ฑด (์ˆ˜๋ฝ๋ฅ  {rate:.0f}%)")
        return "\n".join(lines)
    except Exception as e:
        return f"ํ†ต๊ณ„ ๋กœ๋“œ ์‹คํŒจ: {e}"


# ============================================================
# ๋ฉ”์ธ ์ฒ˜๋ฆฌ
# ============================================================
def process_voice(audio_input):
    if not _data_ready:
        return json.dumps({"error": "๋„์„œ ๋ฐ์ดํ„ฐ ๋กœ๋”ฉ ์ค‘์ž…๋‹ˆ๋‹ค. ์ž ์‹œ ํ›„ ๋‹ค์‹œ ์‹œ๋„ํ•ด์ฃผ์„ธ์š”."}, ensure_ascii=False, indent=2), []
    if audio_input is None:
        return json.dumps({"error": "์Œ์„ฑ์„ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”."}, ensure_ascii=False, indent=2), []
    if stt_model is None:
        return json.dumps({"error": "STT ๋ชจ๋ธ์ด ๋กœ๋“œ๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค."}, ensure_ascii=False, indent=2), []

    try:
        # filepath(str) vs numpy tuple ๋ถ„๊ธฐ
        if isinstance(audio_input, str):
            import soundfile as sf
            y, sr = sf.read(audio_input)
            y = y.astype(np.float32)
            if y.ndim > 1:       # ์Šคํ…Œ๋ ˆ์˜ค โ†’ ๋ชจ๋…ธ
                y = y.mean(axis=1)
        else:
            sr, y = audio_input  # ๋งˆ์ดํฌ numpy fallback
            y = y.astype(np.float32)

        if len(y) == 0:
            return json.dumps({"error": "์Œ์„ฑ์ด ๋„ˆ๋ฌด ์งง์Šต๋‹ˆ๋‹ค."}, ensure_ascii=False, indent=2), []

        max_v = np.max(np.abs(y))
        if max_v > 0:
            y = y / max_v

        stt_result = stt_model({"sampling_rate": sr, "raw": y})
        user_input = stt_result["text"].strip()

        if not user_input:
            return json.dumps({"error": "์Œ์„ฑ์ด ์ธ์‹๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค."}, ensure_ascii=False, indent=2), []

        t_scores = text_emotion_scores(user_input)
        a_scores = audio_emotion_scores(y, sr)         # โ† ์ปค์Šคํ…€ ๋ชจ๋ธ ์‚ฌ์šฉ
        top_label, combined = fused_emotion(t_scores, a_scores)
        books      = get_recommendations(user_input, top_label, top_n=3)
        books_json = _render_books_json(user_input, top_label, combined, books)

        return books_json, books

    except Exception as e:
        logger.error(f"์ฒ˜๋ฆฌ ์˜ค๋ฅ˜: {e}")
        return json.dumps({"error": str(e)}, ensure_ascii=False, indent=2), []


def run_analysis(audio):
    books_json, books = process_voice(audio)
    return books_json, books


# ============================================================
# Gradio UI
# ============================================================
with gr.Blocks(theme=gr.themes.Soft(), title="Boolook") as demo:
    gr.Markdown("""
    # Boolook โ€” ์Œ์„ฑ ๊ธฐ๋ฐ˜ ๊ฐ์ • ๋ถ„์„ ์ฑ… ์ถ”์ฒœ
    ๋‹น์‹ ์˜ ๊ฐ์ •์„ ๋ง๋กœ ํ‘œํ˜„ํ•˜๋ฉด, AI๊ฐ€ ๋”ฑ ๋งž๋Š” ์ฑ…์„ ์ถ”์ฒœํ•ด๋“œ๋ฆฝ๋‹ˆ๋‹ค.
    **์‚ฌ์šฉ๋ฒ•:** ๋งˆ์ดํฌ๋กœ ๊ฐ์ • ํ‘œํ˜„ โ†’ ๋ถ„์„ํ•˜๊ธฐ
    """)

    state_books = gr.State([])

    with gr.Row():
        with gr.Column(scale=1):
            gr.Markdown("### ์Œ์„ฑ ์ž…๋ ฅ")
            audio_in    = gr.Audio(
                sources=["microphone", "upload"],
                type="filepath",
                label="๋งˆ์ดํฌ ๋˜๋Š” ํŒŒ์ผ ์—…๋กœ๋“œ",
            )
            analyze_btn = gr.Button("๋ถ„์„ํ•˜๊ธฐ", variant="primary", size="lg")
            gr.Markdown("์˜ˆ: '์˜ค๋Š˜ ๋„ˆ๋ฌด ์Šฌํผ์š”', 'ํ–‰๋ณตํ•œ ๊ธฐ๋ถ„์ด์—์š”'")

        with gr.Column(scale=1):
            out_books_json = gr.Code(
                label="๋ถ„์„ ๊ฒฐ๊ณผ & ์ถ”์ฒœ ๋„์„œ",
                language="json",
                interactive=False,
            )

    with gr.Accordion("ํ†ต๊ณ„", open=False):
        stats_md    = gr.Markdown("์ƒˆ๋กœ๊ณ ์นจ์„ ๋ˆŒ๋Ÿฌ์ฃผ์„ธ์š”.")
        refresh_btn = gr.Button("ํ†ต๊ณ„ ์ƒˆ๋กœ๊ณ ์นจ")
        refresh_btn.click(fn=get_feedback_stats, outputs=stats_md)

    # ํ”ผ๋“œ๋ฐฑ API ์—”๋“œํฌ์ธํŠธ (ํด๋ผ์ด์–ธํŠธ ์ „์šฉ, UI ๋ฏธ๋…ธ์ถœ)
    with gr.Row(visible=False):
        fb_api_in  = gr.Textbox()
        fb_api_out = gr.Textbox()
        fb_api_btn = gr.Button()
        fb_api_btn.click(
            fn=api_feedback,
            inputs=fb_api_in,
            outputs=fb_api_out,
            api_name="feedback",
        )

    analyze_btn.click(
        fn=run_analysis,
        inputs=audio_in,
        outputs=[out_books_json, state_books],
    )

if __name__ == "__main__":
    demo.launch()