File size: 13,491 Bytes
13ff032
a428f4c
13ff032
 
 
 
 
 
 
 
 
a428f4c
 
 
13ff032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a428f4c
13ff032
 
 
 
 
 
 
a428f4c
13ff032
a428f4c
 
 
 
13ff032
 
a428f4c
13ff032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a428f4c
13ff032
a428f4c
13ff032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a428f4c
13ff032
 
 
 
a428f4c
 
13ff032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a428f4c
13ff032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a428f4c
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
"""
Tool ASR Generate - Batch Text-to-Speech with VoxCPM2 (ZeroGPU Space)
Focused on Khmer (km) and English (en).

Upload a CSV / JSON / XLSX file containing a "text" column, and this app will
generate speech for every row using openbmb/VoxCPM2, then package all the
generated audio + a metadata.csv/json manifest into a downloadable ZIP that is
already structured the way Hugging Face `datasets` expects an audio folder
(audio/<file>.wav + metadata.csv with a "file_name" column), so you can push
it straight to a Dataset repo.

This version runs on a ZeroGPU Space. The model is instantiated at import
time (on CPU/meta); actual CUDA execution only happens inside the function
decorated with @spaces.GPU, which is where the GPU is allocated per call.

Language handling:
    - VoxCPM2 auto-detects language from the text itself (no language tag
      needed). Each row is still labeled "km" or "en" in the output metadata
      (either from an optional "language" column, or auto-detected from the
      Khmer Unicode script range), which is useful for filtering the dataset
      later, but generation itself uses a single shared reference voice.
    - The sidebar lets you upload one optional reference voice clip (+
      transcript) used for cloning across every row, regardless of language.

Input file requirements:
    - text                (required)  the sentence/paragraph to synthesize
    - id                  (optional)  used as the output filename, auto-generated if missing
    - language            (optional)  "en" or "km" β€” auto-detected if omitted
    - voice_description   (optional)  natural language voice style, e.g. "a calm young woman"
                                       (will be prepended as "(voice_description)text",
                                       overrides the reference-audio cloning for that row)
"""

import os
import io
import json
import uuid
import zipfile
import tempfile

import numpy as np
import pandas as pd
import soundfile as sf
import gradio as gr
import spaces
import torch

from voxcpm import VoxCPM

MODEL_ID = "openbmb/VoxCPM2"

# ---------------------------------------------------------------------------
# Model loading
# ---------------------------------------------------------------------------
# On ZeroGPU Spaces the model is instantiated at import time (on CPU/meta),
# and actual CUDA execution only happens inside functions decorated with
# @spaces.GPU. Do NOT move the model to cuda manually here.
print(f"Loading {MODEL_ID} ...")
model = VoxCPM.from_pretrained(MODEL_ID, load_denoiser=False)
SAMPLE_RATE = getattr(model.tts_model, "sample_rate", 48000)
print(f"Model loaded. Sample rate = {SAMPLE_RATE}")


# ---------------------------------------------------------------------------
# Language detection (Khmer vs English)
# ---------------------------------------------------------------------------
KHMER_RANGE = (0x1780, 0x17FF)  # Khmer Unicode block


def detect_language(text: str) -> str:
    for ch in str(text):
        if KHMER_RANGE[0] <= ord(ch) <= KHMER_RANGE[1]:
            return "km"
    return "en"


def normalize_language(value: str) -> str:
    v = str(value).strip().lower()
    if v in ("km", "kh", "khm", "khmer", "cambodian"):
        return "km"
    if v in ("en", "eng", "english"):
        return "en"
    return ""  # unrecognized -> fall back to auto-detect


