File size: 18,600 Bytes
e305037
 
 
 
 
 
47cdaac
 
444646a
e305037
58e531c
 
 
e305037
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47cdaac
e305037
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92a16ab
 
d800097
 
e305037
92a16ab
d800097
e305037
 
d800097
92a16ab
d800097
68b8998
d800097
68b8998
d800097
68b8998
d800097
 
 
 
444646a
 
 
d800097
 
 
 
 
 
 
 
 
 
444646a
d800097
7d55c2c
d800097
 
 
 
e305037
 
f3888c4
 
 
68b8998
f3888c4
328f8ed
f3888c4
e305037
 
 
 
47cdaac
444646a
e305037
 
6d0d3a0
d800097
e305037
f3888c4
e305037
a340c2b
1c7d87d
 
a340c2b
e305037
6d0d3a0
 
 
 
 
 
 
 
 
e305037
 
 
 
328f8ed
e305037
 
 
6d0d3a0
e305037
 
 
 
 
 
 
 
6d0d3a0
e305037
 
 
6d0d3a0
ef52230
e305037
328f8ed
 
 
 
 
 
 
 
 
 
 
 
e305037
 
 
 
40f7200
f3888c4
 
 
2f583f9
f3888c4
 
 
ef52230
47cdaac
 
ef52230
 
 
 
 
 
 
 
 
 
 
 
 
 
2f583f9
7d55c2c
47cdaac
7d55c2c
47cdaac
 
ef52230
 
47cdaac
 
 
 
ef52230
 
 
 
 
 
 
 
 
 
 
47cdaac
 
 
 
 
ef52230
47cdaac
ef52230
47cdaac
 
 
 
ef52230
7d55c2c
ef52230
 
 
 
 
e305037
6b6279a
 
 
 
 
e305037
 
 
a340c2b
 
e305037
a340c2b
 
 
 
 
 
 
 
 
 
 
 
e305037
a340c2b
 
e305037
328f8ed
a340c2b
e305037
 
 
 
 
 
1c7d87d
e305037
47cdaac
 
ef52230
47cdaac
ef52230
 
 
 
 
 
 
 
 
 
7d55c2c
47cdaac
ef52230
e305037
ef52230
47cdaac
 
4ba10b8
f3888c4
 
2f583f9
 
 
 
328f8ed
2f583f9
f3888c4
 
 
ef52230
 
 
92a16ab
 
 
 
 
 
 
 
ef52230
 
 
 
 
 
f3888c4
 
 
328f8ed
f3888c4
92a16ab
 
 
 
 
 
 
 
f3888c4
6d0d3a0
f3888c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92a16ab
f3888c4
 
92a16ab
f3888c4
 
 
 
92a16ab
f3888c4
e305037
ef52230
 
92a16ab
ef52230
 
e305037
 
c3b9c5a
 
 
6020c2c
 
c3b9c5a
 
 
 
e27adae
 
40f7200
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
import gradio as gr
import librosa
import numpy as np
import torch
import os
import json
import base64
import tempfile
import soundfile as sf
from datetime import datetime

from speechbrain.inference import EncoderClassifier
from huggingface_hub import login
from datasets import load_dataset, Dataset

# 1. ์ดˆ๊ธฐ ์„ธํŒ… ๋ฐ ํ† ํฐ ๋กœ๊ทธ์ธ
HF_TOKEN = os.environ.get("HF_TOKEN")
if HF_TOKEN:
    login(token=HF_TOKEN)

DATASET_REPO = "easyadaptor/Voice-Matcher-DB"

# 2. ํ™”์ž ์ž„๋ฒ ๋”ฉ ๋ชจ๋ธ ๋กœ๋“œ (SpeechBrain)
classifier = EncoderClassifier.from_hparams(
    source="speechbrain/spkrec-ecapa-voxceleb", 
    savedir="pretrained_models/spkrec-ecapa-voxceleb"
)

