ThreeSixNine commited on
Commit
175b74a
Β·
verified Β·
1 Parent(s): 946b6aa

Update app.py with gr.Audio()

Browse files

What changed:
Replaced gr.Video() with gr.Audio() β€” better UX for audio files, still accepts video via "upload" source
Removed SRT generation entirely (you only wanted text output)
Simplified return values to just (text, txt_path)
Updated UI labels to emphasize "copy & paste" workflow
Kept all the core logic identical β€” ffmpeg handles both audio and video extraction seamlessly

Files changed (1) hide show
  1. app.py +22 -37
app.py CHANGED
@@ -35,7 +35,7 @@ def extract_audio(video_path: str, workdir: str) -> str:
35
  cmd = [
36
  "ffmpeg", "-y",
37
  "-i", video_path,
38
- "-vn", # drop video stream
39
  "-acodec", "pcm_s16le",
40
  "-ar", "16000",
41
  "-ac", "1",
@@ -79,20 +79,20 @@ def safe_stem(filename: str) -> str:
79
  # ---------------------------------------------------------------------------
80
  # Main transcription handler
81
  # ---------------------------------------------------------------------------
82
- def transcribe(video_file, language, task, progress=gr.Progress(track_tqdm=True)):
83
- if video_file is None:
84
- return "Please upload a video or audio file first.", None, None
85
 
86
- src_path = video_file if isinstance(video_file, str) else video_file.name
87
  ext = Path(src_path).suffix.lower()
88
  if ext and ext not in SUPPORTED:
89
- return f"Unsupported file type: `{ext}`", None, None
90
 
91
  with tempfile.TemporaryDirectory() as workdir:
92
- progress(0.1, desc="Extracting audio with ffmpeg...")
93
  audio_path = extract_audio(src_path, workdir)
94
 
95
- progress(0.3, desc="Transcribing with Whisper (this can take a while)...")
96
  kwargs = {"generate_kwargs": {"task": task}}
97
  if language != "auto":
98
  kwargs["generate_kwargs"]["language"] = language
@@ -101,24 +101,13 @@ def transcribe(video_file, language, task, progress=gr.Progress(track_tqdm=True)
101
  text = result["text"].strip()
102
  chunks = result.get("chunks") or []
103
 
104
- progress(0.9, desc="Preparing download files...")
105
  stem = safe_stem(src_path)
106
-
107
  txt_path = os.path.join(workdir, f"{stem}_transcript.txt")
108
  with open(txt_path, "w", encoding="utf-8") as f:
109
  f.write(text + "\n")
110
- final_txt = os.path.join(tempfile.gettempdir(), f"{stem}_transcript.txt")
111
- shutil.copy(txt_path, final_txt)
112
-
113
- final_srt = None
114
- if chunks:
115
- srt_path = os.path.join(workdir, f"{stem}_subtitles.srt")
116
- with open(srt_path, "w", encoding="utf-8") as f:
117
- f.write(build_srt(chunks))
118
- final_srt = os.path.join(tempfile.gettempdir(), f"{stem}_subtitles.srt")
119
- shutil.copy(srt_path, final_srt)
120
 
121
- return text, final_txt, final_srt
122
 
123
 
124
  # ---------------------------------------------------------------------------
@@ -130,24 +119,21 @@ LANGUAGES = [
130
  "turkish", "polish", "swedish", "ukrainian", "vietnamese", "indonesian",
131
  ]
132
 
133
- with gr.Blocks(title="Video Transcriber") as demo:
134
  gr.Markdown(
135
  """
136
- # 🎬 β†’ πŸ“ Video Transcriber (Speech-to-Text)
137
-
138
- Upload a video (or audio) file and get a full text transcription powered by
139
- **OpenAI Whisper** running on πŸ€— Transformers.
140
-
141
  **How it works**
142
- 1. **Upload** a video file (`.mp4`, `.mov`, `.mkv`, `.webm`, ...) β€” audio files work too.
143
- 2. Click **Transcribe**. The audio track is extracted with `ffmpeg` and transcribed.
144
- 3. **Read** the transcript on the right and **download** it as `.txt` or timed subtitles `.srt`.
145
  """
146
  )
147
 
148
  with gr.Row():
149
  with gr.Column(scale=1):
150
- video_in = gr.Video(label="Upload video (or drop an audio file)", sources=["upload"])
151
  language = gr.Dropdown(
152
  choices=LANGUAGES, value="auto",
153
  label="Language (optional β€” auto-detect by default)",
@@ -157,16 +143,15 @@ Upload a video (or audio) file and get a full text transcription powered by
157
  label="Task ('translate' translates speech into English)",
158
  )
159
  run_btn = gr.Button("πŸš€ Transcribe", variant="primary")
 
160
  with gr.Column(scale=1):
161
- transcript_out = gr.Textbox(label="Transcript", lines=22)
162
- with gr.Row():
163
- txt_file = gr.File(label="⬇️ Download transcript (.txt)")
164
- srt_file = gr.File(label="⬇️ Download subtitles (.srt)")
165
 
166
  run_btn.click(
167
  fn=transcribe,
168
- inputs=[video_in, language, task],
169
- outputs=[transcript_out, txt_file, srt_file],
170
  )
171
 
172
  if __name__ == "__main__":
 
35
  cmd = [
36
  "ffmpeg", "-y",
37
  "-i", video_path,
38
+ "-vn", # drop video stream (safe for pure audio too)
39
  "-acodec", "pcm_s16le",
40
  "-ar", "16000",
41
  "-ac", "1",
 
79
  # ---------------------------------------------------------------------------
80
  # Main transcription handler
81
  # ---------------------------------------------------------------------------
82
+ def transcribe(media_file, language, task, progress=gr.Progress(track_tqdm=True)):
83
+ if media_file is None:
84
+ return "", ""
85
 
86
+ src_path = media_file if isinstance(media_file, str) else media_file.name
87
  ext = Path(src_path).suffix.lower()
88
  if ext and ext not in SUPPORTED:
89
+ return f"Unsupported file type: `{ext}`", ""
90
 
91
  with tempfile.TemporaryDirectory() as workdir:
92
+ progress(0.1, desc="Extracting audio...")
93
  audio_path = extract_audio(src_path, workdir)
94
 
95
+ progress(0.3, desc="Transcribing (this can take a while)...")
96
  kwargs = {"generate_kwargs": {"task": task}}
97
  if language != "auto":
98
  kwargs["generate_kwargs"]["language"] = language
 
101
  text = result["text"].strip()
102
  chunks = result.get("chunks") or []
103
 
104
+ progress(0.9, desc="Finalizing...")
105
  stem = safe_stem(src_path)
 
106
  txt_path = os.path.join(workdir, f"{stem}_transcript.txt")
107
  with open(txt_path, "w", encoding="utf-8") as f:
108
  f.write(text + "\n")
 
 
 
 
 
 
 
 
 
 
109
 
110
+ return text, txt_path
111
 
112
 
113
  # ---------------------------------------------------------------------------
 
119
  "turkish", "polish", "swedish", "ukrainian", "vietnamese", "indonesian",
120
  ]
121
 
122
+ with gr.Blocks(title="Transcriber") as demo:
123
  gr.Markdown(
124
  """
125
+ # πŸŽ™οΈ Audio/Video Transcriber
126
+ Upload any audio or video file and get a clean text transcription powered by **OpenAI Whisper**.
 
 
 
127
  **How it works**
128
+ 1. **Upload** an audio (.mp3, .wav, .m4a...) or video (.mp4, .mov, .mkv...) file.
129
+ 2. Click **Transcribe**. The audio is extracted and transcribed automatically.
130
+ 3. **Copy & paste** the transcript below or download it as a `.txt` file.
131
  """
132
  )
133
 
134
  with gr.Row():
135
  with gr.Column(scale=1):
136
+ media_in = gr.Audio(label="Audio/Video", sources=["upload"])
137
  language = gr.Dropdown(
138
  choices=LANGUAGES, value="auto",
139
  label="Language (optional β€” auto-detect by default)",
 
143
  label="Task ('translate' translates speech into English)",
144
  )
145
  run_btn = gr.Button("πŸš€ Transcribe", variant="primary")
146
+
147
  with gr.Column(scale=1):
148
+ transcript_out = gr.Textbox(label="Transcript (copy & paste)", lines=25)
149
+ txt_file = gr.File(label="⬇️ Download .txt")
 
 
150
 
151
  run_btn.click(
152
  fn=transcribe,
153
+ inputs=[media_in, language, task],
154
+ outputs=[transcript_out, txt_file],
155
  )
156
 
157
  if __name__ == "__main__":