TTS-player / app.py
trung06042002's picture
Create app.py
7597632 verified
import os
from typing import List, Optional
import gradio as gr
from huggingface_hub import HfApi, hf_hub_download, hf_hub_url
DATASET_REPO = os.getenv("DATASET_REPO", "trung06042002/TTS")
REPO_TYPE = "dataset"
api = HfApi()
def list_audio_files() -> List[str]:
files = api.list_repo_files(repo_id=DATASET_REPO, repo_type=REPO_TYPE)
audio_ext = (".mp3", ".wav", ".m4a", ".flac", ".ogg")
audios = [f for f in files if f.lower().endswith(audio_ext)]
audios.sort(reverse=True)
return audios
def make_download_link(path_in_repo: str) -> str:
url = hf_hub_url(repo_id=DATASET_REPO, repo_type=REPO_TYPE, filename=path_in_repo)
return f"✅ **Download:** {url}?download=1"
def load_audio(path_in_repo: str):
if not path_in_repo:
return None, "Chọn một file audio."
local_path = hf_hub_download(
repo_id=DATASET_REPO,
repo_type=REPO_TYPE,
filename=path_in_repo,
)
return local_path, make_download_link(path_in_repo)
def on_refresh():
files = list_audio_files()
return gr.Dropdown(choices=files, value=(files[0] if files else None))
def on_load(request: gr.Request):
files = list_audio_files()
qp = request.query_params if request else {}
wanted: Optional[str] = qp.get("file")
if wanted and wanted in files:
audio_path, md = load_audio(wanted)
return gr.Dropdown(choices=files, value=wanted), audio_path, md
# default: file mới nhất
if files:
audio_path, md = load_audio(files[0])
return gr.Dropdown(choices=files, value=files[0]), audio_path, md
return gr.Dropdown(choices=[], value=None), None, "Chưa có file audio trong dataset."
with gr.Blocks(title="TTS Player") as demo:
gr.Markdown(f"# 🎧 TTS Player\nDataset: `{DATASET_REPO}`")
with gr.Row():
dd = gr.Dropdown(label="Audio files", choices=[], value=None, interactive=True)
btn = gr.Button("🔄 Refresh")
audio = gr.Audio(label="Player", type="filepath")
download_md = gr.Markdown()
btn.click(on_refresh, inputs=None, outputs=dd)
dd.change(load_audio, inputs=dd, outputs=[audio, download_md])
demo.load(on_load, inputs=None, outputs=[dd, audio, download_md])
demo.launch()