# 3. ์˜ค๋””์˜ค ํŠน์„ฑ ์ž๋™ ์ถ”์ถœ ํ•จ์ˆ˜
def extract_audio_features(file_path):
    y, sr = librosa.load(file_path, sr=16000)
    onset_env = librosa.onset.onset_strength(y=y, sr=sr)
    tempo, _ = librosa.beat.beat_track(onset_envelope=onset_env, sr=sr)
    pitches, _ = librosa.piptrack(y=y, sr=sr)
    mean_pitch = np.mean(pitches[pitches > 0]) if np.any(pitches > 0) else 0

    tags =[]
    if mean_pitch > 200: tags.append("์ฒญ์•„ํ•œ ๊ณ ์Œ")
    elif mean_pitch < 120: tags.append("๋ฌต์งํ•œ ์ €์Œ")
    else: tags.append("์•ˆ์ •์ ์ธ ์ค‘์Œ")
    
    if tempo > 130: tags.append("๋น ๋ฅด๊ณ  ๊ฒฝ์พŒํ•œ ํ…œํฌ")
    elif tempo < 100: tags.append("์ฐจ๋ถ„ํ•˜๊ณ  ๋А๋ฆฐ ํ…œํฌ")
    else: tags.append("์ ๋‹นํ•œ ํ…œํฌ")
    
    return tags

# 4.[๊ด€๋ฆฌ์ž์šฉ] ๋‹ค์ค‘ ํŒŒ์ผ ๋™์‹œ ์—…๋กœ๋“œ ๋ฐ ๋ณ‘ํ•ฉ ๋กœ์ง
def register_voice(actor_name, audio_files, gender, age, atmosphere, content):
    if not actor_name:
        return "์„ฑ์šฐ ์ด๋ฆ„์„ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”."
    
    if not audio_files:
        return "์ตœ์†Œ 1๊ฐœ ์ด์ƒ์˜ ์˜ค๋””์˜ค ํŒŒ์ผ์„ ์—…๋กœ๋“œํ•ด์ฃผ์„ธ์š”."
    
    try:
        combined_y =[]
        for f in audio_files:
            y, sr = librosa.load(f, sr=16000)
            combined_y.append(y)
        
        final_signal_np = np.concatenate(combined_y, axis=0)
        temp_audio = tempfile.NamedTemporaryFile(delete=False, suffix=".wav")
        sf.write(temp_audio.name, final_signal_np, 16000)
        
        combined_audio_path = temp_audio.name
        
        auto_tags = extract_audio_features(combined_audio_path)
        
        y_final, sr_final = librosa.load(combined_audio_path, sr=16000)
        signal = torch.tensor(y_final).unsqueeze(0)
        embedding = classifier.encode_batch(signal).squeeze().tolist()
        
        with open(combined_audio_path, "rb") as f:
            audio_b64 = base64.b64encode(f.read()).decode("utf-8")
        
        new_data = {
            "actor_name":[actor_name],
            "tags":[json.dumps(auto_tags)],
            "embedding":[json.dumps(embedding)],
            "registered_at":[datetime.now().strftime("%Y-%m-%d %H:%M:%S")],
            "audio_b64":[audio_b64],
            "gender":[gender if gender else ""],
            "age":[age if age else ""],
            "atmosphere":[json.dumps(atmosphere if atmosphere else [])],
            "content":[json.dumps(content if content else [])]
        }
        
        try:
            ds = load_dataset(DATASET_REPO, split="train")
            
            if actor_name in ds["actor_name"]:
                ds = ds.filter(lambda x: x["actor_name"] != actor_name)
                msg_prefix = "๐Ÿ”„[์ •๋ณด ์ˆ˜์ •]"
            else:
                msg_prefix = "โœ…[์‹ ๊ทœ ๋“ฑ๋ก]"
                
            new_ds = Dataset.from_dict(new_data)
            from datasets import concatenate_datasets
            updated_ds = concatenate_datasets([ds, new_ds])
        except Exception:
            updated_ds = Dataset.from_dict(new_data)
            msg_prefix = "โœ…[์‹ ๊ทœ ๋“ฑ๋ก]"
            
        updated_ds.push_to_hub(DATASET_REPO, token=HF_TOKEN)
        return f"{msg_prefix} ์™„๋ฃŒ![{actor_name}] ์„ฑ์šฐ์˜ ์ •๋ณด๊ฐ€ ๋ฐ˜์˜๋˜์—ˆ์Šต๋‹ˆ๋‹ค."
        
    except Exception as e:
        return f"โŒ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}"

