""" AI Subtitle & SRT Generator -- Studio Web Application ====================================================== A production-grade, cloud-deployable AI Subtitle and SRT Generator web app powered by **Faster-Whisper** (`large-v3` model) and **FFmpeg**. Designed with a high-end Olive & Crisp White studio aesthetic inspired by modern SaaS creator platforms (VEED, Descript, Happy Scribe, Riverside, Rev). Usage ----- python app.py # starts at http://localhost:7860 """ from __future__ import annotations import logging import sys from pathlib import Path import gradio as gr # --------------------------------------------------------------------------- # Logging Configuration # --------------------------------------------------------------------------- logging.basicConfig( level=logging.INFO, format="%(asctime)s | %(levelname)-8s | %(name)s | %(message)s", datefmt="%Y-%m-%d %H:%M:%S", handlers=[logging.StreamHandler(sys.stdout)], ) logger = logging.getLogger("app") # --------------------------------------------------------------------------- # Local Imports # --------------------------------------------------------------------------- from utils.helpers import ( # noqa: E402 validate_uploaded_file, ensure_directories, cleanup_temp_file, format_duration, ) from services.media_processor import extract_audio_to_wav, get_audio_duration # noqa: E402 from services.transcription import transcribe_audio, LANGUAGE_MAP # noqa: E402 from services.subtitle_generator import generate_srt_file, generate_preview_text # noqa: E402 # --------------------------------------------------------------------------- # Bootstrap Runtime Directories # --------------------------------------------------------------------------- ensure_directories() LANGUAGE_CHOICES: list[str] = [ "🌐 Auto-detect (Recommended)", "🇎🇧 English", "🇧ðŸ‡Đ Bangla (āĶŽāĶūāĶ‚āĶēāĶū)", "🔀 Mixed / Banglish", ] _ACCEPTED_FILE_TYPES: list[str] = [ ".mp4", ".mkv", ".avi", ".mov", ".webm", ".flv", ".wmv", ".m4v", ".mp3", ".wav", ".flac", ".aac", ".ogg", ".m4a", ".wma", ".opus", ] # ═══════════════════════════════════════════════════════════════════════════ # Processing Pipeline # ═══════════════════════════════════════════════════════════════════════════ def process_media( file_path: str | None, language: str, progress: gr.Progress = gr.Progress(), ) -> tuple[str, str | None]: """ End-to-end subtitle generation pipeline. Steps: Validate -> FFmpeg 16kHz WAV -> Whisper large-v3 -> SRT Generation. Returns ------- tuple[str, str | None] ``(preview_text, srt_file_path_or_none)`` """ wav_path: str | None = None try: # -- Step 1: Validate upload ------------------------------------ progress(0.05, desc="📁 Validating media file ...") is_valid, message = validate_uploaded_file(file_path) if not is_valid: return f"❌ Validation Error:\n{message}", None logger.info("Processing media: %s | language=%s", file_path, language) original_name = Path(file_path).name # -- Step 2: Extract audio with FFmpeg -------------------------- progress(0.15, desc="ðŸŽĩ Extracting 16 kHz studio WAV via FFmpeg ...") wav_path = extract_audio_to_wav(file_path) duration = get_audio_duration(wav_path) if duration: logger.info("Audio duration: %s", format_duration(duration)) # -- Step 3: Transcribe with Faster-Whisper large-v3 ------------ progress(0.35, desc="⚡ Transcribing with Whisper large-v3 engine ...") result = transcribe_audio(wav_path, language=language) if not result.segments: return ( "⚠ïļ No audible speech detected.\n\n" "ðŸ’Ą Helpful Tips:\n" " â€Ē Ensure the file contains clear, audible spoken dialogue.\n" " â€Ē For mixed speech, leave Language set to Auto-detect.\n" " â€Ē Verify that the audio stream is not muted or heavily degraded.", None, ) # -- Step 4: Generate SRT Subtitle file ------------------------- progress(0.85, desc="📝 Formatting SRT timestamps & building file ...") srt_path, _ = generate_srt_file(result, original_name) # -- Step 5: Build preview text --------------------------------- progress(0.95, desc="âœĻ Subtitle generation complete!") preview = generate_preview_text(result) return preview, srt_path except EnvironmentError as exc: logger.error("Environment error: %s", exc) return f"❌ Environment Error:\n{exc}", None except FileNotFoundError as exc: logger.error("File not found: %s", exc) return f"❌ File Error:\n{exc}", None except RuntimeError as exc: logger.error("Runtime error: %s", exc) return f"❌ Processing Error:\n{exc}", None except Exception as exc: logger.exception("Unexpected error during subtitle processing") return ( f"❌ Unexpected Error ({type(exc).__name__}):\n{exc}\n\n" "Please check the file format or try another media file.", None, ) finally: if wav_path: cleanup_temp_file(wav_path) # ═══════════════════════════════════════════════════════════════════════════ # Professional Custom CSS (Olive & Crisp White Creator Palette) # ═══════════════════════════════════════════════════════════════════════════ CUSTOM_CSS = """ /* ========== Global Page Canvas & Olive/White Palette ========== */ :root { --olive-dark: #2B382A; --olive-primary: #3E4F3C; --olive-medium: #52674F; --olive-light: #6E846A; --olive-soft: #DDE8DA; --olive-tint: #EEF4EB; --olive-bg: #F3F7F1; --white-card: #FFFFFF; --text-charcoal: #1E281D; --text-muted: #576854; --border-subtle: rgba(62, 79, 60, 0.16); --border-strong: rgba(62, 79, 60, 0.28); } body, gradio-app { background: linear-gradient(180deg, #F3F7F1 0%, #E7EFE4 45%, #DCE7D9 100%) !important; color: var(--text-charcoal) !important; font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif !important; min-height: 100vh; } .gradio-container { max-width: 1060px !important; margin: 0 auto !important; background: transparent !important; padding: 1rem !important; } /* ========== Hero Section (Deep Olive Banner with Crisp White Elements) ========== */ .studio-hero-card { background: linear-gradient(135deg, #243023 0%, #354433 50%, #465744 100%); border-radius: 20px; padding: 2.4rem 1.8rem; text-align: center; box-shadow: 0 12px 36px rgba(36, 48, 35, 0.18); border: 1px solid rgba(255, 255, 255, 0.12); margin-bottom: 1.4rem; position: relative; overflow: hidden; } .studio-pill-badge { display: inline-flex; align-items: center; gap: 0.45rem; background: rgba(238, 244, 235, 0.16); border: 1px solid rgba(238, 244, 235, 0.35); color: #E2ECDSubtle; color: #EEF4EB; font-size: 0.84rem; font-weight: 700; padding: 0.38rem 1.1rem; border-radius: 9999px; margin-bottom: 1rem; letter-spacing: 0.04em; text-transform: uppercase; } .studio-title { font-size: 2.5rem !important; font-weight: 800 !important; letter-spacing: -0.025em !important; color: #FFFFFF !important; margin: 0.2rem 0 0.7rem 0 !important; line-height: 1.2 !important; } .studio-subtitle { color: #DDE8DA !important; font-size: 1.05rem; max-width: 680px; margin: 0 auto 0.5rem auto; line-height: 1.6; } /* ========== 4-Step Workflow Cards (Crisp White + Olive Trim) ========== */ .workflow-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 0.85rem; margin: 0.5rem 0 1.5rem 0; } .step-card { background: var(--white-card); border: 1px solid var(--border-subtle); border-radius: 14px; padding: 1rem 1.1rem; display: flex; align-items: center; gap: 0.85rem; box-shadow: 0 4px 16px rgba(43, 56, 42, 0.05); transition: all 0.22s ease; } .step-card:hover { border-color: var(--olive-primary); transform: translateY(-3px); box-shadow: 0 8px 24px rgba(43, 56, 42, 0.1); } .step-icon-box { width: 44px; height: 44px; border-radius: 10px; background: var(--olive-tint); border: 1px solid var(--olive-soft); display: flex; align-items: center; justify-content: center; font-size: 1.35rem; flex-shrink: 0; } .step-info { text-align: left; } .step-number { font-size: 0.72rem; font-weight: 800; text-transform: uppercase; color: var(--olive-medium); letter-spacing: 0.06em; } .step-label { font-size: 0.92rem; font-weight: 700; color: var(--text-charcoal); } /* ========== Content Cards (Crisp White Panels) ========== */ .card, .gr-box, .gr-panel, .gr-form { background: var(--white-card) !important; border: 1px solid var(--border-subtle) !important; border-radius: 16px !important; box-shadow: 0 4px 20px rgba(43, 56, 42, 0.05) !important; } .panel-title { font-size: 0.95rem; font-weight: 800; text-transform: uppercase; letter-spacing: 0.05em; color: var(--olive-dark); display: flex; align-items: center; gap: 0.5rem; margin: 0.4rem 0 0.6rem 0; } /* ========== Format Chips (Olive Pastel Tags) ========== */ .chips-container { display: flex; flex-wrap: wrap; gap: 0.45rem; margin: 0.6rem 0 0.9rem 0; } .format-chip { background: var(--olive-tint); border: 1px solid rgba(62, 79, 60, 0.2); color: var(--olive-dark); font-size: 0.78rem; font-weight: 700; padding: 0.28rem 0.65rem; border-radius: 8px; display: inline-flex; align-items: center; gap: 0.3rem; } /* ========== Action Button (Rich Deep Olive Gradient) ========== */ .generate-btn { background: linear-gradient(135deg, #2E3B2C 0%, #465843 50%, #2E3B2C 100%) !important; border: none !important; color: #FFFFFF !important; font-weight: 800 !important; font-size: 1.08rem !important; padding: 0.9rem 1.8rem !important; border-radius: 12px !important; box-shadow: 0 6px 24px rgba(46, 59, 44, 0.3) !important; transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1) !important; width: 100% !important; cursor: pointer !important; margin-top: 0.6rem !important; } .generate-btn:hover { background: linear-gradient(135deg, #243023 0%, #3B4B38 50%, #243023 100%) !important; transform: translateY(-2px) !important; box-shadow: 0 10px 30px rgba(46, 59, 44, 0.45) !important; } .generate-btn:active { transform: translateY(0) !important; } /* ========== Input & Textarea Refinement ========== */ input, textarea, select, .gr-input, .gr-textarea { background: #FAFCF9 !important; border: 1px solid var(--border-strong) !important; color: var(--text-charcoal) !important; border-radius: 10px !important; } input:focus, textarea:focus, select:focus { border-color: var(--olive-primary) !important; box-shadow: 0 0 0 3px rgba(62, 79, 60, 0.15) !important; } /* ========== Studio Footer ========== */ .studio-footer { text-align: center; padding: 2rem 1rem 1rem; color: var(--text-muted); font-size: 0.85rem; border-top: 1px solid var(--border-subtle); margin-top: 2.2rem; } /* Hide default Gradio footer */ footer { display: none !important; } """ # ═══════════════════════════════════════════════════════════════════════════ # Gradio UI Construction # ═══════════════════════════════════════════════════════════════════════════ def build_ui() -> gr.Blocks: """Construct and return the redesigned Olive & White Gradio Studio UI.""" with gr.Blocks(title="AI Subtitle & SRT Generator | Studio") as app: # -- Hero Banner (Deep Olive + Crisp White) ----------------- gr.HTML( '
' '
' " 🎎 AI Video & Audio Subtitle Studio · 2-Line Subtitle Standard 🎙ïļ" "
" '

