|
1 | 1 | import csv |
2 | 2 | import os |
3 | 3 | import subprocess |
| 4 | +import sys |
| 5 | +from pathlib import Path |
4 | 6 | from dotenv import load_dotenv |
5 | 7 | from elevenlabs.client import ElevenLabs |
6 | 8 | from elevenlabs import play |
7 | 9 |
|
| 10 | +from rich.console import Console, Group |
| 11 | +from rich.live import Live |
| 12 | +from rich.progress import ( |
| 13 | + BarColumn, |
| 14 | + Progress, |
| 15 | + TaskProgressColumn, |
| 16 | + TextColumn, |
| 17 | + TimeElapsedColumn, |
| 18 | + TimeRemainingColumn, |
| 19 | +) |
| 20 | +from rich.text import Text |
| 21 | + |
8 | 22 | load_dotenv() |
9 | 23 | client = ElevenLabs() |
10 | 24 |
|
|
25 | 39 | # Add other languages here |
26 | 40 | ] |
27 | 41 |
|
28 | | -for csv_file, voice_name, output_dir in languages: |
29 | | - print(f"\nProcesing file {csv_file}") |
| 42 | +in_ci = os.environ.get("GITHUB_ACTIONS", "").lower() == "true" |
| 43 | +total_files = len(languages) |
30 | 44 |
|
31 | | - with open(csv_file, newline="", encoding="utf-8") as f: |
32 | | - reader = csv.DictReader(f) |
| 45 | +def process_csv_file(csv_file: str, voice_name: str, output_dir: str, processed_files: int, total_files: int) -> None: |
| 46 | + """Process a single CSV file.""" |
| 47 | + console = Console(force_terminal=not in_ci, no_color=in_ci) |
| 48 | + progress = Progress( |
| 49 | + TextColumn("[bold blue]{task.description}"), |
| 50 | + TextColumn("{task.fields[status]}", justify="left"), |
| 51 | + BarColumn(bar_width=None), |
| 52 | + TaskProgressColumn(), |
| 53 | + TimeElapsedColumn(), |
| 54 | + TimeRemainingColumn(), |
| 55 | + console=console, |
| 56 | + transient=False, |
| 57 | + expand=True, |
| 58 | + ) |
33 | 59 |
|
34 | | - for row in reader: |
35 | | - if not row.get("Filename") or row.get("String ID", "").startswith("#"): |
36 | | - continue |
| 60 | + class StatusLine: |
| 61 | + def __init__(self) -> None: |
| 62 | + self.message = "" |
37 | 63 |
|
38 | | - name = row["Filename"].split('.')[0] |
39 | | - tr = row.get("Translation", "") |
40 | | - subd = row.get("Path", "") # Subdirectory |
| 64 | + def update(self, message: str) -> None: |
| 65 | + self.message = message |
41 | 66 |
|
42 | | - full_dir = os.path.join("SOUNDS", output_dir, subd) |
43 | | - os.makedirs(full_dir, exist_ok=True) |
44 | | - output_mp3 = os.path.join(full_dir, f"{name}.mp3") |
45 | | - output_wav = os.path.join(full_dir, f"{name}.wav") |
| 67 | + def __rich_console__(self, console, options): |
| 68 | + yield Text(self.message) |
46 | 69 |
|
47 | | - # To save free tokens available on Elevenlabs - skip existing files to avoid double generating |
48 | | - if os.path.exists(output_wav): |
49 | | - # print(f"\n\nWAV file exist, skipping: {output_wav}") |
50 | | - continue |
| 70 | + status_line = StatusLine() |
| 71 | + layout = Group(status_line, progress) |
51 | 72 |
|
52 | | - print(f"\n\nGenerating MP3 file: {output_mp3} ...") |
| 73 | + print(f"\nProcessing file {csv_file}") |
53 | 74 |
|
54 | | - audio_generator = client.text_to_speech.convert( |
55 | | - text=tr, |
56 | | - voice_id=voice_name, |
57 | | - model_id="eleven_multilingual_v2", |
58 | | - output_format="mp3_44100_128" |
| 75 | + with open(csv_file, newline="", encoding="utf-8") as f, Live(layout, console=console, refresh_per_second=10, transient=False): |
| 76 | + reader = csv.DictReader(f) |
| 77 | + rows = list(reader) |
| 78 | + total_rows = len(rows) |
| 79 | + task_id = progress.add_task("Synthesizing", total=total_rows or None, status="") |
| 80 | + |
| 81 | + def report(msg: str) -> None: |
| 82 | + if in_ci: |
| 83 | + progress.console.print(msg) |
| 84 | + else: |
| 85 | + status_line.update(msg) |
| 86 | + progress.refresh() |
| 87 | + |
| 88 | + processed_count = 0 |
| 89 | + line_count = 0 |
| 90 | + |
| 91 | + try: |
| 92 | + for row in rows: |
| 93 | + line_count += 1 |
| 94 | + if not row.get("Filename") or row.get("String ID", "").startswith("#"): |
| 95 | + progress.update(task_id, advance=1) |
| 96 | + processed_count += 1 |
| 97 | + continue |
| 98 | + |
| 99 | + name = row["Filename"].split('.')[0] |
| 100 | + tr = row.get("Translation", "") |
| 101 | + subd = row.get("Path", "") # Subdirectory |
| 102 | + |
| 103 | + full_dir = os.path.join("SOUNDS", output_dir, subd) |
| 104 | + os.makedirs(full_dir, exist_ok=True) |
| 105 | + output_mp3 = os.path.join(full_dir, f"{name}.mp3") |
| 106 | + output_wav = os.path.join(full_dir, f"{name}.wav") |
| 107 | + |
| 108 | + # To save free tokens available on Elevenlabs - skip existing files to avoid double generating |
| 109 | + if os.path.exists(output_wav): |
| 110 | + report(f"[{line_count}/{total_rows}] Skipping \"{name}.wav\" as already exists.") |
| 111 | + progress.update(task_id, advance=1) |
| 112 | + processed_count += 1 |
| 113 | + continue |
| 114 | + |
| 115 | + report(f"[{line_count}/{total_rows}] Generating MP3 file: {output_mp3} ...") |
| 116 | + |
| 117 | + audio_generator = client.text_to_speech.convert( |
| 118 | + text=tr, |
| 119 | + voice_id=voice_name, |
| 120 | + model_id="eleven_multilingual_v2", |
| 121 | + output_format="mp3_44100_128" |
| 122 | + ) |
| 123 | + |
| 124 | + audio_bytes = b''.join(audio_generator) |
| 125 | + |
| 126 | + with open(output_mp3, "wb") as out_file: |
| 127 | + out_file.write(audio_bytes) |
| 128 | + |
| 129 | + # Conversion MP3 -> WAV using ffmpeg command |
| 130 | + skip = row.get("Skip") or "0.0" |
| 131 | + ffmpeg_cmd = [ |
| 132 | + "ffmpeg", |
| 133 | + "-ss", skip, # skip beginning in words that can be interpreted in a wrong lanuage |
| 134 | + "-y", # overwrite existing file |
| 135 | + "-i", output_mp3, |
| 136 | + "-ar", "32000", # sample rate 32 kHz |
| 137 | + "-ac", "1", # mono |
| 138 | + "-sample_fmt", "s16", # 16-bit PCM |
| 139 | + output_wav |
| 140 | + ] |
| 141 | + |
| 142 | + subprocess.run(ffmpeg_cmd, check=True) |
| 143 | + |
| 144 | + # Remove temporary mp3 file |
| 145 | + if os.path.exists(output_mp3): |
| 146 | + os.remove(output_mp3) |
| 147 | + |
| 148 | + progress.update(task_id, advance=1) |
| 149 | + processed_count += 1 |
| 150 | + except KeyboardInterrupt: |
| 151 | + report( |
| 152 | + f"Interrupted. Processed {processed_files}/{total_files} files; {processed_count}/{total_rows} entries in current file." |
59 | 153 | ) |
60 | | - |
61 | | - audio_bytes = b''.join(audio_generator) |
62 | | - |
63 | | - with open(output_mp3, "wb") as out_file: |
64 | | - out_file.write(audio_bytes) |
65 | | - |
66 | | - print(f"MP3 saved: {output_mp3}") |
67 | | - |
68 | | - |
69 | | - |
70 | | - # Conversion MP# -> WAV using ffmpeg command |
71 | | - skip = row.get("Skip") or "0.0" |
72 | | - ffmpeg_cmd = [ |
73 | | - "ffmpeg", |
74 | | - "-ss", skip, # skip beginning in words that can be interpreted in a wrong lanuage |
75 | | - "-y", # overwrite existing file |
76 | | - "-i", output_mp3, |
77 | | - "-ar", "32000", # sample rate 32 kHz |
78 | | - "-ac", "1", # mono |
79 | | - "-sample_fmt", "s16", # 16-bit PCM |
80 | | - output_wav |
81 | | - ] |
82 | | - |
83 | | - subprocess.run(ffmpeg_cmd, check=True) |
84 | | - print(f"WAV for EdgeTX saved: {output_wav}") |
85 | | - |
86 | | - # Remove temporary mp3 file |
87 | | - if os.path.exists(output_mp3): |
88 | | - os.remove(output_mp3) |
| 154 | + progress.update(task_id, completed=processed_count) |
| 155 | + raise SystemExit(1) |
| 156 | + |
| 157 | + report( |
| 158 | + f'Finished processing {processed_files}/{total_files} files ({processed_count}/{total_rows} entries) in "{csv_file}".') |
| 159 | + |
| 160 | +for idx, (csv_file, voice_name, output_dir) in enumerate(languages, 1): |
| 161 | + try: |
| 162 | + process_csv_file(csv_file, voice_name, output_dir, idx, total_files) |
| 163 | + except SystemExit as e: |
| 164 | + if e.code == 1: |
| 165 | + print("\nProcessing interrupted by user.") |
| 166 | + sys.exit(1) |
| 167 | + raise |
89 | 168 |
|
90 | 169 |
|
0 commit comments