# 5.[์‚ฌ์šฉ์ž์šฉ] ์œ ์‚ฌ๋„ ๋ถ„์„ ๋ฐ ๊ฒฐ๊ณผ ์˜ค๋””์˜ค ๋ฐ˜ํ™˜
def match_voice(user_audio):
    if user_audio is None:
        return "๋ถ„์„ํ•  ์˜ค๋””์˜ค๋ฅผ ์—…๋กœ๋“œํ•˜๊ฑฐ๋‚˜ ๋…น์Œํ•ด์ฃผ์„ธ์š”.", "", None
    
    target_audio = user_audio

    try:
        user_tags = extract_audio_features(target_audio)
        y_user, sr_user = librosa.load(target_audio, sr=16000)
        signal = torch.tensor(y_user).unsqueeze(0)
        user_embedding = classifier.encode_batch(signal).squeeze()
    except Exception as e:
        return f"โŒ ์˜ค๋””์˜ค ๋ถ„์„์— ์‹คํŒจํ–ˆ์Šต๋‹ˆ๋‹ค. ์œ ํšจํ•œ ์Œ์„ฑ์ธ์ง€ ํ™•์ธํ•ด์ฃผ์„ธ์š”.\n(์—๋Ÿฌ: {str(e)})", "", None
    
    try:
        ds = load_dataset(DATASET_REPO, split="train")
    except Exception:
        return "๋“ฑ๋ก๋œ ์„ฑ์šฐ ๋ฐ์ดํ„ฐ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค. ๊ด€๋ฆฌ์ž ํƒญ์—์„œ ๋จผ์ € ๋“ฑ๋กํ•ด์ฃผ์„ธ์š”.", "", None
    
    best_match = None
    highest_score = -1
    best_audio_b64 = None 
    cos = torch.nn.CosineSimilarity(dim=-1)
    
    for row in ds:
        db_emb = torch.tensor(json.loads(row["embedding"]))
        score = cos(user_embedding, db_emb).item()
        if score > highest_score:
            highest_score = score
            best_match = row["actor_name"]
            best_audio_b64 = row.get("audio_b64", None)
            
    similarity_percent = round((highest_score + 1) / 2 * 100, 2)
    
    ment = f"๋ถ„์„๋œ ์Œ์„ฑ์€ '{user_tags[0]}'๊ณผ '{user_tags[1]}'๋ฅผ ๊ฐ€์ง€๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค.\n"
    ment += f"์ด๋Ÿฌํ•œ ํŠน์„ฑ๊ณผ ์„ฑ๋„ ํŒŒํ˜•์ด ๊ฐ€์žฅ ์ผ์น˜ํ•˜๋Š” ์„ฑ์šฐ๋กœ **[{best_match}]** ๋‹˜์„ ์ถ”์ฒœํ•ฉ๋‹ˆ๋‹ค! (์ผ์น˜์œจ: {similarity_percent}%)"
    
    matched_audio_path = None
    if best_audio_b64:
        try:
            audio_bytes = base64.b64decode(best_audio_b64)
            temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".wav")
            temp_file.write(audio_bytes)
            temp_file.close()
            matched_audio_path = temp_file.name
        except Exception:
            pass
            
    return ment, best_match, matched_audio_path

