File size: 27,379 Bytes
29cd263
 
5fa5554
1f5d6fb
 
 
 
 
 
 
 
e19e3ff
cc83bd5
1f5d6fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9829399
 
 
 
 
 
 
94f9674
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b04e9c4
 
 
 
 
 
 
 
 
 
 
 
 
 
1f5d6fb
c73b270
 
 
 
 
1f5d6fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d6e07cc
1f5d6fb
 
 
 
 
 
 
 
 
 
 
 
 
 
875160b
1f5d6fb
 
 
 
 
 
 
 
 
 
 
29cd263
 
df71dac
 
29cd263
cf49ea6
 
 
 
 
29cd263
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e8fa0f1
1b19fcd
e8fa0f1
fd6482c
e8fa0f1
 
fd6482c
 
 
 
e8fa0f1
29cd263
 
e8fa0f1
29cd263
 
e8fa0f1
29cd263
21fa8e2
c73b270
29cd263
 
 
 
 
e8fa0f1
c73b270
29cd263
 
 
 
 
 
 
 
 
 
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
# gradio final ver ----------------------------

import torch
from torch import nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import Dataset, DataLoader
import gluonnlp as nlp
import numpy as np
from tqdm import tqdm, tqdm_notebook
import pandas as pd
import ast
import os

#  Hugging Face๋ฅผ ํ†ตํ•œ ๋ชจ๋ธ ๋ฐ ํ† ํฌ๋‚˜์ด์ € Import
from kobert_tokenizer import KoBERTTokenizer
from transformers import BertModel

from transformers import AdamW
from transformers.optimization import get_cosine_schedule_with_warmup

n_devices = torch.cuda.device_count()
print(n_devices)

for i in range(n_devices):
    print(torch.cuda.get_device_name(i))

if torch.cuda.is_available():
    device = torch.device("cuda")
    print('There are %d GPU(s) available.' % torch.cuda.device_count())
    print('We will use the GPU:', torch.cuda.get_device_name(0))
else:
    device = torch.device("cpu")
    print('No GPU available, using the CPU instead.')

max_len = 64
batch_size = 32
warmup_ratio = 0.1
num_epochs = 5
max_grad_norm = 1
log_interval = 200
learning_rate = 1e-5

class BERTSentenceTransform:
    r"""BERT style data transformation.

    Parameters
    ----------
    tokenizer : BERTTokenizer.
        Tokenizer for the sentences.
    max_seq_length : int.
        Maximum sequence length of the sentences.
    pad : bool, default True
        Whether to pad the sentences to maximum length.
    pair : bool, default True
        Whether to transform sentences or sentence pairs.
    """

    # ์ž…๋ ฅ์œผ๋กœ ๋ฐ›์€ tokenizerm ์ตœ๋Œ€ ์‹œํ€€์Šค ๊ธธ์ด, vocab, pad ๋ฐ pair ์„ค์ •
    def __init__(self, tokenizer, max_seq_length,vocab, pad=True, pair=True):
        self._tokenizer = tokenizer
        self._max_seq_length = max_seq_length
        self._pad = pad
        self._pair = pair
        self._vocab = vocab

    # ์ž…๋ ฅ๋œ ๋ฌธ์žฅ ๋˜๋Š” ๋ฌธ์žฅ ์Œ์„ BERT ๋ชจ๋ธ์ด ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋Š” ํ˜•์‹์œผ๋กœ ๋ณ€ํ™˜
    def __call__(self, line):
        """Perform transformation for sequence pairs or single sequences.

        The transformation is processed in the following steps:
        - tokenize the input sequences
        - insert [CLS], [SEP] as necessary
        - generate type ids to indicate whether a token belongs to the first
        sequence or the second sequence.
        - generate valid length

        For sequence pairs, the input is a tuple of 2 strings:
        text_a, text_b.

        Inputs:
            text_a: 'is this jacksonville ?'
            text_b: 'no it is not'
        Tokenization:
            text_a: 'is this jack ##son ##ville ?'
            text_b: 'no it is not .'
        Processed:
            tokens: '[CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]'
            type_ids: 0     0  0    0    0     0       0 0     1  1  1  1   1 1
            valid_length: 14

        For single sequences, the input is a tuple of single string:
        text_a.

        Inputs:
            text_a: 'the dog is hairy .'
        Tokenization:
            text_a: 'the dog is hairy .'
        Processed:
            text_a: '[CLS] the dog is hairy . [SEP]'
            type_ids: 0     0   0   0  0     0 0
            valid_length: 7

        Parameters
        ----------
        line: tuple of str
            Input strings. For sequence pairs, the input is a tuple of 2 strings:
            (text_a, text_b). For single sequences, the input is a tuple of single
            string: (text_a,).

        Returns
        -------
        np.array: input token ids in 'int32', shape (batch_size, seq_length)
        np.array: valid length in 'int32', shape (batch_size,)
        np.array: input token type ids in 'int32', shape (batch_size, seq_length)

        """

        # convert to unicode
        text_a = line[0]
        if self._pair:
            assert len(line) == 2
            text_b = line[1]

        tokens_a = self._tokenizer.tokenize(text_a)
        tokens_b = None

        if self._pair:
            tokens_b = self._tokenizer(text_b)

        if tokens_b:
            # Modifies `tokens_a` and `tokens_b` in place so that the total
            # length is less than the specified length.
            # Account for [CLS], [SEP], [SEP] with "- 3"
            self._truncate_seq_pair(tokens_a, tokens_b,
                                    self._max_seq_length - 3)
        else:
            # Account for [CLS] and [SEP] with "- 2"
            if len(tokens_a) > self._max_seq_length - 2:
                tokens_a = tokens_a[0:(self._max_seq_length - 2)]

        # The embedding vectors for `type=0` and `type=1` were learned during
        # pre-training and are added to the wordpiece embedding vector
        # (and position vector). This is not *strictly* necessary since
        # the [SEP] token unambiguously separates the sequences, but it makes
        # it easier for the model to learn the concept of sequences.

        # For classification tasks, the first vector (corresponding to [CLS]) is
        # used as as the "sentence vector". Note that this only makes sense because
        # the entire model is fine-tuned.
        #vocab = self._tokenizer.vocab
        vocab = self._vocab
        tokens = []
        tokens.append(vocab.cls_token)
        tokens.extend(tokens_a)
        tokens.append(vocab.sep_token)
        segment_ids = [0] * len(tokens)

        if tokens_b:
            tokens.extend(tokens_b)
            tokens.append(vocab.sep_token)
            segment_ids.extend([1] * (len(tokens) - len(segment_ids)))

        input_ids = self._tokenizer.convert_tokens_to_ids(tokens)

        # The valid length of sentences. Only real  tokens are attended to.
        valid_length = len(input_ids)

        if self._pad:
            # Zero-pad up to the sequence length.
            padding_length = self._max_seq_length - valid_length
            # use padding tokens for the rest
            input_ids.extend([vocab[vocab.padding_token]] * padding_length)
            segment_ids.extend([0] * padding_length)

        return np.array(input_ids, dtype='int32'), np.array(valid_length, dtype='int32'),\
            np.array(segment_ids, dtype='int32')