# ---------------------------------------------------------------------------
# File parsing helpers
# ---------------------------------------------------------------------------
def load_table(file_path: str) -> pd.DataFrame:
    ext = os.path.splitext(file_path)[1].lower()

    if ext == ".csv":
        df = pd.read_csv(file_path)
    elif ext in (".xlsx", ".xls"):
        df = pd.read_excel(file_path)
    elif ext == ".json":
        with open(file_path, "r", encoding="utf-8") as f:
            data = json.load(f)
        if isinstance(data, dict):
            for key in ("items", "data", "rows"):
                if key in data and isinstance(data[key], list):
                    data = data[key]
                    break
        df = pd.DataFrame(data)
    else:
        raise ValueError(f"Unsupported file type: {ext}. Use .csv, .json, or .xlsx")

    df.columns = [str(c).strip().lower() for c in df.columns]

    if "text" not in df.columns:
        for alt in ("content", "sentence", "script", "transcript"):
            if alt in df.columns:
                df = df.rename(columns={alt: "text"})
                break

    if "text" not in df.columns:
        raise ValueError("No 'text' column found in the uploaded file.")

    if "id" not in df.columns:
        df.insert(0, "id", [f"{i + 1:04d}" for i in range(len(df))])
    else:
        df["id"] = df["id"].astype(str)

    if "voice_description" not in df.columns:
        df["voice_description"] = ""
    df["voice_description"] = df["voice_description"].fillna("").astype(str)

    df["text"] = df["text"].astype(str)
    df = df[df["text"].str.strip() != ""].reset_index(drop=True)

    if "language" in df.columns:
        df["language"] = df["language"].fillna("").apply(normalize_language)
    else:
        df["language"] = ""
    # fill anything unrecognized/empty with auto-detection from the text script
    needs_detect = df["language"] == ""
    df.loc[needs_detect, "language"] = df.loc[needs_detect, "text"].apply(detect_language)

    return df


def preview_file(file):
    if file is None:
        return None, "Upload a CSV, JSON, or XLSX file with a `text` column."
    try:
        df = load_table(file)
    except Exception as e:
        return None, f"❌ Error reading file: {e}"
    preview = df[["id", "language", "text", "voice_description"]].head(20)
    n_en = int((df["language"] == "en").sum())
    n_km = int((df["language"] == "km").sum())
    return preview, f"βœ… Loaded **{len(df)}** rows β€” English: {n_en}, Khmer: {n_km}. Showing first {min(20, len(df))}."


# ---------------------------------------------------------------------------
# GPU-bound single-item generation
# ---------------------------------------------------------------------------
@spaces.GPU(duration=120)
def _generate_one(text, voice_description, ref_wav_path, ref_text, cfg_value, inference_timesteps):
    prompt = text
    if voice_description and voice_description.strip():
        prompt = f"({voice_description.strip()}){text}"

    kwargs = dict(
        text=prompt,
        cfg_value=float(cfg_value),
        inference_timesteps=int(inference_timesteps),
    )

    # voice_description (Voice Design) and reference-audio cloning are
    # alternative modes β€” only clone when no per-row description was given.
    if ref_wav_path and not (voice_description and voice_description.strip()):
        kwargs["reference_wav_path"] = ref_wav_path
        if ref_text and ref_text.strip():
            # transcript + reference wav given -> ultimate cloning mode
            kwargs["prompt_wav_path"] = ref_wav_path
            kwargs["prompt_text"] = ref_text.strip()

    wav = model.generate(**kwargs)
    return np.asarray(wav)


# ---------------------------------------------------------------------------
# Batch orchestration (runs on CPU, calls the GPU function per row so we are
# not bound by a single ZeroGPU call's duration limit)
# ---------------------------------------------------------------------------
N_SAMPLES = 10  # how many generated rows to preview inline after a run


def run_batch(
    file,
    ref_audio,
    ref_text,
    cfg_value,
    inference_timesteps,
    progress=gr.Progress(),
):
    if file is None:
        raise gr.Error("Please upload a text file (CSV / JSON / XLSX) first.")

    df = load_table(file)
    if len(df) == 0:
        raise gr.Error("No valid text rows found in the uploaded file.")

    work_dir = tempfile.mkdtemp(prefix="voxcpm_batch_")
    audio_dir = os.path.join(work_dir, "audio")
    os.makedirs(audio_dir, exist_ok=True)

    records = []
    errors = []
    sample_pairs = []  # [(text, wav_path), ...] for the first N_SAMPLES successes

    rows = list(df.iterrows())
    for _, row in progress.tqdm(rows, desc="Generating speech"):
        rid = str(row["id"])
        text = row["text"]
        lang = row["language"]  # "en" or "km", kept for metadata/labeling only
        vdesc = row.get("voice_description", "")
        fname = f"{rid}.wav"
        fpath = os.path.join(audio_dir, fname)

        try:
            wav = _generate_one(text, vdesc, ref_audio, ref_text, cfg_value, inference_timesteps)
            sf.write(fpath, wav, SAMPLE_RATE)
            duration = float(len(wav)) / SAMPLE_RATE
            records.append(
                {
                    "file_name": f"audio/{fname}",
                    "id": rid,
                    "language": lang,
                    "text": text,
                    "voice_description": vdesc,
                    "duration_sec": round(duration, 3),
                }
            )
            if len(sample_pairs) < N_SAMPLES:
                sample_pairs.append((text, fpath))
        except Exception as e:
            errors.append(f"{rid} ({lang}): {e}")

    meta_df = pd.DataFrame(records)
    meta_csv_path = os.path.join(work_dir, "metadata.csv")
    meta_df.to_csv(meta_csv_path, index=False, encoding="utf-8")

    meta_json_path = os.path.join(work_dir, "metadata.json")
    meta_df.to_json(meta_json_path, orient="records", force_ascii=False, indent=2)

    zip_path = os.path.join(tempfile.gettempdir(), f"voxcpm_output_{uuid.uuid4().hex[:8]}.zip")
    with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
        for root, _, files in os.walk(work_dir):
            for fn in files:
                full = os.path.join(root, fn)
                arc = os.path.relpath(full, work_dir)
                zf.write(full, arc)

    status = f"βœ… Done: **{len(records)}** file(s) generated."
    if errors:
        status += f"\n\n⚠️ {len(errors)} failed:\n" + "\n".join(f"- {e}" for e in errors[:15])

    # build fixed-length update lists for the N_SAMPLES (text, audio) preview slots
    sample_updates = []
    for i in range(N_SAMPLES):
        if i < len(sample_pairs):
            t, wav_path = sample_pairs[i]
            sample_updates.append(gr.update(value=t, visible=True))
            sample_updates.append(gr.update(value=wav_path, visible=True))
        else:
            sample_updates.append(gr.update(value="", visible=False))
            sample_updates.append(gr.update(value=None, visible=False))

    return [zip_path, meta_df, status] + sample_updates