def save_feedback(best_match, feedback_score):
    return f"[{best_match}] ์ถ”์ฒœ์— ๋Œ€ํ•œ ํ”ผ๋“œ๋ฐฑ({feedback_score}์ )์ด ์•ˆ์ „ํ•˜๊ฒŒ ์ €์žฅ๋˜์—ˆ์Šต๋‹ˆ๋‹ค."

# 6.[๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ ๋ฐ ๊ด€๋ฆฌ์ž ๊ณตํ†ต์šฉ]
def get_actor_list():
    try:
        ds = load_dataset(DATASET_REPO, split="train")
        return sorted([row["actor_name"] for row in ds])
    except:
        return[]

def get_filtered_actors(genders, ages, atmos, contents):
    try:
        ds = load_dataset(DATASET_REPO, split="train")
        filtered_list =[]
        for row in ds:
            r_gender = row.get("gender", "")
            r_age = row.get("age", "")
            r_atmos = json.loads(row.get("atmosphere", "[]")) if row.get("atmosphere") else[]
            r_content = json.loads(row.get("content", "[]")) if row.get("content") else[]
            
            if genders and r_gender not in genders: continue
            if ages and r_age not in ages: continue
            if atmos and not any(a in r_atmos for a in atmos): continue
            if contents and not any(c in r_content for c in contents): continue
            
            filtered_list.append(row["actor_name"])
        
        filtered_list = sorted(filtered_list)
        return gr.Radio(choices=filtered_list, value=None, label="๊ฒ€์ƒ‰๋œ ์„ฑ์šฐ ์„ ํƒ (๋ฐ”๋กœ ํด๋ฆญํ•˜์„ธ์š”)")
    except:
        return gr.Radio(choices=[], value=None, label="๊ฒ€์ƒ‰๋œ ์„ฑ์šฐ ์„ ํƒ (๋ฐ”๋กœ ํด๋ฆญํ•˜์„ธ์š”)")

def load_actor_details(actor_name):
    if not actor_name:
        return None, "์„ฑ์šฐ๋ฅผ ์„ ํƒํ•ด์ฃผ์„ธ์š”."
    try:
        ds = load_dataset(DATASET_REPO, split="train")
        for row in ds:
            if row["actor_name"] == actor_name:
                auto_tags = ", ".join(json.loads(row.get("tags", "[]")))
                r_gender = row.get("gender", "")
                r_age = row.get("age", "")
                r_atmos = ", ".join(json.loads(row.get("atmosphere", "[]"))) if row.get("atmosphere") else ""
                r_content = ", ".join(json.loads(row.get("content", "[]"))) if row.get("content") else ""
                
                info_text = f"**[AI ๋ถ„์„ ํŠน์ง•]** {auto_tags}\n"
                info_text += f"**[์„ฑ๋ณ„/์—ฐ๋ น]** {r_gender} / {r_age}\n"
                info_text += f"**[๋ถ„์œ„๊ธฐ]** {r_atmos}\n"
                info_text += f"**[์ถ”์ฒœ ์ฝ˜ํ…์ธ ]** {r_content}"
                
                if "audio_b64" in row and row["audio_b64"]:
                    audio_bytes = base64.b64decode(row["audio_b64"])
                    temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".wav")
                    temp_file.write(audio_bytes)
                    temp_file.close()
                    return temp_file.name, info_text
                else:
                    return None, f"{info_text}\n\n(์˜ค๋””์˜ค ํŒŒ์ผ์ด ์—†๋Š” ์ดˆ๊ธฐ ๋ฐ์ดํ„ฐ์ž…๋‹ˆ๋‹ค)"
        return None, "์ •๋ณด๋ฅผ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."
    except Exception as e:
        return None, f"์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}"