class BERTDataset(Dataset):
    def __init__(self, dataset, sent_idx, label_idx, bert_tokenizer, vocab, max_len,
                 pad, pair):
        transform = BERTSentenceTransform(bert_tokenizer, max_seq_length=max_len,vocab=vocab, pad=pad, pair=pair)
        #transform = nlp.data.BERTSentenceTransform(
        #    tokenizer, max_seq_length=max_len, pad=pad, pair=pair)
        self.sentences = [transform([i[sent_idx]]) for i in dataset]
        self.labels = [np.int32(i[label_idx]) for i in dataset]

    def __getitem__(self, i):
        return (self.sentences[i] + (self.labels[i], ))

    def __len__(self):
        return (len(self.labels))


tokenizer = KoBERTTokenizer.from_pretrained('skt/kobert-base-v1')
bertmodel = BertModel.from_pretrained('skt/kobert-base-v1', return_dict=False)
vocab = nlp.vocab.BERTVocab.from_sentencepiece(tokenizer.vocab_file, padding_token='[PAD]')

# Kobert_softmax
class BERTClassifier(nn.Module):
    def __init__(self,
                 bert,
                 hidden_size=768,
                 num_classes=6,
                 dr_rate=None,
                 params=None):
        super(BERTClassifier, self).__init__()
        self.bert = bert
        self.dr_rate = dr_rate
        self.softmax = nn.Softmax(dim=1)  # Softmax๋กœ ๋ณ€๊ฒฝ
        self.classifier = nn.Sequential(
            nn.Dropout(p=0.5),
            nn.Linear(in_features=hidden_size, out_features=512),
            nn.Linear(in_features=512, out_features=num_classes),
        )

        # ์ •๊ทœํ™” ๋ ˆ์ด์–ด ์ถ”๊ฐ€ (Layer Normalization)
        self.layer_norm = nn.LayerNorm(768)

        # ๋“œ๋กญ์•„์›ƒ
        self.dropout = nn.Dropout(p=dr_rate)

    def gen_attention_mask(self, token_ids, valid_length):
        attention_mask = torch.zeros_like(token_ids)
        for i, v in enumerate(valid_length):
            attention_mask[i][:v] = 1
        return attention_mask.float()

    def forward(self, token_ids, valid_length, segment_ids):
        attention_mask = self.gen_attention_mask(token_ids, valid_length)
        _, pooler = self.bert(input_ids=token_ids, token_type_ids=segment_ids.long(), attention_mask=attention_mask.float().to(token_ids.device))

        pooled_output = self.dropout(pooler)
        normalized_output = self.layer_norm(pooled_output)
        out = self.classifier(normalized_output)

        # LayerNorm ์ ์šฉ
        pooler = self.layer_norm(pooler)

        if self.dr_rate:
            pooler = self.dropout(pooler)

        logits = self.classifier(pooler)  # ๋ถ„๋ฅ˜๋ฅผ ์œ„ํ•œ ๋กœ์ง“ ๊ฐ’ ๊ณ„์‚ฐ
        probabilities = self.softmax(logits)  # Softmax๋กœ ๊ฐ ํด๋ž˜์Šค์˜ ํ™•๋ฅ  ๊ณ„์‚ฐ
        return probabilities  # ๊ฐ ํด๋ž˜์Šค์— ๋Œ€ํ•œ ํ™•๋ฅ  ๋ฐ˜ํ™˜