AI Subtitle & SRT Generator

' '

' " Convert video and audio recordings into professional, broadcast-compliant " ".srt subtitles (strictly max 2 lines per timestamp) powered by " "Faster-Whisper large-v3. Engineered for creators, editors, and podcasters." "

" "
" ) # -- 4-Step Workflow Grid (Crisp White + Olive Trim) -------- gr.HTML( '
' '
' '
📁
' '
' '
Step 01
' '
Upload Media
' "
" "
" '
' '
🌐
' '
' '
Step 02
' '
Select Language
' "
" "
" '
' '
⚡
' '
' '
Step 03
' '
Whisper large-v3
' "
" "
" '
' '
ðŸ“Ĩ
' '
' '
Step 04
' '
Download .SRT
' "
" "
" "
" ) # -- Main Dual-Pane Studio Layout --------------------------- with gr.Row(equal_height=False): # == Left Column: Media Inputs & Settings =============== with gr.Column(scale=1): gr.HTML( '
' " 🎎 Media File Upload" "
" ) file_input = gr.File( label="Select Video or Audio File", file_types=_ACCEPTED_FILE_TYPES, type="filepath", ) # Format chips in pastel olive tags gr.HTML( '
' ' 🎎 MP4' ' 🎞ïļ MKV' ' ðŸ“―ïļ MOV' ' ðŸŽĨ WebM' ' ðŸŽĩ MP3' ' 🎧 WAV' ' 🎞 FLAC' ' 🎙ïļ M4A' ' 🔊 AAC' ' ðŸ“Ķ Max 500 MB' "
" ) gr.HTML( '
' " 🌐 Speech & Language Configuration" "
" ) language_dropdown = gr.Dropdown( choices=LANGUAGE_CHOICES, value="🌐 Auto-detect (Recommended)", label="Spoken Language", info="Supports English, Bangla, and Mixed Bangla-English (Banglish).", ) generate_btn = gr.Button( "âœĻ Generate Studio Subtitles 🎎", variant="primary", size="lg", elem_classes=["generate-btn"], ) # Engine badge gr.HTML( '
' " 🎙ïļ Engine: Faster-Whisper large-v3 (1.55B Parameters · int8 Quantized)" "
" ) # == Right Column: Preview & Subtitle Download ========== with gr.Column(scale=1): gr.HTML( '
' " 📝 Live Transcript & Timestamps Preview" "
" ) preview_box = gr.Textbox( label="Studio Transcript", placeholder="Transcription summary and timestamped subtitle blocks will appear here...", lines=18, max_lines=32, interactive=False, ) gr.HTML( '
' " ⮇ïļ Export & Download" "
" ) download_file = gr.File( label="Download .SRT Subtitle File", interactive=False, ) # -- Interactive Workflow Wiring ---------------------------- generate_btn.click( fn=process_media, inputs=[file_input, language_dropdown], outputs=[preview_box, download_file], ) # -- Studio Footer ------------------------------------------ gr.HTML( '" ) return app # ═══════════════════════════════════════════════════════════════════════════ # Application Entrypoint # ═══════════════════════════════════════════════════════════════════════════ if __name__ == "__main__": application = build_ui() application.launch( server_name="0.0.0.0", server_port=7860, share=True, show_error=True, css=CUSTOM_CSS, theme=gr.themes.Soft( primary_hue="emerald", secondary_hue="stone", neutral_hue="stone", ), )