# UI ์นดํ…Œ๊ณ ๋ฆฌ ์ •์˜
UI_GENDER =["๋‚จ์„ฑ", "์—ฌ์„ฑ"]
UI_AGE =["์•„๋™", "์ฒญ์†Œ๋…„", "์ฒญ๋…„", "์ค‘๋…„", "์žฅ๋…„"]
UI_ATMOS =["ํž˜ ์žˆ๋Š”", "๋ฐ์€", "๊ท€์—ฌ์šด", "๊ฐ€๋ฒผ์šด", "์„ธ๋ จ๋œ", "๋”ฐ๋œปํ•œ", "์ฐจ๋ถ„ํ•œ", "์‹ ๋ขฐ๊ฐ์žˆ๋Š”", "์ฐจ๊ฐ€์šด", "๊ฐ์„ฑ์ ์ธ", "๊ธฐํƒ€"]
UI_CONTENT =["๋‹คํ/๋ฆฌ๋ทฐ", "๋‚ญ๋…/์˜ค๋””์˜ค๋ถ", "๊ธฐ์ž/์•„๋‚˜์šด์„œ", "๋ผ๋””์˜ค/ํŒŸ์บ์ŠคํŠธ", "๊ด‘๊ณ /์ด๋ฒคํŠธ", "๊ต์œก/๊ฐ•์˜", "์•ˆ๋‚ด์Œ์„ฑ/ARS", "๊ฒŒ์ž„/์• ๋‹ˆ", "์Œ์•…/์—”ํ„ฐํ…Œ์ธ๋จผํŠธ"]