model = torch.load('./model_weights_softmax(model).pth', map_location=torch.device('cpu'))
model.eval()

# ๋ฉœ๋ก  ๋ฐ์ดํ„ฐ ๋ถˆ๋Ÿฌ์˜ค๊ธฐ 

melon_data = pd.read_csv('./melon_data.csv')
melon_emotions = pd.read_csv('./melon_emotions_final.csv')
melon_emotions = pd.merge(melon_emotions, melon_data, left_on='Title', right_on='title', how='inner')
melon_emotions = melon_emotions[['singer', 'Title', 'genre','Emotions']]
melon_emotions = melon_emotions.drop_duplicates(subset='Title', keep='first')
melon_emotions['Emotions'] = melon_emotions['Emotions'].apply(lambda x: ast.literal_eval(x))

emotions = melon_emotions['Emotions'].to_list()

#gradio

import numpy as np
import pandas as pd
import requests
from PIL import Image
import torch
from transformers import AutoProcessor, AutoModelForZeroShotImageClassification, pipeline
import gradio as gr
import openai
from sklearn.metrics.pairwise import cosine_similarity
import ast

###### ๊ธฐ๋ณธ ์„ค์ • ######
# OpenAI API ํ‚ค ์„ค์ •
api_key = os.getenv("OPEN_AI_KEY")
openai.api_key = api_key

if openai.api_key:
    print("Private Key:", openai.api_key)
else:
    print("Private Key not set.")
    
# ๋ชจ๋ธ ๋ฐ ํ”„๋กœ์„ธ์„œ ๋กœ๋“œ
processor = AutoProcessor.from_pretrained("openai/clip-vit-large-patch14")
model_clip = AutoModelForZeroShotImageClassification.from_pretrained("openai/clip-vit-large-patch14")
tokenizer = KoBERTTokenizer.from_pretrained('skt/kobert-base-v1')

# ์˜ˆ์ธก ๋ ˆ์ด๋ธ”
labels = ['a photo of a happy face', 'a photo of a joyful face', 'a photo of a loving face',
          'a photo of an angry face', 'a photo of a melancholic face', 'a photo of a lonely face']

###### ์–ผ๊ตด ๊ฐ์ • ๋ฒกํ„ฐ ์˜ˆ์ธก ํ•จ์ˆ˜ ######
def predict_face_emotion(image):
    # ์ด๋ฏธ์ง€๊ฐ€ None์ด๊ฑฐ๋‚˜ ์ž˜๋ชป๋œ ๊ฒฝ์šฐ
    if image is None:
        return np.zeros(len(labels))  # ๋นˆ ๋ฒกํ„ฐ ๋ฐ˜ํ™˜

    # PIL ์ด๋ฏธ์ง€๋ฅผ RGB๋กœ ๋ณ€ํ™˜
    image = image.convert("RGB")

    # CLIP ๋ชจ๋ธ์˜ processor๋ฅผ ์ด์šฉํ•œ ์ „์ฒ˜๋ฆฌ
    inputs = processor(text=labels, images=image, return_tensors="pt", padding=True)

    # pixel_values๊ฐ€ 4์ฐจ์›์ธ์ง€ ํ™•์ธ ํ›„ ๊ฐ•์ œ ๋ณ€ํ™˜
    pixel_values = inputs["pixel_values"]  # (batch_size, channels, height, width)

    # CLIP ๋ชจ๋ธ ์˜ˆ์ธก: forward์— ์˜ฌ๋ฐ”๋ฅธ ์ž…๋ ฅ ์ „๋‹ฌ
    with torch.no_grad():
        outputs = model_clip(pixel_values=pixel_values, input_ids=inputs["input_ids"])

    # ํ™•๋ฅ ๊ฐ’ ๊ณ„์‚ฐ
    probs = outputs.logits_per_image.softmax(dim=1)[0]
    return probs.numpy()

###### ํ…์ŠคํŠธ ๊ฐ์ • ๋ฒกํ„ฐ ์˜ˆ์ธก ํ•จ์ˆ˜ ######
sentence_emotions = []

def predict_text_emotion(predict_sentence):

    if not isinstance(predict_sentence, str):
        predict_sentence = str(predict_sentence)

    data = [predict_sentence, '0']
    dataset_another = [data]

    another_test = BERTDataset(dataset_another, 0, 1, tokenizer, vocab, max_len, True, False)
    test_dataloader = torch.utils.data.DataLoader(another_test, batch_size=1, num_workers=5)

    model.eval()

    for batch_id, (token_ids, valid_length, segment_ids, label) in enumerate(test_dataloader):
        token_ids = token_ids.long().to(device)
        segment_ids = segment_ids.long().to(device)

        out = model(token_ids, valid_length, segment_ids)
        for i in out:
            logits = i.detach().cpu().numpy()
            emotions = [value.item() for value in i]
            sentence_emotions.append(emotions)
    return sentence_emotions[0]  # ์ตœ์ข… ๋ฆฌ์ŠคํŠธ ๋ฐ˜ํ™˜

