File size: 2,369 Bytes
d1999e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import asyncio
import edge_tts
import pandas as pd
import os
from tqdm import tqdm  # progress bar

# ================= Configuration =================
INPUT_FILE = ""  
OUTPUT_DIR = ""    
VOICE = "en-US-GuyNeural"                                  
# ===========================================

async def generate_speech(code, text, output_path):
    """
    Generate one speech clip.
    """
    try:
        communicate = edge_tts.Communicate(text, VOICE)
        await communicate.save(output_path)
        # Use tqdm.write instead of print so the progress bar layout stays intact
        tqdm.write(f"[OK] Saved {code}.mp3")
        return True
    except Exception as e:
        tqdm.write(f"[FAIL] {code}.mp3: {e}")
        return False

async def amain():
    # 1. Ensure output directory exists
    if not os.path.exists(OUTPUT_DIR):
        os.makedirs(OUTPUT_DIR)
        tqdm.write(f"Created output directory: {OUTPUT_DIR}")

    # 2. Load Excel
    try:
        df = pd.read_excel(INPUT_FILE)
        # Strip column names
        df.columns = df.columns.str.strip()
        if 'code' not in df.columns or 'sentence' not in df.columns:
            tqdm.write("Error: Excel must contain 'code' and 'sentence' columns")
            return
    except FileNotFoundError:
        tqdm.write(f"Error: file not found: {INPUT_FILE}")
        return
    except Exception as e:
        tqdm.write(f"Error reading Excel: {e}")
        return

    total_count = len(df)
    tqdm.write(f"Starting: {total_count} row(s)...")

    # 3. Iterate rows with tqdm
    # desc: label on the left of the bar
    # unit: bar unit
    # total: row count for percentage
    for index, row in tqdm(df.iterrows(), total=total_count, desc="Progress", unit="row"):
        code = str(row['code']).strip()
        sentence = str(row['sentence']).strip()

        # Skip empty sentences
        if not sentence:
            tqdm.write(f"[SKIP] row {index}: empty sentence")
            continue

        # Sanitize code for use in filenames
        safe_code = "".join([c for c in code if c not in r'\/:*?"<>|'])
        
        # Output path
        output_file = os.path.join(OUTPUT_DIR, f"{safe_code}.mp3")

        # Synthesize
        await generate_speech(safe_code, sentence, output_file)

    tqdm.write("All tasks finished.")

if __name__ == "__main__":
    asyncio.run(amain())