Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,7 +3,6 @@ from transformers import pipeline
|
|
| 3 |
import torch
|
| 4 |
import subprocess
|
| 5 |
import os
|
| 6 |
-
from moviepy.editor import VideoFileClip
|
| 7 |
import tempfile
|
| 8 |
import shutil
|
| 9 |
|
|
@@ -19,8 +18,8 @@ print(f"Using dtype: {torch_dtype}")
|
|
| 19 |
pipe = pipeline(
|
| 20 |
"automatic-speech-recognition",
|
| 21 |
"openai/whisper-large-v3-turbo",
|
| 22 |
-
torch_dtype=torch_dtype,
|
| 23 |
-
device=device
|
| 24 |
)
|
| 25 |
|
| 26 |
print(f"Whisper Large V3 Turbo loaded on {device}")
|
|
@@ -40,28 +39,55 @@ except Exception as e:
|
|
| 40 |
def format_srt_time(seconds):
|
| 41 |
h = int(seconds // 3600)
|
| 42 |
m = int((seconds % 3600) // 60)
|
| 43 |
-
s =
|
| 44 |
-
|
| 45 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
|
| 47 |
def process_video(video_file, language="hindi", progress=gr.Progress()):
|
|
|
|
|
|
|
| 48 |
if not video_file:
|
| 49 |
return None, None, "Please upload a video"
|
| 50 |
|
| 51 |
-
|
| 52 |
-
output_dir = tempfile.mkdtemp() # Separate directory for outputs
|
| 53 |
-
print(f"Processing in temp directory: {temp_dir}")
|
| 54 |
print(f"Output directory: {output_dir}")
|
| 55 |
|
| 56 |
try:
|
| 57 |
-
# Extract audio
|
| 58 |
progress(0.2, desc="Extracting audio...")
|
| 59 |
-
|
| 60 |
|
| 61 |
-
|
| 62 |
video = VideoFileClip(video_file)
|
|
|
|
| 63 |
if not video.audio:
|
| 64 |
-
shutil.rmtree(temp_dir, ignore_errors=True)
|
| 65 |
shutil.rmtree(output_dir, ignore_errors=True)
|
| 66 |
return None, None, "Video has no audio track"
|
| 67 |
|
|
@@ -74,243 +100,62 @@ def process_video(video_file, language="hindi", progress=gr.Progress()):
|
|
| 74 |
logger=None
|
| 75 |
)
|
| 76 |
video.close()
|
| 77 |
-
print(f"Audio extracted: {audio_path}
|
| 78 |
-
|
| 79 |
-
# Transcribe - keep chunk_length_s for full audio, but simplify everything else
|
| 80 |
-
progress(0.4, desc="Transcribing with Whisper Turbo...")
|
| 81 |
-
print(f"Starting transcription (language: {language})...")
|
| 82 |
-
|
| 83 |
-
transcription_result = pipe(
|
| 84 |
-
audio_path,
|
| 85 |
-
return_timestamps=True,
|
| 86 |
-
chunk_length_s=30, # Keep this to process full audio
|
| 87 |
-
generate_kwargs={
|
| 88 |
-
"language": language if language != "auto" else None,
|
| 89 |
-
"task": "transcribe"
|
| 90 |
-
}
|
| 91 |
-
)
|
| 92 |
-
|
| 93 |
-
print(f"Transcription result keys: {transcription_result.keys()}")
|
| 94 |
-
|
| 95 |
-
# Verify we have chunks
|
| 96 |
-
if not transcription_result.get('chunks') or len(transcription_result['chunks']) == 0:
|
| 97 |
-
error_msg = f"Transcription returned no segments"
|
| 98 |
-
print(error_msg)
|
| 99 |
-
shutil.rmtree(temp_dir, ignore_errors=True)
|
| 100 |
-
shutil.rmtree(output_dir, ignore_errors=True)
|
| 101 |
-
return None, None, error_msg
|
| 102 |
|
| 103 |
-
|
|
|
|
|
|
|
| 104 |
|
| 105 |
-
#
|
| 106 |
-
|
| 107 |
-
for i, chunk in enumerate(transcription_result['chunks'][:3], 1):
|
| 108 |
-
print(f" {i}: {chunk}")
|
| 109 |
-
print(f"\nLast 3 chunks:")
|
| 110 |
-
for i, chunk in enumerate(transcription_result['chunks'][-3:], len(transcription_result['chunks'])-2):
|
| 111 |
-
print(f" {i}: {chunk}")
|
| 112 |
-
|
| 113 |
-
# Post-process: Split overly long chunks for better readability
|
| 114 |
-
processed_chunks = []
|
| 115 |
-
max_chunk_duration = 5.0 # Maximum 5 seconds per subtitle
|
| 116 |
-
max_words_per_chunk = 15 # Maximum words per subtitle
|
| 117 |
-
|
| 118 |
-
for chunk in transcription_result['chunks']:
|
| 119 |
-
start, end = chunk['timestamp']
|
| 120 |
-
text = chunk['text'].strip()
|
| 121 |
-
duration = end - start
|
| 122 |
-
words = text.split()
|
| 123 |
-
|
| 124 |
-
# If chunk is short enough, keep as is
|
| 125 |
-
if duration <= max_chunk_duration and len(words) <= max_words_per_chunk:
|
| 126 |
-
processed_chunks.append(chunk)
|
| 127 |
-
else:
|
| 128 |
-
# Split long chunk into smaller pieces
|
| 129 |
-
words_per_split = max(5, len(words) // max(2, int(duration / max_chunk_duration)))
|
| 130 |
-
time_per_word = duration / len(words)
|
| 131 |
-
|
| 132 |
-
for i in range(0, len(words), words_per_split):
|
| 133 |
-
split_words = words[i:i + words_per_split]
|
| 134 |
-
split_start = start + (i * time_per_word)
|
| 135 |
-
split_end = start + ((i + len(split_words)) * time_per_word)
|
| 136 |
-
|
| 137 |
-
processed_chunks.append({
|
| 138 |
-
'timestamp': (split_start, split_end),
|
| 139 |
-
'text': ' '.join(split_words)
|
| 140 |
-
})
|
| 141 |
-
|
| 142 |
-
print(f"After splitting long chunks: {len(processed_chunks)} segments")
|
| 143 |
-
|
| 144 |
-
# Use processed chunks instead of original
|
| 145 |
-
transcription_result['chunks'] = processed_chunks
|
| 146 |
-
|
| 147 |
-
# Create SRT in output directory (persistent)
|
| 148 |
-
progress(0.6, desc="Creating SRT...")
|
| 149 |
srt_path = os.path.join(output_dir, "subtitles.srt")
|
|
|
|
|
|
|
|
|
|
| 150 |
|
| 151 |
-
|
| 152 |
-
print(f"Total chunks to process: {len(transcription_result['chunks'])}")
|
| 153 |
-
|
| 154 |
-
# Use EXACT approach from your working code - NO modifications
|
| 155 |
-
try:
|
| 156 |
-
with open(srt_path, 'w', encoding='utf-8-sig') as f:
|
| 157 |
-
if 'chunks' in transcription_result:
|
| 158 |
-
for i, chunk in enumerate(transcription_result['chunks'], start=1):
|
| 159 |
-
start, end = chunk['timestamp']
|
| 160 |
-
text = chunk['text'].strip()
|
| 161 |
-
|
| 162 |
-
f.write(f"{i}\n")
|
| 163 |
-
f.write(f"{format_srt_time(start)} --> {format_srt_time(end)}\n")
|
| 164 |
-
f.write(f"{text}\n\n")
|
| 165 |
-
else:
|
| 166 |
-
# Fallback if no chunks
|
| 167 |
-
f.write("1\n")
|
| 168 |
-
f.write("00:00:00,000 --> 00:00:10,000\n")
|
| 169 |
-
f.write(f"{transcription_result.get('text', '')}\n\n")
|
| 170 |
-
|
| 171 |
-
print(f"SRT file created with {len(transcription_result['chunks'])} entries")
|
| 172 |
-
|
| 173 |
-
except Exception as e:
|
| 174 |
-
print(f"Error creating SRT: {e}")
|
| 175 |
-
import traceback
|
| 176 |
-
print(traceback.format_exc())
|
| 177 |
-
raise
|
| 178 |
-
|
| 179 |
-
# Verify SRT was created and show preview
|
| 180 |
-
if not os.path.exists(srt_path):
|
| 181 |
-
shutil.rmtree(temp_dir, ignore_errors=True)
|
| 182 |
-
shutil.rmtree(output_dir, ignore_errors=True)
|
| 183 |
-
return None, None, f"SRT file was not created at: {srt_path}"
|
| 184 |
-
|
| 185 |
-
srt_size = os.path.getsize(srt_path)
|
| 186 |
-
if srt_size == 0:
|
| 187 |
-
shutil.rmtree(temp_dir, ignore_errors=True)
|
| 188 |
-
shutil.rmtree(output_dir, ignore_errors=True)
|
| 189 |
-
return None, None, f"SRT file is empty at: {srt_path}"
|
| 190 |
-
|
| 191 |
-
print(f"SRT created successfully: {srt_path} ({srt_size} bytes)")
|
| 192 |
-
|
| 193 |
-
# Show first few SRT entries for debugging
|
| 194 |
-
with open(srt_path, 'r', encoding='utf-8-sig') as f:
|
| 195 |
-
srt_content = f.read()
|
| 196 |
-
srt_lines = srt_content.split('\n\n')
|
| 197 |
-
print(f"\nTotal SRT entries: {len(srt_lines)}")
|
| 198 |
-
print(f"\nFirst 3 SRT entries:")
|
| 199 |
-
for entry in srt_lines[:3]:
|
| 200 |
-
print(f"---\n{entry}\n")
|
| 201 |
-
print(f"\nLast 3 SRT entries:")
|
| 202 |
-
for entry in srt_lines[-3:]:
|
| 203 |
-
print(f"---\n{entry}\n")
|
| 204 |
-
|
| 205 |
-
# Burn subtitles
|
| 206 |
-
progress(0.85, desc="Burning subtitles...")
|
| 207 |
-
output_path = os.path.join(output_dir, "final.mp4")
|
| 208 |
-
|
| 209 |
-
print("Burning subtitles with FFmpeg...")
|
| 210 |
-
|
| 211 |
-
# Convert SRT to ASS first (more reliable with FFmpeg)
|
| 212 |
ass_path = os.path.join(output_dir, "subtitles.ass")
|
| 213 |
-
|
| 214 |
-
print(f"Converting SRT to ASS for better compatibility...")
|
| 215 |
subprocess.run([
|
| 216 |
'ffmpeg', '-y',
|
| 217 |
'-i', srt_path,
|
| 218 |
ass_path
|
| 219 |
-
], check=True, capture_output=True
|
|
|
|
| 220 |
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
raise Exception(f"Failed to create ASS file at {ass_path}")
|
| 225 |
-
|
| 226 |
-
print(f"ASS file created: {ass_path} ({os.path.getsize(ass_path)} bytes)")
|
| 227 |
|
| 228 |
-
# Use
|
| 229 |
-
|
|
|
|
| 230 |
|
| 231 |
-
|
| 232 |
'ffmpeg', '-y',
|
| 233 |
'-i', video_file,
|
| 234 |
-
'-vf', f"ass={
|
| 235 |
'-c:a', 'copy',
|
| 236 |
'-c:v', 'libx264',
|
| 237 |
'-preset', 'medium',
|
| 238 |
'-crf', '23',
|
| 239 |
output_path
|
| 240 |
-
]
|
| 241 |
-
|
| 242 |
-
print(f"FFmpeg command: {' '.join(ffmpeg_cmd)}")
|
| 243 |
-
|
| 244 |
-
subprocess.run(
|
| 245 |
-
ffmpeg_cmd,
|
| 246 |
-
check=True,
|
| 247 |
-
capture_output=True,
|
| 248 |
-
text=True,
|
| 249 |
-
timeout=600
|
| 250 |
-
)
|
| 251 |
-
|
| 252 |
-
if not os.path.exists(output_path):
|
| 253 |
-
shutil.rmtree(temp_dir, ignore_errors=True)
|
| 254 |
-
shutil.rmtree(output_dir, ignore_errors=True)
|
| 255 |
-
return None, None, f"Output video was not created at: {output_path}"
|
| 256 |
|
| 257 |
-
print(f"Video created: {output_path}
|
| 258 |
|
| 259 |
progress(1.0, desc="Complete!")
|
| 260 |
|
| 261 |
-
#
|
| 262 |
-
|
| 263 |
-
for i, chunk in enumerate(transcription_result['chunks'][:10], 1):
|
| 264 |
-
text = chunk['text'].strip()
|
| 265 |
-
start_time = chunk['timestamp'][0]
|
| 266 |
-
end_time = chunk['timestamp'][1]
|
| 267 |
-
preview_lines.append(f"{i}. [{start_time:.1f}s - {end_time:.1f}s] {text}")
|
| 268 |
-
|
| 269 |
-
preview_text = "\n".join(preview_lines)
|
| 270 |
-
full_text = " ".join([c['text'].strip() for c in transcription_result['chunks']])
|
| 271 |
|
| 272 |
-
status = f"""Processing Complete!
|
| 273 |
-
Statistics:
|
| 274 |
-
- Model: Whisper Large V3 Turbo
|
| 275 |
-
- Device: {device}
|
| 276 |
-
- Segments: {len(transcription_result['chunks'])}
|
| 277 |
-
- Duration: {transcription_result['chunks'][-1]['timestamp'][1]:.1f}s
|
| 278 |
-
- Language: {language}
|
| 279 |
-
|
| 280 |
-
Preview (first 10 segments with timestamps):
|
| 281 |
-
{preview_text}
|
| 282 |
-
|
| 283 |
-
Full Transcription:
|
| 284 |
-
{full_text[:500]}{"..." if len(full_text) > 500 else ""}
|
| 285 |
-
|
| 286 |
-
Files created successfully!
|
| 287 |
-
"""
|
| 288 |
-
|
| 289 |
-
# Cleanup only temp_dir, keep output_dir for Gradio
|
| 290 |
-
shutil.rmtree(temp_dir, ignore_errors=True)
|
| 291 |
-
print(f"Cleaned up temp directory: {temp_dir}")
|
| 292 |
-
|
| 293 |
-
# Return paths - Gradio needs these files to exist
|
| 294 |
-
return srt_path, output_path, status
|
| 295 |
-
|
| 296 |
-
except subprocess.TimeoutExpired:
|
| 297 |
-
shutil.rmtree(temp_dir, ignore_errors=True)
|
| 298 |
-
shutil.rmtree(output_dir, ignore_errors=True)
|
| 299 |
-
return None, None, "Processing timeout. Try a shorter video."
|
| 300 |
-
except subprocess.CalledProcessError as e:
|
| 301 |
-
shutil.rmtree(temp_dir, ignore_errors=True)
|
| 302 |
-
shutil.rmtree(output_dir, ignore_errors=True)
|
| 303 |
-
error_detail = e.stderr if hasattr(e, 'stderr') else str(e)
|
| 304 |
-
return None, None, f"FFmpeg error: {error_detail}"
|
| 305 |
except Exception as e:
|
| 306 |
-
shutil.rmtree(temp_dir, ignore_errors=True)
|
| 307 |
shutil.rmtree(output_dir, ignore_errors=True)
|
| 308 |
import traceback
|
| 309 |
error_trace = traceback.format_exc()
|
| 310 |
print(f"Error: {error_trace}")
|
| 311 |
return None, None, f"Error: {str(e)}\n\nDetails:\n{error_trace}"
|
| 312 |
|
| 313 |
-
# Gradio
|
| 314 |
with gr.Blocks(theme=gr.themes.Soft(), title="Hindi Subtitle Generator") as demo:
|
| 315 |
|
| 316 |
gr.Markdown("""
|
|
@@ -318,73 +163,79 @@ with gr.Blocks(theme=gr.themes.Soft(), title="Hindi Subtitle Generator") as demo
|
|
| 318 |
### Powered by Whisper Large V3 Turbo
|
| 319 |
""")
|
| 320 |
|
| 321 |
-
with gr.
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
video_input = gr.Video(label="Video File")
|
| 326 |
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
("
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 336 |
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
|
|
|
| 341 |
)
|
| 342 |
-
|
| 343 |
-
gr.Markdown("""
|
| 344 |
-
### Features
|
| 345 |
-
- Whisper Large V3 Turbo (5x faster)
|
| 346 |
-
- High accuracy transcription
|
| 347 |
-
- SRT file export
|
| 348 |
-
- Burned-in subtitles
|
| 349 |
-
- System-installed Devanagari fonts
|
| 350 |
-
|
| 351 |
-
### Technical Info
|
| 352 |
-
- Docker container with fonts
|
| 353 |
-
- CPU/GPU auto-detection
|
| 354 |
-
- Production ready
|
| 355 |
-
""")
|
| 356 |
|
| 357 |
-
|
| 358 |
-
|
|
|
|
| 359 |
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 365 |
|
| 366 |
-
|
| 367 |
-
|
|
|
|
|
|
|
|
|
|
| 368 |
|
| 369 |
gr.Markdown("""
|
| 370 |
---
|
| 371 |
-
###
|
| 372 |
-
|
| 373 |
-
This app uses Docker to install Devanagari fonts at the system level,
|
| 374 |
-
ensuring proper Hindi text rendering in burned subtitles.
|
| 375 |
-
""")
|
| 376 |
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 381 |
)
|
|
|
|
|
|
|
| 382 |
|
| 383 |
if __name__ == "__main__":
|
| 384 |
demo.queue(max_size=20).launch(
|
| 385 |
server_name="0.0.0.0",
|
| 386 |
server_port=7860,
|
| 387 |
share=False,
|
| 388 |
-
show_api=
|
| 389 |
show_error=True
|
| 390 |
)
|
|
|
|
| 3 |
import torch
|
| 4 |
import subprocess
|
| 5 |
import os
|
|
|
|
| 6 |
import tempfile
|
| 7 |
import shutil
|
| 8 |
|
|
|
|
| 18 |
pipe = pipeline(
|
| 19 |
"automatic-speech-recognition",
|
| 20 |
"openai/whisper-large-v3-turbo",
|
| 21 |
+
torch_dtype=torch_dtype,
|
| 22 |
+
device=device
|
| 23 |
)
|
| 24 |
|
| 25 |
print(f"Whisper Large V3 Turbo loaded on {device}")
|
|
|
|
| 39 |
def format_srt_time(seconds):
|
| 40 |
h = int(seconds // 3600)
|
| 41 |
m = int((seconds % 3600) // 60)
|
| 42 |
+
s = seconds % 60
|
| 43 |
+
return f"{h:02}:{m:02}:{int(s):02},{int((s-int(s))*1000):03}"
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def transcribe_to_srt(audio_file, language="hindi"):
|
| 47 |
+
"""Transcribe audio to SRT - matches your Gradio API exactly"""
|
| 48 |
+
|
| 49 |
+
print(f"Transcribing: {audio_file} in {language}")
|
| 50 |
+
|
| 51 |
+
# Transcribe with exact same parameters as your working code
|
| 52 |
+
result = pipe(
|
| 53 |
+
audio_file,
|
| 54 |
+
return_timestamps=True,
|
| 55 |
+
generate_kwargs={"language": language if language != "auto" else None}
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
print(f"Transcription complete: {len(result['chunks'])} chunks")
|
| 59 |
+
|
| 60 |
+
# Create SRT content - exact same format as your code
|
| 61 |
+
srt_lines = []
|
| 62 |
+
for i, chunk in enumerate(result['chunks'], 1):
|
| 63 |
+
start, end = chunk['timestamp']
|
| 64 |
+
text = chunk['text'].strip()
|
| 65 |
+
srt_lines.append(f"{i}\n{format_srt_time(start)} --> {format_srt_time(end)}\n{c['text'].strip()}\n")
|
| 66 |
+
|
| 67 |
+
srt_content = "\n".join(srt_lines)
|
| 68 |
+
preview = result['text'][:500]
|
| 69 |
+
status = f"✅ {len(result['chunks'])} segments transcribed"
|
| 70 |
+
|
| 71 |
+
return srt_content, preview, status
|
| 72 |
|
| 73 |
def process_video(video_file, language="hindi", progress=gr.Progress()):
|
| 74 |
+
"""Full video processing with subtitle burning"""
|
| 75 |
+
|
| 76 |
if not video_file:
|
| 77 |
return None, None, "Please upload a video"
|
| 78 |
|
| 79 |
+
output_dir = tempfile.mkdtemp()
|
|
|
|
|
|
|
| 80 |
print(f"Output directory: {output_dir}")
|
| 81 |
|
| 82 |
try:
|
| 83 |
+
# Step 1: Extract audio
|
| 84 |
progress(0.2, desc="Extracting audio...")
|
| 85 |
+
from moviepy.editor import VideoFileClip
|
| 86 |
|
| 87 |
+
audio_path = os.path.join(output_dir, "audio.wav")
|
| 88 |
video = VideoFileClip(video_file)
|
| 89 |
+
|
| 90 |
if not video.audio:
|
|
|
|
| 91 |
shutil.rmtree(output_dir, ignore_errors=True)
|
| 92 |
return None, None, "Video has no audio track"
|
| 93 |
|
|
|
|
| 100 |
logger=None
|
| 101 |
)
|
| 102 |
video.close()
|
| 103 |
+
print(f"Audio extracted: {audio_path}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
|
| 105 |
+
# Step 2: Transcribe - use exact same function as API
|
| 106 |
+
progress(0.5, desc="Transcribing...")
|
| 107 |
+
srt_content, preview, status = transcribe_to_srt(audio_path, language)
|
| 108 |
|
| 109 |
+
# Step 3: Save SRT
|
| 110 |
+
progress(0.7, desc="Creating subtitle files...")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
srt_path = os.path.join(output_dir, "subtitles.srt")
|
| 112 |
+
with open(srt_path, 'w', encoding='utf-8') as f:
|
| 113 |
+
f.write(srt_content)
|
| 114 |
+
print(f"SRT saved: {srt_path}")
|
| 115 |
|
| 116 |
+
# Step 4: Convert to ASS
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
ass_path = os.path.join(output_dir, "subtitles.ass")
|
|
|
|
|
|
|
| 118 |
subprocess.run([
|
| 119 |
'ffmpeg', '-y',
|
| 120 |
'-i', srt_path,
|
| 121 |
ass_path
|
| 122 |
+
], check=True, capture_output=True)
|
| 123 |
+
print(f"ASS created: {ass_path}")
|
| 124 |
|
| 125 |
+
# Step 5: Burn subtitles
|
| 126 |
+
progress(0.9, desc="Burning subtitles...")
|
| 127 |
+
output_path = os.path.join(output_dir, "final.mp4")
|
|
|
|
|
|
|
|
|
|
| 128 |
|
| 129 |
+
# Use temp file method like your code
|
| 130 |
+
temp_ass = os.path.join(output_dir, "temp.ass")
|
| 131 |
+
shutil.copy2(ass_path, temp_ass)
|
| 132 |
|
| 133 |
+
subprocess.run([
|
| 134 |
'ffmpeg', '-y',
|
| 135 |
'-i', video_file,
|
| 136 |
+
'-vf', f"ass={temp_ass}",
|
| 137 |
'-c:a', 'copy',
|
| 138 |
'-c:v', 'libx264',
|
| 139 |
'-preset', 'medium',
|
| 140 |
'-crf', '23',
|
| 141 |
output_path
|
| 142 |
+
], check=True, capture_output=True, text=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 143 |
|
| 144 |
+
print(f"Video created: {output_path}")
|
| 145 |
|
| 146 |
progress(1.0, desc="Complete!")
|
| 147 |
|
| 148 |
+
# Return paths for download
|
| 149 |
+
return srt_path, output_path, f"Processing Complete!\n\n{status}\n\nPreview:\n{preview}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 151 |
except Exception as e:
|
|
|
|
| 152 |
shutil.rmtree(output_dir, ignore_errors=True)
|
| 153 |
import traceback
|
| 154 |
error_trace = traceback.format_exc()
|
| 155 |
print(f"Error: {error_trace}")
|
| 156 |
return None, None, f"Error: {str(e)}\n\nDetails:\n{error_trace}"
|
| 157 |
|
| 158 |
+
# Gradio Interface with both API and Full Processing
|
| 159 |
with gr.Blocks(theme=gr.themes.Soft(), title="Hindi Subtitle Generator") as demo:
|
| 160 |
|
| 161 |
gr.Markdown("""
|
|
|
|
| 163 |
### Powered by Whisper Large V3 Turbo
|
| 164 |
""")
|
| 165 |
|
| 166 |
+
with gr.Tabs():
|
| 167 |
+
# Tab 1: API Mode (like your Gradio code)
|
| 168 |
+
with gr.Tab("🎙️ Audio to SRT (API)"):
|
| 169 |
+
gr.Markdown("Upload audio file to get SRT subtitle text")
|
|
|
|
| 170 |
|
| 171 |
+
with gr.Row():
|
| 172 |
+
with gr.Column():
|
| 173 |
+
api_audio = gr.Audio(sources=["upload"], type="filepath", label="Upload Audio")
|
| 174 |
+
api_lang = gr.Dropdown(
|
| 175 |
+
["hindi", "english", "auto"],
|
| 176 |
+
value="hindi",
|
| 177 |
+
label="Language"
|
| 178 |
+
)
|
| 179 |
+
api_btn = gr.Button("Generate SRT", variant="primary")
|
| 180 |
+
|
| 181 |
+
with gr.Column():
|
| 182 |
+
api_srt = gr.Textbox(label="SRT Content", lines=20)
|
| 183 |
+
api_preview = gr.Textbox(label="Preview", lines=5)
|
| 184 |
+
api_status = gr.Textbox(label="Status")
|
| 185 |
|
| 186 |
+
api_btn.click(
|
| 187 |
+
fn=transcribe_to_srt,
|
| 188 |
+
inputs=[api_audio, api_lang],
|
| 189 |
+
outputs=[api_srt, api_preview, api_status],
|
| 190 |
+
api_name="transcribe"
|
| 191 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 192 |
|
| 193 |
+
# Tab 2: Full Video Processing
|
| 194 |
+
with gr.Tab("🎬 Video with Burned Subtitles"):
|
| 195 |
+
gr.Markdown("Upload video to get subtitles burned into the video")
|
| 196 |
|
| 197 |
+
with gr.Row():
|
| 198 |
+
with gr.Column():
|
| 199 |
+
video_input = gr.Video(label="Video File")
|
| 200 |
+
video_lang = gr.Dropdown(
|
| 201 |
+
["hindi", "english", "auto"],
|
| 202 |
+
value="hindi",
|
| 203 |
+
label="Language"
|
| 204 |
+
)
|
| 205 |
+
video_btn = gr.Button("Generate Subtitles", variant="primary")
|
| 206 |
+
|
| 207 |
+
with gr.Column():
|
| 208 |
+
status_output = gr.Textbox(label="Status", lines=10)
|
| 209 |
+
srt_output = gr.File(label="Download SRT File")
|
| 210 |
+
video_output = gr.Video(label="Final Video")
|
| 211 |
|
| 212 |
+
video_btn.click(
|
| 213 |
+
fn=process_video,
|
| 214 |
+
inputs=[video_input, video_lang],
|
| 215 |
+
outputs=[srt_output, video_output, status_output]
|
| 216 |
+
)
|
| 217 |
|
| 218 |
gr.Markdown("""
|
| 219 |
---
|
| 220 |
+
### API Usage
|
|
|
|
|
|
|
|
|
|
|
|
|
| 221 |
|
| 222 |
+
Use the **Audio to SRT** tab as an API endpoint:
|
| 223 |
+
```python
|
| 224 |
+
from gradio_client import Client
|
| 225 |
+
client = Client("YOUR_SPACE_URL")
|
| 226 |
+
srt_content, preview, status = client.predict(
|
| 227 |
+
"audio.wav", # audio file
|
| 228 |
+
"hindi", # language
|
| 229 |
+
api_name="/transcribe"
|
| 230 |
)
|
| 231 |
+
```
|
| 232 |
+
""")
|
| 233 |
|
| 234 |
if __name__ == "__main__":
|
| 235 |
demo.queue(max_size=20).launch(
|
| 236 |
server_name="0.0.0.0",
|
| 237 |
server_port=7860,
|
| 238 |
share=False,
|
| 239 |
+
show_api=True,
|
| 240 |
show_error=True
|
| 241 |
)
|