###### ์ตœ์ข… ๊ฐ์ • ๋ฒกํ„ฐ ๊ณ„์‚ฐ ######
def generate_final_emotion_vector(diary_input, image_input):
    # ํ…์ŠคํŠธ ๊ฐ์ • ๋ฒกํ„ฐ ์˜ˆ์ธก
    text_vector = predict_text_emotion(diary_input)
    # ์–ผ๊ตด ๊ฐ์ • ๋ฒกํ„ฐ ์˜ˆ์ธก
    image_vector = predict_face_emotion(image_input)
    text_vector = np.array(text_vector, dtype=float)
    image_vector = np.array(image_vector, dtype=float)

    print(text_vector)
    print(image_vector)

    # ์ตœ์ข… ๊ฐ์ • ๋ฒกํ„ฐ ๊ฐ€์ค‘์น˜ ์ ์šฉ
    return (text_vector * 0.7) + (image_vector * 0.3)

####### ์ฝ”์‚ฌ์ธ ์œ ์‚ฌ๋„ ํ•จ์ˆ˜ ######
def cosine_similarity_fn(vec1, vec2):
    dot_product = np.dot(vec1, vec2)
    norm_vec1 = np.linalg.norm(vec1)
    norm_vec2 = np.linalg.norm(vec2)
    if norm_vec1 == 0 or norm_vec2 == 0:
        return np.nan  # ์ œ๋กœ ๋ฒกํ„ฐ์ธ ๊ฒฝ์šฐ NaN ๋ฐ˜ํ™˜
    return dot_product / (norm_vec1 * norm_vec2)


####### ์ด๋ฏธ์ง€ ๋‹ค์šด๋กœ๋“œ ํ•จ์ˆ˜ (PIL ๊ฐ์ฒด ๋ฐ˜ํ™˜) ######
def download_image(image_url):
    try:
        response = requests.get(image_url)
        response.raise_for_status()
        return Image.open(requests.get(image_url, stream=True).raw)
    except Exception as e:
        print(f"์ด๋ฏธ์ง€ ๋‹ค์šด๋กœ๋“œ ์˜ค๋ฅ˜: {e}")
        return None

# ์Šคํƒ€์ผ ์˜ต์…˜
options = {
    1: "๐ŸŒผ ์นœ๊ทผํ•œ",
    2: "๐Ÿ”ฅ ํŠธ๋ Œ๋””ํ•œ MZ์„ธ๋Œ€",
    3: "๐Ÿ˜„ ์œ ๋จธ๋Ÿฌ์Šคํ•œ ์žฅ๋‚œ๊พธ๋Ÿฌ๊ธฐ",
    4: "๐Ÿง˜ ์ฐจ๋ถ„ํ•œ ๋ช…์ƒ๊ฐ€",
    5: "๐ŸŽจ ์ฐฝ์˜์ ์ธ ์˜ˆ์ˆ ๊ฐ€",
}

