SohomToom commited on
Commit
235e7c7
·
verified ·
1 Parent(s): 59d129e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +75 -78
app.py CHANGED
@@ -1,11 +1,14 @@
1
  import os
2
  os.environ["NUMBA_DISABLE_CACHE"] = "1"
3
 
 
4
  import gradio as gr
5
  from docx import Document
6
  from TTS.api import TTS
7
  import tempfile
8
  import zipfile
 
 
9
 
10
  # Voice model
11
  VOICE_MODEL = "tts_models/en/vctk/vits"
@@ -105,91 +108,85 @@ SPEAKER_METADATA = {
105
 
106
 
107
 
108
- # Return dropdown list like: "p225 - F, English"
109
- def get_speaker_dropdown_choices():
110
- choices = []
111
- for speaker_id, meta in SPEAKER_METADATA.items():
112
- desc = f"p{speaker_id} - {meta['gender']}, {meta['accent']}"
113
- choices.append((desc, f"p{speaker_id}"))
114
- return choices
115
-
116
- # Cache TTS model
117
- MODEL_CACHE = {}
118
-
119
- def load_tts_model():
120
- if VOICE_MODEL not in MODEL_CACHE:
121
- MODEL_CACHE[VOICE_MODEL] = TTS(model_name=VOICE_MODEL, progress_bar=False, gpu=False)
122
- return MODEL_CACHE[VOICE_MODEL]
123
-
124
- def docx_to_wav(doc_file, selected_desc):
125
- speaker_id = next((sid for desc, sid in get_speaker_dropdown_choices() if desc == selected_desc), None)
126
- if not speaker_id:
127
- raise ValueError("Invalid speaker selection")
128
-
129
- tts = load_tts_model()
130
- document = Document(doc_file.name)
131
- full_text = "\n".join([para.text for para in document.paragraphs if para.text.strip()])
132
-
 
133
  with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp_wav:
134
- wav_path = tmp_wav.name
135
-
136
- tts.tts_to_file(text=full_text, file_path=wav_path, speaker=speaker_id)
137
- return wav_path
138
-
139
-
140
- def docx_to_zipped_wavs(doc_file, selected_desc):
141
- speaker_id = next((sid for desc, sid in get_speaker_dropdown_choices() if desc == selected_desc), None)
142
- if not speaker_id:
143
- raise ValueError("Invalid speaker selection")
144
-
145
- tts = load_tts_model()
146
- document = Document(doc_file.name)
147
- paragraphs = [p.text.strip() for p in document.paragraphs if p.text.strip()]
148
-
149
- if not paragraphs:
150
- raise ValueError("No non-empty paragraphs found in the document.")
 
 
 
 
 
 
 
 
 
 
 
 
 
151
 
152
- with tempfile.TemporaryDirectory() as temp_dir:
153
- wav_paths = []
154
- for i, para in enumerate(paragraphs, start=1):
155
- wav_path = os.path.join(temp_dir, f"chunk_{i:02d}.wav")
156
- tts.tts_to_file(text=para, file_path=wav_path, speaker=speaker_id)
157
- wav_paths.append(wav_path)
158
 
159
- # Create a zip file
160
- zip_path = os.path.join(temp_dir, "voice_chunks.zip")
161
- with zipfile.ZipFile(zip_path, "w") as zipf:
162
- for wav in wav_paths:
163
- zipf.write(wav, os.path.basename(wav))
164
 
165
- # Copy zip to a final temp file for Gradio to return
166
- final_zip = tempfile.NamedTemporaryFile(suffix=".zip", delete=False)
167
- with open(zip_path, "rb") as src, open(final_zip.name, "wb") as dst:
168
- dst.write(src.read())
169
 
170
- return final_zip.name
 
 
171
 
 
172
 
173
- # Gradio UI
174
- with gr.Blocks() as interface:
175
- gr.Markdown("# 🎤 English Voice Generator from DOCX")
176
- gr.Markdown("Upload a `.docx` file and select a speaker to generate a WAV voiceover.")
177
-
178
- doc_input = gr.File(label="Upload .docx File", type="filepath")
179
- speaker_dropdown = gr.Dropdown(
180
- choices=[desc for desc, _ in get_speaker_dropdown_choices()],
181
- label="Select Speaker",
182
- value=None
183
- )
184
-
185
- generate_btn = gr.Button("Generate WAV")
186
- #output_audio = gr.Audio(label="Generated Audio", type="filepath")
187
-
188
- generate_btn.click(
189
- fn=docx_to_zipped_wavs,
190
- inputs=[doc_input, speaker_dropdown],
191
- outputs=gr.File(label="Download ZIP of Audio Files")
192
- )
193
 
194
  if __name__ == "__main__":
195
  interface.launch()
 
1
  import os
2
  os.environ["NUMBA_DISABLE_CACHE"] = "1"
3
 
4
+ import os
5
  import gradio as gr
6
  from docx import Document
7
  from TTS.api import TTS
8
  import tempfile
9
  import zipfile
10
+ from io import BytesIO
11
+ import re
12
 
13
  # Voice model
14
  VOICE_MODEL = "tts_models/en/vctk/vits"
 
108
 
109
 
110
 
111
+ # Static list of speakers for dropdown
112
+ SPEAKER_CHOICES = [
113
+ f"{sid} - {data['gender']} - {data['accent']} (Age {data['age']})"
114
+ for sid, data in SPEAKER_METADATA.items()
115
+ ]
116
+
117
+ # VCTK model (multi-speaker)
118
+ MODEL_NAME = "tts_models/en/vctk/vits"
119
+ tts = TTS(model_name=MODEL_NAME, progress_bar=False, gpu=False)
120
+
121
+ # Extract plain text from docx, ignoring hyperlinks
122
+ def extract_text_ignoring_hyperlinks(docx_file):
123
+ doc = Document(docx_file.name)
124
+ text_blocks = []
125
+ for para in doc.paragraphs:
126
+ # Remove hyperlinks using regex or by inspecting runs
127
+ if para.text.strip():
128
+ clean_text = re.sub(r'https?://\S+', '', para.text)
129
+ text_blocks.append(clean_text.strip())
130
+ return text_blocks
131
+
132
+ # Generate sample audio for preview
133
+ def generate_sample_audio(sample_text, selected_speaker):
134
+ if not sample_text.strip():
135
+ raise gr.Error("Sample text cannot be empty.")
136
+ sid = selected_speaker.split(" ")[0] # Extract speaker ID
137
  with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp_wav:
138
+ tts.tts_to_file(text=sample_text, speaker=sid, file_path=tmp_wav.name)
139
+ return tmp_wav.name
140
+
141
+ # Main conversion function
142
+ def docx_to_zipped_wavs(doc_file, selected_speaker):
143
+ sid = selected_speaker.split(" ")[0]
144
+ paragraphs = extract_text_ignoring_hyperlinks(doc_file)
145
+ audio_files = []
146
+ try:
147
+ for i, para in enumerate(paragraphs):
148
+ if not para:
149
+ continue
150
+ with tempfile.NamedTemporaryFile(suffix=f"_{i}.wav", delete=False) as tmp_wav:
151
+ tts.tts_to_file(text=para, speaker=sid, file_path=tmp_wav.name)
152
+ audio_files.append(tmp_wav.name)
153
+ except Exception as e:
154
+ print("Connection interrupted, returning partial result.", str(e))
155
+
156
+ # Zip the results
157
+ zip_buffer = BytesIO()
158
+ with zipfile.ZipFile(zip_buffer, "w") as zipf:
159
+ for wav_path in audio_files:
160
+ zipf.write(wav_path, arcname=os.path.basename(wav_path))
161
+ zip_buffer.seek(0)
162
+
163
+ # Save the zip temporarily for download
164
+ final_zip = tempfile.NamedTemporaryFile(delete=False, suffix=".zip")
165
+ final_zip.write(zip_buffer.read())
166
+ final_zip.close()
167
+ return final_zip.name
168
 
169
+ # Gradio UI
170
+ with gr.Blocks() as interface:
171
+ gr.Markdown("""# Multi-Paragraph Voiceover Generator
172
+ Upload a `.docx` file and convert each paragraph to audio. You can also try a short sample first.
173
+ """)
 
174
 
175
+ with gr.Row():
176
+ sample_text = gr.Textbox(label="Sample Text (Max 500 chars)", max_lines=4, lines=3, max_length=500)
177
+ speaker_dropdown = gr.Dropdown(label="Select Speaker", choices=SPEAKER_CHOICES, value=SPEAKER_CHOICES[0])
 
 
178
 
179
+ sample_button = gr.Button("Generate Sample Audio")
180
+ sample_audio = gr.Audio(label="Sample Audio", type="filepath")
 
 
181
 
182
+ with gr.Row():
183
+ docx_input = gr.File(label="Upload .docx File", type="filepath")
184
+ convert_button = gr.Button("Generate WAV Zip")
185
 
186
+ final_output = gr.File(label="Download ZIP of WAVs")
187
 
188
+ sample_button.click(fn=generate_sample_audio, inputs=[sample_text, speaker_dropdown], outputs=sample_audio)
189
+ convert_button.click(fn=docx_to_zipped_wavs, inputs=[docx_input, speaker_dropdown], outputs=final_output)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
190
 
191
  if __name__ == "__main__":
192
  interface.launch()