Update app.py
Browse files6 unmodified lines78910111241 unmodified lines5455565758596061626364656667686970717273747576777879808112 unmodified lines9495969798991008 unmodified lines1091101111121131141151161171181191201211221231241251261271281291302 unmodified lines1331341351361371381392 unmodified lines14214314414514614714814915015115215315415514 unmodified lines17017117217317417517615 unmodified lines19219319419519619719842 unmodified lines2412422432442452462472482492506 unmodified lines25725825926026126226321 unmodified lines28528628728828929029136 unmodified lines32832933033133233333430 unmodified lines3653663673686 unmodified linesimport base64import tempfileimport soundfile as sffrom datetime import datetimefrom speechbrain.inference import EncoderClassifier41 unmodified linesreturn "μ΅μ 1κ° μ΄μμ μ€λμ€ νμΌμ μ λ‘λν΄μ£ΌμΈμ."try:# μ¬λ¬ κ°μ μ€λμ€ νμΌμ νλλ‘ μμ°μ€λ½κ² ν©μΉκΈ° (16000Hzλ‘ ν΅μΌ)combined_y =[]for f in audio_files:y, sr = librosa.load(f, sr=16000)combined_y.append(y)# μμ ν soundfile λΌμ΄λΈλ¬λ¦¬λ₯Ό μ΄μ©ν΄ λ³ν© λ° μμ μ μ₯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# AI μλ λΆμ (ν©μ³μ§ νμΌ κΈ°μ€)auto_tags = extract_audio_features(combined_audio_path)# librosaλ₯Ό μ¬μ©νμ¬ μμ νκ² ν μλ‘ λ³ν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")12 unmodified linestry: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 = "π[μ 보 μμ ]"8 unmodified linesmsg_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 "μ€λμ€ νμΌμ μ λ‘λν΄μ£ΌμΈμ.", "", Noneuser_tags = extract_audio_features(user_audio)# librosaλ₯Ό μ¬μ©νμ¬ μμ νκ² ν μλ‘ λ³νy_user, sr_user = librosa.load(user_audio, sr=16000)signal = torch.tensor(y_user).unsqueeze(0)user_embedding = classifier.encode_batch(signal).squeeze()try:ds = load_dataset(DATASET_REPO, split="train")2 unmodified linesbest_match = Nonehighest_score = -1best_audio_b64 = None # λ§€μΉλ μ±μ°μ μ€λμ€λ₯Ό λ΄μ λ³μcos = torch.nn.CosineSimilarity(dim=-1)for row in ds:2 unmodified linesif score > highest_score:highest_score = scorebest_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 = Noneif best_audio_b64:try:14 unmodified linesdef get_actor_list():try:ds = load_dataset(DATASET_REPO, split="train")#[μμ ] κ°λλ€ μμΌλ‘ μ λ ¬(sorted) μΆκ°return sorted([row["actor_name"] for row in ds])except:return[]15 unmodified linesfiltered_list.append(row["actor_name"])# [μμ ] νν°λ§λ κ²°κ³Όλ κ°λλ€ μμΌλ‘ μ λ ¬filtered_list = sorted(filtered_list)return gr.Radio(choices=filtered_list, value=None, label="κ²μλ μ±μ° μ ν (λ°λ‘ ν΄λ¦νμΈμ)")except:42 unmodified lineswith gr.Tabs():# ν 1: μ¬μ©μ κ²μwith gr.Tab("μ¬μ©μ κ²μ (Voice Matcher)"):gr.Markdown("μ°Ύκ³ μΆμ λλμ λͺ©μ리 μν(15μ΄ μ΄λ΄)μ μ¬λ €μ£ΌμΈμ.")with gr.Row():with gr.Column():user_audio = gr.Audio(type="filepath", label="μμ± μ λ‘λ")match_btn = gr.Button("κ°μ₯ λΉμ·ν μ±μ° μ°ΎκΈ°", variant="primary")with gr.Column():result_text = gr.Textbox(label="λΆμ λ° μΆμ² κ²°κ³Ό", lines=4)6 unmodified linesfeedback_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)# ν 2: λΌμ΄λΈλ¬λ¦¬21 unmodified lineswith gr.Tab("κ΄λ¦¬μ ν (μ±μ° λ±λ‘ λ° μμ )"):gr.Markdown("μλ‘μ΄ μ±μ°λ₯Ό λ±λ‘νκ±°λ κΈ°μ‘΄ μ±μ°μ μ 보λ₯Ό μμ ν μ μμ΅λλ€.")# [μμ ] λͺ¨λ°μΌ μ κ·Όμ±μ μν΄ νΌ μ΄κΈ°ν λ²νΌμ μμ½λμΈ λ°κΉ₯(μ)μΌλ‘ λΆλ¦¬with gr.Row():admin_clear_btn = gr.Button("β¨ μ κ· λ±λ‘μ μν΄ νΌ μ 체 λΉμ°κΈ°", variant="secondary")36 unmodified lines)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:30 unmodified linesif __name__ == "__main__":demo.launch()6 unmodified lines789101112131441 unmodified lines565758596061626364656667686970717273747576777812 unmodified lines9192939495968 unmodified lines1051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691702 unmodified lines1731741751761771781792 unmodified lines18218318418518618718818919019119219319414 unmodified lines20921021121221321415 unmodified lines23023123223323423542 unmodified lines2782792802812822832842852862872882892902912922932942952962972986 unmodified lines30530630730830931031121 unmodified lines33333433533633733836 unmodified lines37537637737837938038130 unmodified lines4124134146 unmodified linesimport base64import tempfileimport soundfile as sfimport urllib.requestimport yt_dlp # μ νλΈ μ§μ μΆμΆμ μν΄ μΆκ°λ λΌμ΄λΈλ¬λ¦¬from datetime import datetimefrom speechbrain.inference import EncoderClassifier41 unmodified linesreturn "μ΅μ 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.nameauto_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")12 unmodified linestry: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 = "π[μ 보 μμ ]"8 unmodified linesmsg_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, user_url):if user_audio is None and not user_url.strip():return "μ€λμ€ νμΌμ μ λ‘λνκ±°λ URLμ μ λ ₯ν΄μ£ΌμΈμ.", "", Nonetarget_audio = user_audio# 1. νμΌμ΄ μκ³ URLλ§ μ λ ₯λ κ²½μ° λ€μ΄λ‘λ λ‘μ§ μ€νif target_audio is None and user_url.strip():# μ νλΈ URLμΈ κ²½μ° μ± λ΄μ₯ yt-dlpλ₯Ό μ¬μ©νμ¬ μ§μ μ€λμ€ μΆμΆif "youtube.com" in user_url or "youtu.be" in user_url:try:# μμ νμΌλͺ μμ± (.wav λ‘ λ³ννλλ‘ μ€μ )temp_out = tempfile.mktemp(suffix='.%(ext)s')ydl_opts = {'format': 'bestaudio/best','postprocessors':[{'key': 'FFmpegExtractAudio','preferredcodec': 'wav','preferredquality': '192',}],'outtmpl': temp_out,'quiet': True,'no_warnings': True}with yt_dlp.YoutubeDL(ydl_opts) as ydl:info_dict = ydl.extract_info(user_url, download=True)downloaded_file = ydl.prepare_filename(info_dict)# yt-dlpκ° νμ₯μλ₯Ό .wavλ‘ λ°κΏ¨μΌλ―λ‘ κ²½λ‘ μμ target_audio = downloaded_file.rsplit('.', 1)[0] + '.wav'except Exception as e:# [μμ ] μλ¬ μ μ§μ μ λ‘λλ₯Ό μ λνλ 문ꡬ 보κ°return f"β μ νλΈ μμ μΆμΆμ μ€ν¨νμ΅λλ€. μ νλΈ μ체 보μ(λ΄ μ°¨λ¨) λλ¬Έμ λλ€.\nμλ μλ΄μ λ°λΌ μΈλΆ ν΄μμ mp3λ₯Ό μ§μ λ€μ΄λ‘λνμ ν [μμ± νμΌ μ§μ μ λ‘λ] μΉΈμ μ΄μ©ν΄μ£ΌμΈμ!", "", None# μ νλΈκ° μλ μΌλ° μ§μ μ€λμ€ νμΌ λ§ν¬(.mp3, .wav λ±)μΈ κ²½μ°else:try:temp_dl = tempfile.NamedTemporaryFile(delete=False, suffix=".wav")req = urllib.request.Request(user_url, headers={'User-Agent': 'Mozilla/5.0'})with urllib.request.urlopen(req) as response, open(temp_dl.name, 'wb') as out_file:out_file.write(response.read())target_audio = temp_dl.nameexcept Exception as e:return f"β μΌλ° URL λ€μ΄λ‘λ μ€ν¨: μ§μ μ μΈ μ€λμ€ νμΌ λ§ν¬(.mp3, .wav)μΈμ§ νμΈν΄μ£ΌμΈμ.\n(μλ¬: {str(e)})", "", None# 2. λ€μ΄λ‘λλ νμΌλ‘ AI λΆμ μ€ν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)})", "", Nonetry:ds = load_dataset(DATASET_REPO, split="train")2 unmodified linesbest_match = Nonehighest_score = -1best_audio_b64 = Nonecos = torch.nn.CosineSimilarity(dim=-1)for row in ds:2 unmodified linesif score > highest_score:highest_score = scorebest_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 = Noneif best_audio_b64:try:14 unmodified linesdef get_actor_list():try:ds = load_dataset(DATASET_REPO, split="train")return sorted([row["actor_name"] for row in ds])except:return[]15 unmodified linesfiltered_list.append(row["actor_name"])filtered_list = sorted(filtered_list)return gr.Radio(choices=filtered_list, value=None, label="κ²μλ μ±μ° μ ν (λ°λ‘ ν΄λ¦νμΈμ)")except:42 unmodified lineswith gr.Tabs():# ν 1: μ¬μ©μ κ²μwith gr.Tab("μ¬μ©μ κ²μ (Voice Matcher)"):gr.Markdown("μ°Ύκ³ μΆμ λλμ λͺ©μ리 μν(15μ΄ μ΄λ΄)μ μ¬λ¦¬κ±°λ μ νλΈ URLμ μ λ ₯ν΄μ£ΌμΈμ.")with gr.Row():with gr.Column():user_audio = gr.Audio(type="filepath", label="π΅ μμ± νμΌ μ§μ μ λ‘λ")gr.Markdown("<div style='text-align: center; font-weight: bold; margin: 10px 0;'>λλ</div>")user_url = gr.Textbox(label="π μ νλΈ μμ λ§ν¬ μ λ ₯ (μλμΌλ‘ μ€λμ€λ₯Ό μΆμΆνμ¬ λΆμν©λλ€)", placeholder="μ: https://www.youtube.com/watch?v=...")#[μ κ· μΆκ°] μΆμΆ μ€ν¨ μ μΈλΆ ν΄ μλ΄ λ° λ§ν¬ μ 곡gr.HTML("""<div style="background-color: #f9f9f9; padding: 12px; border-radius: 8px; margin-top: 10px; font-size: 13px; color: #555;">π‘ <b>[μλ΄μ¬ν]</b> μλ² μνλ μ νλΈ λ³΄μ μ μ± (λ΄ μ°¨λ¨)μ λ°λΌ κ°νΉ URL μλ μΆμΆμ μ€ν¨ν μ μμ΅λλ€.<br>λ§μ½ μ€ν¨νλ€λ©΄ λΉν©νμ§ λ§μκ³ , <a href="https://cobalt.tools/" target="_blank" style="color: #d93025; font-weight: bold; text-decoration: underline;">λ¬΄λ£ μ€λμ€ μΆμΆκΈ°(μ¬κΈ°λ₯Ό ν΄λ¦)</a>μμ mp3λ₯Ό μ§μ λ€μ΄λ‘λνμ ν μμ <b>[μμ± νμΌ μ§μ μ λ‘λ]</b> κΈ°λ₯μ μ΄μ©ν΄μ£ΌμΈμ!</div>""")match_btn = gr.Button("κ°μ₯ λΉμ·ν μ±μ° μ°ΎκΈ°", variant="primary")with gr.Column():result_text = gr.Textbox(label="λΆμ λ° μΆμ² κ²°κ³Ό", lines=4)6 unmodified linesfeedback_btn = gr.Button("νΌλλ°± μ μΆ")feedback_out = gr.Textbox(label="μμ€ν λ©μμ§")match_btn.click(fn=match_voice, inputs=[user_audio, user_url], outputs=[result_text, matched_actor, matched_audio_preview])feedback_btn.click(fn=save_feedback, inputs=[matched_actor, feedback_slider], outputs=feedback_out)# ν 2: λΌμ΄λΈλ¬λ¦¬21 unmodified lineswith gr.Tab("κ΄λ¦¬μ ν (μ±μ° λ±λ‘ λ° μμ )"):gr.Markdown("μλ‘μ΄ μ±μ°λ₯Ό λ±λ‘νκ±°λ κΈ°μ‘΄ μ±μ°μ μ 보λ₯Ό μμ ν μ μμ΅λλ€.")with gr.Row():admin_clear_btn = gr.Button("β¨ μ κ· λ±λ‘μ μν΄ νΌ μ 체 λΉμ°κΈ°", variant="secondary")36 unmodified lines)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:30 unmodified linesif __name__ == "__main__":demo.launch()
app.py+74-28