# ์ผ๊ธฐ ๋ถ„์„ ํ•จ์ˆ˜
def chatbot_diary_with_image(style_option, diary_input, image_input, playlist_input):

    style = options.get(int(style_option.split('.')[0]), "๐ŸŒผ ์นœ๊ทผํ•œ")

    # GPT ์‘๋‹ต (์ผ๊ธฐ ์ฝ”๋ฉ˜ํŠธ)
    try:
        response_comment = openai.ChatCompletion.create(
            model="gpt-4-turbo",
            messages=[{"role": "system", "content": f"๋„ˆ๋Š” {style} ์ฑ—๋ด‡์ด์•ผ."}, {"role": "user", "content": diary_input}],
        )
        comment = response_comment.choices[0].message.content
    except Exception as e:
        comment = f"๐Ÿ’ฌ ์˜ค๋ฅ˜: {e}"

    # GPT ๊ธฐ๋ฐ˜ ์ผ๊ธฐ ์ฃผ์ œ ์ถ”์ฒœ
    try:
        topics = get_initial_response(style_option, diary_input)
    except Exception as e:
        topics = f"๐Ÿ“ ์ฃผ์ œ ์ถ”์ฒœ ์˜ค๋ฅ˜: {e}"

    # DALLยทE 3 ์ด๋ฏธ์ง€ ์ƒ์„ฑ ์š”์ฒญ (3D ์Šคํƒ€์ผ ์บ๋ฆญํ„ฐ)
    try:
        response = openai.Image.create(
            model="dall-e-3",
            prompt=(
                  f"{diary_input}๋ฅผ ๋ฐ˜์˜ํ•ด์„œ ๊ฐ์ •์„ ํ‘œํ˜„ํ•˜๋Š” 3D ์Šคํƒ€์ผ์˜ ์ผ๋Ÿฌ์ŠคํŠธ ์บ๋ฆญํ„ฐ๋ฅผ ๊ทธ๋ ค์ค˜. "
                  "์บ๋ฆญํ„ฐ๋Š” ๋ถ€๋“œ๋Ÿฝ๊ณ  ๋‘ฅ๊ทผ ๋””์ž์ธ์— ํ‘œ์ •์ด ๊ฐ์ •์„ ์ž˜ ๋“œ๋Ÿฌ๋‚ด์•ผ ํ•ด. "
                  "๊ฐ์ •์„ ์‹œ๊ฐ์ ์œผ๋กœ ํ‘œํ˜„ํ•  ์ˆ˜ ์žˆ๋Š” ์†Œํ’ˆ์ด๋‚˜ ์ž‘์€ ์ƒ์ง•์„ ํฌํ•จํ•ด์ค˜. "
                  "๊ฐ์ •์˜ ๋ถ„์œ„๊ธฐ๋ฅผ ๋ฐ˜์˜ํ•˜๋Š” ์„ ๋ช…ํ•˜๊ณ  ๊นจ๋—ํ•œ ์ƒ‰์ƒ์„ ์‚ฌ์šฉํ•˜๊ณ , ์บ๋ฆญํ„ฐ๊ฐ€ ์—ญ๋™์ ์ด๊ณ  ์žฌ๋ฏธ์žˆ๋Š” ์ž์„ธ๋ฅผ ์ทจํ•  ์ˆ˜ ์žˆ๋„๋ก ํ•ด์ค˜. "
                  "์ด๋ฏธ์ง€์—๋Š” ํ•˜๋‚˜์˜ ์บ๋ฆญํ„ฐ๋งŒ ๋‚˜์˜ค๊ฒŒ ํ•ด์ค˜."
                  "๋ฐฐ๊ฒฝ์€ ๋‹จ์ˆœํ•˜๊ณ  ๋ฐ์€ ์ƒ‰์ƒ์œผ๋กœ ์„ค์ •ํ•ด์„œ ์บ๋ฆญํ„ฐ๊ฐ€ ๊ฐ•์กฐ๋  ์ˆ˜ ์žˆ๋„๋ก ํ•ด์ค˜."
            ),
            size="1024x1024",
            n=1
        )
        # URL ๊ฐ€์ ธ์˜ค๊ธฐ ๋ฐ ๋‹ค์šด๋กœ๋“œ
        image_url = response['data'][0]['url']
        print(f"Generated Image URL: {image_url}")  # URL ํ™•์ธ
        image = download_image(image_url)
    except Exception as e:
        print(f"์ด๋ฏธ์ง€ ์ƒ์„ฑ ์˜ค๋ฅ˜: {e}")  # ์˜ค๋ฅ˜ ์ƒ์„ธ ์ถœ๋ ฅ
        image = None

    # ์‚ฌ์šฉ์ž ์ตœ์ข… ๊ฐ์ • ๋ฒกํ„ฐ
    final_user_emotions = generate_final_emotion_vector(diary_input,image_input)

    # ๊ฐ ๋…ธ๋ž˜์— ๋Œ€ํ•œ ์ฝ”์‚ฌ์ธ ์œ ์‚ฌ๋„ ๊ณ„์‚ฐ
    similarities = [cosine_similarity_fn(final_user_emotions, song_vec) for song_vec in emotions]

    #์œ ํšจํ•œ ์œ ์‚ฌ๋„ ํ•„ํ„ฐ๋ง
    valid_indices = [i for i, sim in enumerate(similarities) if not np.isnan(sim)]
    filtered_similarities = [similarities[i] for i in valid_indices]

    recommendations = np.argsort(filtered_similarities)[::-1]  # ๋†’์€ ์œ ์‚ฌ๋„ ์ˆœ์œผ๋กœ ์ •๋ ฌ
    results_df = pd.DataFrame({
    'Singer' : melon_emotions['singer'].iloc[recommendations].values,
    'title' : melon_emotions['Title'].iloc[recommendations].values,
    'genre' : melon_emotions['genre'].iloc[recommendations].values,
    'Cosine Similarity': [similarities[idx] for idx in recommendations]
    })

    # ๊ฐ€์ค‘์น˜ ๊ฐ’ ์„ค์ •
    gamma = 0.3

    similar_playlists = results_df.head(5)
    similar_playlists = pd.merge(similar_playlists, melon_emotions, left_on="title", right_on="Title", how="inner")
    similar_playlists = similar_playlists[["title", "Emotions", "singer"]]

    dissimilar_playlists = results_df.tail(5)
    dissimilar_playlists = pd.merge(dissimilar_playlists, melon_emotions, left_on="title", right_on="Title", how="inner")
    dissimilar_playlists = dissimilar_playlists[["title", "Emotions", "singer"]]

    #๊ฐ์ •๊ณผ ์œ ์‚ฌํ•œ ํ”Œ๋ ˆ์ด๋ฆฌ์ŠคํŠธ
    if playlist_input == '๋น„์Šทํ•œ':
      results = []
      seen_songs = set(similar_playlists["title"].values)  # ์ดˆ๊ธฐ seen_songs์— similar_playlists์˜ ๊ณก๋“ค์„ ์ถ”๊ฐ€

      # ์‚ฌ์šฉ์ž ๊ฐ์ • ๋ฒกํ„ฐ
      user_emotion_vector = generate_final_emotion_vector(diary_input, image_input).reshape(1, -1)

      for index, row in similar_playlists.iterrows():
          song_title = row["title"]
          song_singer = row["singer"]
          song_vector = np.array(row["Emotions"]).reshape(1, -1)

          song_results = []
          for i, emotion_vec in enumerate(emotions):
              emotion_title = melon_emotions.iloc[i]["Title"]
              emotion_singer = melon_emotions.iloc[i]["singer"]
              emotion_vec = np.array(emotion_vec).reshape(1, -1)

              # similar_playlists์— ์žˆ๋Š” ๊ณก๊ณผ seen_songs์— ์žˆ๋Š” ๊ณก์€ ์ œ์™ธ
              if (
                  emotion_title != song_title and
                  emotion_title not in seen_songs
              ):
                  try:
                      # ๊ณก ๊ฐ„ ์œ ์‚ฌ๋„(Song-Song Similarity)
                      song_song_similarity = cosine_similarity(song_vector, emotion_vec)[0][0]

                      # ์‚ฌ์šฉ์ž ๊ฐ์ • ๋ฒกํ„ฐ์™€์˜ ์œ ์‚ฌ๋„(User-Song Similarity)
                      user_song_similarity = cosine_similarity(user_emotion_vector, emotion_vec)[0][0]

                      # Final Score ๊ณ„์‚ฐ
                      final_score = gamma * song_song_similarity + (1 - gamma) * user_song_similarity

                      song_results.append({
                          "Title": emotion_title,
                          "Singer": emotion_singer,
                          "Song-Song Similarity": song_song_similarity,
                          "User-Song Similarity": user_song_similarity,
                          "Final Score": final_score
                      })
                  except ValueError as e:
                      print(f"Error with {song_title} vs {emotion_title}: {e}")
                      continue

          # Final Score๋ฅผ ๊ธฐ์ค€์œผ๋กœ ์ƒ์œ„ 3๊ณก ์„ ํƒ
          song_results = sorted(song_results, key=lambda x: x["Final Score"], reverse=True)[:3]
          seen_songs.update([entry["Title"] for entry in song_results])

          results.append({"Song Title": song_title, "Singer": song_singer, "Top 3 Similarities": song_results})

      # ๊ฒฐ๊ณผ ์ถœ๋ ฅ
      for result in results:
          print(f"{result['Singer']} - {result['Song Title']}")
          for entry in result["Top 3 Similarities"]:
              print(f"{entry['Singer']} - {entry['Title']} : Final Score {entry['Final Score']:.4f}")
              print(f"  (Song-Song Similarity: {entry['Song-Song Similarity']:.4f}, User-Song Similarity: {entry['User-Song Similarity']:.4f})")
          print("-" * 30)

    #๋ฐ˜๋Œ€ ํ”Œ๋ ˆ์ด๋ฆฌ์ŠคํŠธ
    if playlist_input == '์ƒ๋ฐ˜๋œ':
      results = []
      seen_songs = set()

      # ์‚ฌ์šฉ์ž ๊ฐ์ • ๋ฒกํ„ฐ
      user_emotion_vector = generate_final_emotion_vector(diary_input, image_input).reshape(1, -1)

      for index, row in dissimilar_playlists.iterrows():
          song_title = row["title"]
          song_singer = row["singer"]
          song_vector = np.array(row["Emotions"]).reshape(1, -1)

          song_results = []
          for i, emotion_vec in enumerate(emotions):
              emotion_title = melon_emotions.iloc[i]["Title"]
              emotion_singer = melon_emotions.iloc[i]["singer"]
              emotion_vec = np.array(emotion_vec).reshape(1, -1)

              if (
                  emotion_title != song_title and
                  emotion_title not in dissimilar_playlists["title"].values and
                  emotion_title not in seen_songs
              ):
                  try:
                      # ๊ณก ๊ฐ„ ์œ ์‚ฌ๋„(Song-Song Similarity)
                      song_song_similarity = cosine_similarity(song_vector, emotion_vec)[0][0]

                      # ์‚ฌ์šฉ์ž ๊ฐ์ • ๋ฒกํ„ฐ์™€์˜ ๋ฐ˜๋Œ€ ์œ ์‚ฌ๋„(User-Song Dissimilarity)
                      opposite_user_song_similarity = 1 - cosine_similarity(user_emotion_vector, emotion_vec)[0][0]

                      # Final Score ๊ณ„์‚ฐ
                      final_score = gamma * song_song_similarity + (1 - gamma) * opposite_user_song_similarity

                      song_results.append({
                          "Title": emotion_title,
                          "Singer": emotion_singer,
                          "Song-Song Similarity": song_song_similarity,
                          "User-Song Dissimilarity": opposite_user_song_similarity,
                          "Final Score": final_score
                      })
                  except ValueError as e:
                      print(f"Error with {song_title} vs {emotion_title}: {e}")
                      continue

          # Final Score๋ฅผ ๊ธฐ์ค€์œผ๋กœ ์ƒ์œ„ 3๊ณก ์„ ํƒ (๊ฐ’์ด ํฐ ๊ณก์ด ๋ฐ˜๋Œ€๋˜๋Š” ๊ณก)
          song_results = sorted(song_results, key=lambda x: x["Final Score"], reverse=True)[:3]
          seen_songs.update(entry["Title"] for entry in song_results)

          results.append({"Song Title": song_title, "Singer": song_singer, "Top 3 Similarities": song_results})

      # ๊ฒฐ๊ณผ ์ถœ๋ ฅ
      for result in results:
          print(f"{result['Singer']} - {result['Song Title']}")
          for entry in result["Top 3 Similarities"]:
              print(f"{entry['Singer']} - {entry['Title']} : Final Score {entry['Final Score']:.4f}")
              print(f'  (Song-Song Similarity: {entry["Song-Song Similarity"]:.4f}, User-Song Dissimilarity: {entry["User-Song Dissimilarity"]:.4f})')
          print("-" * 30)
    # ๋ฐ์ดํ„ฐํ”„๋ ˆ์ž„ ๋ณ€ํ™˜์„ ์œ„ํ•œ ๋ฆฌ์ŠคํŠธ ์ƒ์„ฑ
    df_rows = []

    for result in results:
        song_title = result['Song Title']
        song_singer = result['Singer']
        main_song_info = f"{song_singer} - {song_title}"

        for entry in result["Top 3 Similarities"]:
            combined_info = f"{entry['Singer']} - {entry['Title']}"
            df_rows.append({"1st ์ถ”์ฒœ ํ”Œ๋ ˆ์ด๋ฆฌ์ŠคํŠธ": main_song_info, "2nd ์ถ”์ฒœ ํ”Œ๋ ˆ์ด๋ฆฌ์ŠคํŠธ": combined_info})

    # ๋ฐ์ดํ„ฐํ”„๋ ˆ์ž„ ์ƒ์„ฑ
    final_music_playlist_recommendation = pd.DataFrame(df_rows)

    # ๊ณก ์ œ๋ชฉ ๊ทธ๋ฃนํ™”ํ•˜์—ฌ ์ฒซ ๋ฒˆ์งธ ํ–‰์—๋งŒ ๊ณก ์ œ๋ชฉ ํ‘œ์‹œ
    final_music_playlist_recommendation["1st ์ถ”์ฒœ ํ”Œ๋ ˆ์ด๋ฆฌ์ŠคํŠธ"] = final_music_playlist_recommendation.groupby("1st ์ถ”์ฒœ ํ”Œ๋ ˆ์ด๋ฆฌ์ŠคํŠธ")["1st ์ถ”์ฒœ ํ”Œ๋ ˆ์ด๋ฆฌ์ŠคํŠธ"].transform(
        lambda x: [x.iloc[0]] + [""] * (len(x) - 1)
    )

    return final_music_playlist_recommendation, comment, topics, image