# ---------------------------------------------------------------------------
# UI
# ---------------------------------------------------------------------------
with gr.Blocks(title="Tool ASR Generate") as demo:

    with gr.Sidebar():
        gr.Markdown("## πŸŽ™οΈ Reference Voice")
        gr.Markdown(
            "Optional. Upload a short clip to clone that voice for every row "
            "(works for both English and Khmer text). A per-row "
            "`voice_description` in your file overrides this for that row."
        )
        ref_audio = gr.Audio(label="Reference clip", type="filepath")
        ref_text = gr.Textbox(
            label="Reference transcript (optional, improves cloning quality)",
            placeholder="Exact transcript of the reference clip above",
            lines=3,
        )
        gr.Markdown("## βš™οΈ Generation settings")
        cfg_value = gr.Slider(0.5, 4.0, value=2.0, step=0.1, label="CFG value")
        inference_timesteps = gr.Slider(4, 30, value=10, step=1, label="Inference timesteps")

    gr.Markdown(
        """
        # 🌍 Tool ASR Generate β€” Batch Text-to-Speech (VoxCPM2, ZeroGPU)
        ### Focused on πŸ‡°πŸ‡­ Khmer and πŸ‡¬πŸ‡§ English
        Upload a **CSV / JSON / XLSX** file with a `text` column and generate speech for
        every row using [openbmb/VoxCPM2](https://huggingface.co/openbmb/VoxCPM2).
        Set the reference voice and generation settings in the sidebar. When it's done,
        download a ZIP with all the audio + a `metadata.csv` / `metadata.json` manifest,
        ready to push to a Hugging Face Dataset repo.
        """
    )

    file_in = gr.File(
        label="Upload text file (.csv / .json / .xlsx)",
        file_types=[".csv", ".json", ".xlsx", ".xls"],
    )

    preview_df = gr.Dataframe(label="Preview (first 20 rows)", interactive=False)
    preview_status = gr.Markdown()
    file_in.change(preview_file, inputs=file_in, outputs=[preview_df, preview_status])

    generate_btn = gr.Button("πŸš€ Generate All", variant="primary")

    result_zip = gr.File(label="Download ZIP (audio/ + metadata.csv + metadata.json)")
    result_meta = gr.Dataframe(label="Generated metadata")
    run_status = gr.Markdown()

    gr.Markdown("### πŸ”Š Sample preview (first 10 generated rows)")
    sample_components = []
    for i in range(N_SAMPLES):
        with gr.Row():
            t = gr.Textbox(label=f"Text {i + 1}", interactive=False, scale=3, visible=False)
            a = gr.Audio(label=f"Audio {i + 1}", interactive=False, scale=2, visible=False)
        sample_components.append(t)
        sample_components.append(a)

    generate_btn.click(
        run_batch,
        inputs=[file_in, ref_audio, ref_text, cfg_value, inference_timesteps],
        outputs=[result_zip, result_meta, run_status] + sample_components,
    )

demo.queue(max_size=10, default_concurrency_limit=1).launch()