Spaces:
Sleeping

File size: 6,764 Bytes
af5bfc8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
import os
import time
from pathlib import Path

import gradio as gr
import requests
import spaces


ASSEMBLYAI_API = "https://api.assemblyai.com/v2"
MAX_FILE_MB = 500


def _headers(api_key: str) -> dict:
    return {
        "authorization": api_key.strip(),
        "content-type": "application/json",
    }


def transcribe_audio(api_key: str, media_file: str):
    """Upload an audio/video file to AssemblyAI and poll for its transcript."""
    if not api_key or not api_key.strip():
        raise gr.Error("Please paste your AssemblyAI API key first.")
    if not media_file:
        raise gr.Error("Please upload an MP4, MP3, WAV, M4A, or WEBM file.")

    file_path = Path(media_file)
    if not file_path.exists():
        raise gr.Error("The uploaded file could not be found. Please upload it again.")
    if file_path.stat().st_size > MAX_FILE_MB * 1024 * 1024:
        raise gr.Error(f"Please keep files under {MAX_FILE_MB} MB for this demo.")

    try:
        with file_path.open("rb") as audio:
            upload = requests.post(
                f"{ASSEMBLYAI_API}/upload",
                headers={"authorization": api_key.strip()},
                data=audio,
                timeout=300,
            )
        upload.raise_for_status()
        audio_url = upload.json()["upload_url"]

        payload = {
            "audio_url": audio_url,
            "language_detection": True,
            "punctuate": True,
            "format_text": True,
        }
        created = requests.post(
            f"{ASSEMBLYAI_API}/transcript",
            headers=_headers(api_key),
            json=payload,
            timeout=60,
        )
        created.raise_for_status()
        transcript_id = created.json()["id"]

        while True:
            result = requests.get(
                f"{ASSEMBLYAI_API}/transcript/{transcript_id}",
                headers=_headers(api_key),
                timeout=60,
            )
            result.raise_for_status()
            data = result.json()
            status = data.get("status")
            if status == "completed":
                text = data.get("text") or "No speech was detected in this file."
                language = data.get("language_code") or "auto-detected"
                return text, f"Completed • detected language: {language}", text
            if status == "error":
                raise gr.Error(data.get("error") or "AssemblyAI could not transcribe this file.")
            time.sleep(3)
    except requests.HTTPError as exc:
        detail = exc.response.text[:500] if exc.response is not None else str(exc)
        raise gr.Error(f"AssemblyAI request failed: {detail}") from exc
    except requests.RequestException as exc:
        raise gr.Error(f"Network error while contacting AssemblyAI: {exc}") from exc


def clear_all():
    return "", None, "Ready when you are.", "", None


custom_css = """
:root { --bg: #080b16; --panel: #121a29; --panel-2: #1b2738; --muted: #aab3c5; --purple: #7558ff; --purple-2: #5444d7; }
body, .gradio-container { background: radial-gradient(circle at 50% -10%, #24315b 0%, var(--bg) 42%); color: #f7f8ff; }
.gradio-container { max-width: 980px !important; padding: 28px 18px 40px !important; }
.hero { text-align: center; padding: 10px 0 22px; }
.hero h1 { font-size: 2.2rem; margin: 0 0 8px; letter-spacing: -0.03em; }
.hero p { color: var(--muted); margin: 0; }
.app-card { background: rgba(18, 26, 41, .94); border: 1px solid #26344a; border-radius: 22px; padding: 24px; box-shadow: 0 20px 70px rgba(0,0,0,.35); }
.section-label { display: inline-block; background: linear-gradient(135deg,var(--purple),var(--purple-2)); border-radius: 8px; padding: 7px 11px; font-weight: 700; margin: 5px 0 10px; }
.note { color: var(--muted); font-size: .9rem; margin: 0 0 14px; }
textarea, input { background: #263346 !important; color: #fff !important; border: 1px solid #3a4a63 !important; }
.upload-box { background: #1b2a3b; border: 1px dashed #60708a; border-radius: 14px; min-height: 150px; }
button.primary { background: linear-gradient(135deg,var(--purple),#5a45d4) !important; border: none !important; color: white !important; font-weight: 800 !important; }
button.secondary { background: #293548 !important; color: #eef !important; border: 1px solid #3b4a60 !important; }
.status { color: #bfc8da; }
footer { text-align:center; color:#76839a; font-size:.8rem; margin-top:16px; }
"""

with gr.Blocks(title="Transcript Studio", theme=gr.themes.Base(), css=custom_css) as demo:
    gr.HTML(
        """
        <div class="hero">
          <h1>Transcript Studio</h1>
          <p>Turn your MP4 or MP3 into clean, readable text in seconds.</p>
        </div>
        """
    )
    with gr.Column(elem_classes="app-card"):
        gr.Markdown("AssemblyAI API Key", elem_classes="section-label")
        gr.Markdown(
            "Your key is used only for this request and is not saved by this demo. "
            "Create one at [assemblyai.com](https://www.assemblyai.com/).",
            elem_classes="note",
        )
        api_key = gr.Textbox(
            label=None,
            placeholder="Paste your API key here",
            type="password",
            show_label=False,
        )

        gr.Markdown("Upload MP4 / MP3", elem_classes="section-label")
        media = gr.File(
            label="Drop File Here or Click to Upload",
            file_types=[".mp4", ".mp3", ".wav", ".m4a", ".webm"],
            type="filepath",
            elem_classes="upload-box",
        )

        with gr.Row():
            generate = gr.Button("✨ Generate Transcript", variant="primary", elem_classes="primary")
            clear = gr.Button("Clear", variant="secondary", elem_classes="secondary")

        status = gr.Markdown("Ready when you are.", elem_classes="status")
        gr.Markdown("Transcript Result", elem_classes="section-label")
        transcript = gr.Textbox(
            label=None,
            placeholder="Your transcript will appear here...",
            lines=14,
            show_label=False,
        )
        download = gr.File(label="Download transcript", interactive=False)

    gr.HTML("<footer>Built for Hugging Face Spaces • Powered by AssemblyAI</footer>")

    @spaces.GPU(duration=300)
    def transcribe_and_prepare(api, file):
        text, message, output = transcribe_audio(api, file)
        out_path = Path("/tmp/transcript.txt")
        out_path.write_text(output, encoding="utf-8")
        return text, message, str(out_path)

    generate.click(
        transcribe_and_prepare,
        inputs=[api_key, media],
        outputs=[transcript, status, download],
    )
    clear.click(clear_all, outputs=[api_key, media, status, transcript, download])


if __name__ == "__main__":
    demo.launch()