# 7. Gradio UI
with gr.Blocks(theme=gr.themes.Soft()) as demo:
    with gr.Row(elem_id="header-row"):
        gr.Markdown("# ๐ŸŽ™๏ธ AI ์„ฑ์šฐ ๋ชฉ์†Œ๋ฆฌ ๋งค์นญ ์„œ๋น„์Šค")
        logout_btn = gr.Button("๐Ÿ”’ ๋กœ๊ทธ์•„์›ƒ", size="sm", variant="secondary", scale=0, min_width=100)
        
    logout_btn.click(fn=None, inputs=None, outputs=None, js="() => { window.location.href = '/logout'; }")
    
    with gr.Tabs():
        with gr.Tab("์‚ฌ์šฉ์ž ๊ฒ€์ƒ‰ (Voice Matcher)"):
            gr.Markdown("์ฐพ๊ณ  ์‹ถ์€ ๋ ˆํผ๋Ÿฐ์Šค ๋ชฉ์†Œ๋ฆฌ๋ฅผ **์ง์ ‘ ๋…น์Œ**ํ•˜๊ฑฐ๋‚˜ **ํŒŒ์ผ๋กœ ์—…๋กœ๋“œ**ํ•ด์ฃผ์„ธ์š”.")
            
            with gr.Row():
                with gr.Column(scale=1):
                    # ๐ŸŒŸ sources=["upload", "microphone"] ์ถ”๊ฐ€๋กœ ๋…น์Œ๊ณผ ์—…๋กœ๋“œ๋ฅผ ๋™์‹œ ์ง€์›!
                    user_audio = gr.Audio(sources=["upload", "microphone"], type="filepath", label="๐ŸŽต ์ง์ ‘ ๋…น์Œ(๋งˆ์ดํฌ) ๋˜๋Š” ํŒŒ์ผ ์—…๋กœ๋“œ")
                    
                    gr.HTML("""
                        <div style="background-color: #f9f9f9; padding: 12px; border-radius: 8px; margin-top: 10px; font-size: 13px; color: #555;">
                            ๐Ÿ’ก <b>์œ ํŠœ๋ธŒ ์˜์ƒ์˜ ๋ชฉ์†Œ๋ฆฌ๋ฅผ ์ฐพ๊ณ  ์‹ถ์œผ์‹ ๊ฐ€์š”?</b><br>
                            1. ๊ฐ€์žฅ ์‰ฌ์šด ๋ฐฉ๋ฒ•: ์œ ํŠœ๋ธŒ๋ฅผ ์Šคํ”ผ์ปค๋กœ ํ‹€์–ด๋†“๊ณ  ์œ„ ์นธ์˜ <b>[๋งˆ์ดํฌ ์•„์ด์ฝ˜]</b>์„ ๋ˆŒ๋Ÿฌ 10์ดˆ๊ฐ„ ๋…น์Œํ•˜์„ธ์š”!<br>
                            2. ๊ณ ์Œ์งˆ ํŒŒ์ผ์ด ํ•„์š”ํ•˜๋‹ค๋ฉด: <a href="https://cobalt.tools/" target="_blank" style="color: #0066cc; font-weight: bold; text-decoration: underline;">์—ฌ๊ธฐ(์•ˆ์ „ํ•œ ๋ฌด๋ฃŒ ์ถ”์ถœ ์‚ฌ์ดํŠธ ์ƒˆ์ฐฝ์—ด๊ธฐ)</a>์—์„œ mp3๋ฅผ ๋‹ค์šด๋ฐ›์•„ ์—…๋กœ๋“œํ•˜์„ธ์š”.
                        </div>
                    """)
                    
                    match_btn = gr.Button("๊ฐ€์žฅ ๋น„์Šทํ•œ ์„ฑ์šฐ ์ฐพ๊ธฐ", variant="primary")
                    
                with gr.Column(scale=1):
                    result_text = gr.Textbox(label="๋ถ„์„ ๋ฐ ์ถ”์ฒœ ๊ฒฐ๊ณผ", lines=4)
                    matched_audio_preview = gr.Audio(label="๐ŸŽง ์ถ”์ฒœ๋œ ์„ฑ์šฐ ๋ชฉ์†Œ๋ฆฌ ๋ฏธ๋ฆฌ๋“ฃ๊ธฐ", interactive=False)
                    
                    matched_actor = gr.State()
                    gr.Markdown("---")
                    feedback_slider = gr.Slider(1, 5, step=1, label="์ถ”์ฒœ ๋งŒ์กฑ๋„ ํ‰๊ฐ€")
                    feedback_btn = gr.Button("ํ”ผ๋“œ๋ฐฑ ์ œ์ถœ")
                    feedback_out = gr.Textbox(label="์‹œ์Šคํ…œ ๋ฉ”์‹œ์ง€")
                    
            match_btn.click(fn=match_voice, inputs=[user_audio], outputs=[result_text, matched_actor, matched_audio_preview])
            feedback_btn.click(fn=save_feedback, inputs=[matched_actor, feedback_slider], outputs=feedback_out)
        
        with gr.Tab("์„ฑ์šฐ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ (๋ฏธ๋ฆฌ๋“ฃ๊ธฐ)"):
            gr.Markdown("์กฐ๊ฑด์„ ์„ ํƒํ•˜๊ณ  ํ•„ํ„ฐ๋ฅผ ์ ์šฉํ•˜์—ฌ ์›ํ•˜๋Š” ์„ฑ์šฐ์˜ ๋ชฉ์†Œ๋ฆฌ๋ฅผ ์ง์ ‘ ๋“ค์–ด๋ณด์„ธ์š”.")
            with gr.Row():
                with gr.Column(scale=1):
                    gr.Markdown("### ๐Ÿ” ์กฐ๊ฑด ๊ฒ€์ƒ‰")
                    lib_gender = gr.CheckboxGroup(choices=UI_GENDER, label="์„ฑ๋ณ„")
                    lib_age = gr.CheckboxGroup(choices=UI_AGE, label="์—ฐ๋ น์ธต")
                    lib_atmos = gr.CheckboxGroup(choices=UI_ATMOS, label="๋ถ„์œ„๊ธฐ")
                    lib_content = gr.CheckboxGroup(choices=UI_CONTENT, label="์ฝ˜ํ…์ธ ")
                    filter_btn = gr.Button("ํ•„ํ„ฐ ์ ์šฉํ•˜์—ฌ ๊ฒ€์ƒ‰", variant="secondary")
                
                with gr.Column(scale=2):
                    gr.Markdown("### ๐ŸŽง ๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ ๋ฐ ๋ฏธ๋ฆฌ๋“ฃ๊ธฐ")
                    actor_dropdown = gr.Radio(choices=[], label="๊ฒ€์ƒ‰๋œ ์„ฑ์šฐ ์„ ํƒ (๋ฐ”๋กœ ํด๋ฆญํ•˜์„ธ์š”)")
                    library_audio = gr.Audio(label="๋ชฉ์†Œ๋ฆฌ ๋ฏธ๋ฆฌ๋“ฃ๊ธฐ", interactive=False)
                    library_tags = gr.Markdown("์„ฑ์šฐ๋ฅผ ์„ ํƒํ•˜๋ฉด ์ƒ์„ธ ์ •๋ณด๊ฐ€ ์—ฌ๊ธฐ์— ํ‘œ์‹œ๋ฉ๋‹ˆ๋‹ค.")
            
            filter_btn.click(fn=get_filtered_actors, inputs=[lib_gender, lib_age, lib_atmos, lib_content], outputs=actor_dropdown)
            actor_dropdown.change(fn=load_actor_details, inputs=actor_dropdown, outputs=[library_audio, library_tags])

        with gr.Tab("๊ด€๋ฆฌ์ž ํƒญ (์„ฑ์šฐ ๋“ฑ๋ก ๋ฐ ์ˆ˜์ •)"):
            gr.Markdown("์ƒˆ๋กœ์šด ์„ฑ์šฐ๋ฅผ ๋“ฑ๋กํ•˜๊ฑฐ๋‚˜ ๊ธฐ์กด ์„ฑ์šฐ์˜ ์ •๋ณด๋ฅผ ์ˆ˜์ •ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.")
            
            with gr.Row():
                admin_clear_btn = gr.Button("โœจ ์‹ ๊ทœ ๋“ฑ๋ก์„ ์œ„ํ•ด ํผ ์ „์ฒด ๋น„์šฐ๊ธฐ", variant="secondary")
            
            with gr.Accordion("๐Ÿ“‚ ๊ธฐ์กด ์„ฑ์šฐ ์ •๋ณด ๋ถˆ๋Ÿฌ์˜ค๊ธฐ (ํด๋ฆญํ•ด์„œ ์—ด๊ธฐ)", open=False):
                admin_edit_dropdown = gr.Radio(choices=[], label="โœ๏ธ ์ˆ˜์ •ํ•  ์„ฑ์šฐ๋ฅผ ์„ ํƒํ•˜๋ฉด ์•„๋ž˜ ํผ์— ์ •๋ณด๊ฐ€ ์ฑ„์›Œ์ง‘๋‹ˆ๋‹ค")
                admin_refresh_btn = gr.Button("๋“ฑ๋ก๋œ ์„ฑ์šฐ ๋ชฉ๋ก ์ƒˆ๋กœ๊ณ ์นจ")
                
            gr.Markdown("---")
            
            with gr.Row():
                with gr.Column(scale=1):
                    admin_name = gr.Textbox(label="์„ฑ์šฐ ์ด๋ฆ„ (ํ•„์ˆ˜)")
                    admin_audio_files = gr.File(
                        file_count="multiple", 
                        file_types=["audio"], 
                        type="filepath", 
                        label="๐ŸŽต ์Œ์„ฑ ์ƒ˜ํ”Œ ๋‹ค์ค‘ ์—…๋กœ๋“œ (์—ฌ๋Ÿฌ ํŒŒ์ผ์„ ํ•œ๋ฒˆ์— ๋“œ๋ž˜๊ทธํ•˜๊ฑฐ๋‚˜ ์„ ํƒํ•˜์„ธ์š”)"
                    )
                    admin_audio_preview = gr.Audio(label="์ €์žฅ๋œ ์Œ์„ฑ ํ™•์ธ์šฉ (๊ธฐ์กด ์ •๋ณด ๋ถˆ๋Ÿฌ์˜ค๊ธฐ ์‹œ ์žฌ์ƒ)", interactive=False)
                    
                with gr.Column(scale=1):
                    admin_gender = gr.Radio(choices=UI_GENDER, label="์„ฑ๋ณ„")
                    admin_age = gr.Radio(choices=UI_AGE, label="์—ฐ๋ น์ธต")
                    admin_atmos = gr.CheckboxGroup(choices=UI_ATMOS, label="๋ถ„์œ„๊ธฐ (๋‹ค์ค‘ ์„ ํƒ ๊ฐ€๋Šฅ)")
                    admin_content = gr.CheckboxGroup(choices=UI_CONTENT, label="์ถ”์ฒœ ์ฝ˜ํ…์ธ  (๋‹ค์ค‘ ์„ ํƒ ๊ฐ€๋Šฅ)")
            
            admin_btn = gr.Button("์„ฑ์šฐ DB์— ๋“ฑ๋ก/์ˆ˜์ •ํ•˜๊ธฐ", variant="primary")
            admin_out = gr.Textbox(label="์ฒ˜๋ฆฌ ๊ฒฐ๊ณผ")
            
            admin_refresh_btn.click(fn=lambda: gr.Radio(choices=get_actor_list(), label="โœ๏ธ ์ˆ˜์ •ํ•  ์„ฑ์šฐ๋ฅผ ์„ ํƒํ•˜๋ฉด ์•„๋ž˜ ํผ์— ์ •๋ณด๊ฐ€ ์ฑ„์›Œ์ง‘๋‹ˆ๋‹ค"), outputs=admin_edit_dropdown)
            
            def clear_admin_form():
                return None, "", None, None, None, None, [],[], ""
                
            admin_clear_btn.click(
                fn=clear_admin_form,
                outputs=[admin_edit_dropdown, admin_name, admin_audio_files, admin_audio_preview, admin_gender, admin_age, admin_atmos, admin_content, admin_out]
            )
            
            def load_for_admin_edit(name):
                if not name: return name, None, None, None, None,[],[]
                try:
                    ds = load_dataset(DATASET_REPO, split="train")
                    for row in ds:
                        if row["actor_name"] == name:
                            r_gender = row.get("gender", None)
                            r_age = row.get("age", None)
                            r_atmos = json.loads(row.get("atmosphere", "[]")) if row.get("atmosphere") else[]
                            r_content = json.loads(row.get("content", "[]")) if row.get("content") else[]
                            
                            audio_path = None
                            if "audio_b64" in row and row["audio_b64"]:
                                audio_bytes = base64.b64decode(row["audio_b64"])
                                temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".wav")
                                temp_file.write(audio_bytes)
                                temp_file.close()
                                audio_path = temp_file.name
                                
                            return name,[audio_path] if audio_path else None, audio_path, r_gender, r_age, r_atmos, r_content
                except:
                    pass
                return name, None, None, None, None,[],[]

            admin_edit_dropdown.change(
                fn=load_for_admin_edit,
                inputs=admin_edit_dropdown,
                outputs=[admin_name, admin_audio_files, admin_audio_preview, admin_gender, admin_age, admin_atmos, admin_content]
            )
            
            admin_btn.click(
                fn=register_voice, 
                inputs=[admin_name, admin_audio_files, admin_gender, admin_age, admin_atmos, admin_content], 
                outputs=admin_out
            )

if __name__ == "__main__":
    admin_pw = os.environ.get("ADMIN_PASSWORD", "admin0000")
    guest_pw = os.environ.get("GUEST_PASSWORD", "guest0000")
    
    demo.queue()
    
    demo.launch(
        server_name="0.0.0.0",
        auth=[
            ("admin", admin_pw),
            ("guest", guest_pw)
        ]
    )