# ์ผ๊ธฐ ์ฃผ์ œ ์ถ”์ฒœ ํ•จ์ˆ˜
def get_initial_response(style, sentence):
    style = options.get(int(style.split('.')[0]), "๐ŸŒผ ์นœ๊ทผํ•œ")
    system_prompt_momentum = (
        f"๋„ˆ๋Š” {style}์˜ ์ฑ—๋ด‡์ด์•ผ. ์‚ฌ์šฉ์ž๊ฐ€ ์ž‘์„ฑํ•œ ์ผ๊ธฐ๋ฅผ ๋ฐ”ํƒ•์œผ๋กœ ์ƒ๊ฐ์„ ์ •๋ฆฌํ•˜๊ณ  ๋‚ด๋ฉด์„ ๋Œ์•„๋ณผ ์ˆ˜ ์žˆ๋„๋ก "
        "๋„์™€์ฃผ๋Š” ๊ตฌ์ฒด์ ์ธ ์ผ๊ธฐ ์ฝ˜ํ…์ธ ๋‚˜ ์งˆ๋ฌธ 4-5๊ฐœ๋ฅผ ์ถ”์ฒœํ•ด์ค˜."
    )
    try:
        response = openai.ChatCompletion.create(
            model="gpt-4-turbo",
            messages=[
                {"role": "system", "content": system_prompt_momentum},
                {"role": "user", "content": sentence}
            ],
            temperature=1
        )
        return response.choices[0].message.content
    except Exception as e:
        return f"๐Ÿ“ ์ฃผ์ œ ์ถ”์ฒœ ์˜ค๋ฅ˜: {e}"

