File size: 2,240 Bytes
7597632
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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()