# Gradio ์ธํ„ฐํŽ˜์ด์Šค
with gr.Blocks() as app:
    gr.Markdown("""
        # ๐Ÿ“š EmoDiary : ์Šค๋งˆํŠธ ๊ฐ์ • ์ผ๊ธฐ ๋„์šฐ๋ฏธ ๐Ÿ“š
        
        **์˜ค๋Š˜์˜ ํ•˜๋ฃจ๋ฅผ ๊ธฐ๋กํ•˜๋ฉด, ๊ทธ์— ๋งž๋Š” ํ”Œ๋ ˆ์ด๋ฆฌ์ŠคํŠธ์™€ ์ผ๊ธฐ ํšŒ๊ณ  ์ฝ˜ํ…์ธ ๋ฅผ ์ž๋™์œผ๋กœ ์ƒ์„ฑํ•ด๋“œ๋ฆฝ๋‹ˆ๋‹ค!**
        
        ### ์‚ฌ์šฉ ๋ฐฉ๋ฒ•:
        1. ์˜ค๋Š˜์˜ ํ•˜๋ฃจ ๊ธฐ๋กํ•˜๊ธฐ: ํ•˜๋ฃจ ๋™์•ˆ์˜ ๊ฐ์ •์ด๋‚˜ ์ผ์–ด๋‚œ ์ผ์„ ํ…์ŠคํŠธ ๋ฐ•์Šค์— ๊ธฐ๋กํ•˜๊ณ , ์ž์‹ ์˜ ๊ฐ์ •์„ ๋ฐ˜์˜ํ•  ์ˆ˜ ์žˆ๋Š” ์–ผ๊ตด ํ‘œ์ • ์ด๋ฏธ์ง€๋ฅผ ์ดฌ์˜ํ•ด์ฃผ์„ธ์š”. 
        2. AI ์Šคํƒ€์ผ ์„ ํƒํ•˜๊ธฐ: ์ž์‹ ์˜ ์„ ํ˜ธ์— ๋งž๋Š” ์Šคํƒ€์ผ์„ ์„ ํƒํ•˜๋ฉด, ํ•ด๋‹น ์Šคํƒ€์ผ์— ๋งž์ถ˜ ๋‹ต์žฅ๊ณผ ํšŒ๊ณ  ์ฃผ์ œ๋ฅผ ์ถ”์ฒœํ•ด๋“œ๋ฆด๊ฒŒ์š”.
        3. ํ”Œ๋ ˆ์ด๋ฆฌ์ŠคํŠธ ์„ ํƒํ•˜๊ธฐ: ์˜ค๋Š˜์˜ ๊ฐ์ •์— ๋งž์ถฐ "๋น„์Šทํ•œ" ๋˜๋Š” "์ƒ๋ฐ˜๋œ" ๊ฐ์ •์„ ์„ ํƒํ•˜๋ฉด, ๊ทธ์— ๋งž๋Š” ํ”Œ๋ ˆ์ด๋ฆฌ์ŠคํŠธ๋ฅผ ์ถ”์ฒœํ•ด๋“œ๋ฆด๊ฒŒ์š”. 
        4. ๋ถ„์„ ์‹œ์ž‘: "๐Ÿš€ ๋ถ„์„ ์‹œ์ž‘" ๋ฒ„ํŠผ์„ ํด๋ฆญํ•˜๋ฉด, ์ž…๋ ฅํ•œ ์ •๋ณด์™€ ์ด๋ฏธ์ง€๋ฅผ ๋ฐ”ํƒ•์œผ๋กœ ์ถ”์ฒœ ํ”Œ๋ ˆ์ด๋ฆฌ์ŠคํŠธ, ๊ฐ์ • ์บ๋ฆญํ„ฐ ์ด๋ฏธ์ง€, ๊ทธ๋ฆฌ๊ณ  ํšŒ๊ณ  ์ฃผ์ œ๊ฐ€ ์ƒ์„ฑ๋ฉ๋‹ˆ๋‹ค.""")
    
    with gr.Row():
        with gr.Column():
            diary_input = gr.Textbox(label="๐Ÿ“œ ์˜ค๋Š˜ ํ•˜๋ฃจ ๊ธฐ๋กํ•˜๊ธฐ", placeholder="ex)์˜ค๋Š˜ ์†Œํ’๊ฐ€์„œ ๋ง›์žˆ๋Š” ๊ฑธ ๋งŽ์ด ๋จน์–ด์„œ ์—„์ฒญ ์‹ ๋‚ฌ์–ด")
            chatbot_style = gr.Radio(
                choices=[f"{k}. {v}" for k, v in options.items()],
                label="๐Ÿค– ์–ด๋–ค ์Šคํƒ€์ผ์˜ AI์—๊ฒŒ ๋‹ต์žฅ๊ณผ ํšŒ๊ณ  ์ฃผ์ œ๋ฅผ ์ถ”์ฒœ๋ฐ›๊ณ  ์‹ถ๋‚˜์š”?"
            )
            playlist_input = gr.Radio(["๋น„์Šทํ•œ", "์ƒ๋ฐ˜๋œ"], label="๐ŸŽง ์˜ค๋Š˜์˜ ๊ฐ์ •๊ณผ ใ…‡ใ…‡๋˜๋Š” ํ”Œ๋ ˆ์ด๋ฆฌ์ŠคํŠธ๋ฅผ ์ถ”์ฒœ๋ฐ›๊ณ  ์‹ถ๋‚˜์š”?")
            image_input = gr.Image(type="pil", label="๐Ÿ“ท ์–ผ๊ตด ํ‘œ์ • ์‚ฌ์ง„ ์—…๋กœ๋“œ", width=256, height=256)
            submit_btn = gr.Button("๐Ÿš€ ๋ถ„์„ ์‹œ์ž‘")

        with gr.Column():
            output_playlist = gr.Dataframe(label="๐ŸŽง ์ถ”์ฒœ ํ”Œ๋ ˆ์ด๋ฆฌ์ŠคํŠธ ")
            output_comment = gr.Textbox(label="๐Ÿ’ฌ AI ์ฝ”๋ฉ˜ํŠธ")
            output_topics = gr.Textbox(label="๐Ÿ“ ์˜ค๋Š˜์˜ ๋‚ด๋ฉด์„ ๋Œ์•„๋ณด๋Š” ํšŒ๊ณ  ์ถ”์ฒœ ์ฃผ์ œ")
            output_image = gr.Image(label="๐Ÿ–ผ๏ธ ์ƒ์„ฑ๋œ ์˜ค๋Š˜์˜ ๊ฐ์ • ์บ๋ฆญํ„ฐ", type="pil", width=256, height=256)

    # ๋ฒ„ํŠผ ํด๋ฆญ ์ด๋ฒคํŠธ ์—ฐ๊ฒฐ
    submit_btn.click(
        fn=chatbot_diary_with_image,
        inputs=[chatbot_style, diary_input, image_input, playlist_input],
        outputs=[output_playlist, output_comment, output_topics, output_image]
    )

# ์•ฑ ์‹คํ–‰
app.launch(debug=True)