aijadugar commited on
Commit
c0bbf92
·
verified ·
1 Parent(s): 2a00e5d

Upload 4 files

Browse files
Files changed (3) hide show
  1. README.md +54 -1
  2. app.py +282 -0
  3. requirements.txt +3 -0
README.md CHANGED
@@ -1,3 +1,56 @@
1
  ---
2
- license: apache-2.0
 
 
 
 
 
 
 
 
 
3
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Wispr Flow Clone
3
+ emoji: 🎙️
4
+ colorFrom: blue
5
+ colorTo: indigo
6
+ sdk: gradio
7
+ sdk_version: 6.26.0
8
+ python_version: "3.10"
9
+ app_file: app.py
10
+ pinned: false
11
+ short_description: Wispr Flow Clone space
12
  ---
13
+
14
+ # Voice → Clean Text
15
+
16
+ A Wispr Flow-style pipeline: speak, get a verbatim transcript, then a
17
+ cleaned-up version with filler words removed and tone adapted to your
18
+ chosen mode (email / chat / notes).
19
+
20
+ ## How it's wired
21
+
22
+ - **ASR (fine-tuned Whisper)** — transcribes audio **verbatim**. It does
23
+ not rewrite content; its only job is faithful transcription, including
24
+ disfluencies. This matters: a dictation tool that "corrects" during
25
+ transcription can silently put words in your mouth.
26
+ - **Cleanup (fine-tuned LLM)** — takes the verbatim transcript and
27
+ rewrites it: removes filler words and false starts, fixes grammar,
28
+ adapts tone to the selected mode. All rewriting happens here, where
29
+ it's visible and controlled by an explicit system prompt.
30
+
31
+ ## Running locally
32
+
33
+ ```bash
34
+ pip install -r requirements.txt
35
+ export WHISPER_REPO_ID="aijadugar/wispr-clone-whisper"
36
+ export LLM_REPO_ID="aijadugar/wispr-clone-llm"
37
+ python app.py
38
+ ```
39
+
40
+ Or just edit the default repo IDs at the top of `app.py`.
41
+
42
+ ## Deploying as a Hugging Face Space
43
+
44
+ 1. Create a new Space (SDK: Gradio).
45
+ 2. Push `app.py`, `requirements.txt`, and this `README.md`.
46
+ 3. Set `WHISPER_REPO_ID` / `LLM_REPO_ID` as Space variables (Settings →
47
+ Variables), or hardcode them in `app.py`.
48
+ 4. Pick a GPU hardware tier if you want low-latency generation — CPU
49
+ works but the LLM stage will be noticeably slower.
50
+
51
+ ## Training
52
+
53
+ The models this app loads are produced by the companion training
54
+ notebook (`wf-voice-to-clean-text.ipynb`), designed to run on Kaggle's
55
+ free T4×2 GPU quota. See that notebook for the full fine-tuning + Hub
56
+ push pipeline.
app.py ADDED
@@ -0,0 +1,282 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Voice -> Clean Text (Wispr Flow-style) — Gradio app.
3
+
4
+ Loads the two fine-tuned models pushed to the Hub by the training
5
+ notebook:
6
+ - WHISPER_REPO_ID: verbatim, disfluency-robust ASR
7
+ - LLM_REPO_ID: cleanup + tone adaptation
8
+
9
+ ZeroGPU note: no CUDA context exists in the main process — a GPU is attached
10
+ only for the duration of a call to a function decorated with @spaces.GPU, then
11
+ released. So both models are loaded onto CPU at startup; the only functions
12
+ that ever touch CUDA are _transcribe_on_gpu and _clean_up_on_gpu below, which
13
+ move the (already-loaded) models onto the GPU the first time they run and
14
+ reuse that placement on later calls within the same worker. On a plain CPU
15
+ Space (no @spaces available), everything falls back to running on CPU as-is.
16
+ """
17
+
18
+ import os
19
+ import time
20
+
21
+ import gradio as gr
22
+ import torch
23
+ from transformers import (
24
+ AutoModelForCausalLM,
25
+ AutoTokenizer,
26
+ WhisperForConditionalGeneration,
27
+ WhisperProcessor,
28
+ pipeline,
29
+ )
30
+
31
+ try:
32
+ import spaces
33
+ ZEROGPU_AVAILABLE = True
34
+ except ImportError:
35
+ ZEROGPU_AVAILABLE = False
36
+
37
+ class _NoOpSpaces:
38
+ @staticmethod
39
+ def GPU(fn=None, **kwargs):
40
+ # No-op decorator so @spaces.GPU still works on a plain CPU Space
41
+ # (no `spaces` package installed / not running on HF infra).
42
+ if fn is not None:
43
+ return fn
44
+ return lambda f: f
45
+
46
+ spaces = _NoOpSpaces()
47
+
48
+ # ---------------------------------------------------------------------------
49
+ # Config — point these at the repos the notebook pushed to
50
+ # ---------------------------------------------------------------------------
51
+
52
+ WHISPER_REPO_ID = os.environ.get("WHISPER_REPO_ID", "aijadugar/wisprflow-clone-whisper")
53
+ LLM_REPO_ID = os.environ.get("LLM_REPO_ID", "aijadugar/wisprflow-clone-llm")
54
+
55
+ # CPU-only at import time — deliberately never assume CUDA exists here.
56
+ # Under ZeroGPU, torch.cuda.is_available() is unreliable/False in the main
57
+ # process anyway; actual device placement happens lazily inside the
58
+ # @spaces.GPU-decorated functions below.
59
+ #
60
+ # bfloat16 (not float32) on CPU: halves RAM for both models. Modern PyTorch
61
+ # has native CPU kernels for bf16 matmul/linear (unlike float16, which is
62
+ # poorly supported on CPU), so this is safe and meaningfully cuts memory
63
+ # pressure — important since the LLM checkpoint here is ~15GB.
64
+ LOAD_DEVICE = "cpu"
65
+ LOAD_DTYPE = torch.bfloat16
66
+
67
+ MODE_PROMPTS = {
68
+ "Email": (
69
+ "You are a transcription cleanup assistant. Rewrite the raw speech "
70
+ "transcript into clear, well-punctuated, professional email prose. "
71
+ "Remove filler words and false starts, fix grammar, use complete "
72
+ "sentences. Do not add information that was not said. Output ONLY "
73
+ "the cleaned text."
74
+ ),
75
+ "Chat / Slack": (
76
+ "You are a transcription cleanup assistant. Rewrite the raw speech "
77
+ "transcript into clear, casual chat-message text. Remove filler "
78
+ "words and false starts, fix grammar, but keep it brief and "
79
+ "conversational -- do not over-formalize. Do not add information "
80
+ "that was not said. Output ONLY the cleaned text."
81
+ ),
82
+ "Notes": (
83
+ "You are a transcription cleanup assistant. Rewrite the raw speech "
84
+ "transcript into clear, concise note form. Remove filler words and "
85
+ "false starts, fix grammar, tighten wordy phrasing. Do not add "
86
+ "information that was not said. Output ONLY the cleaned text."
87
+ ),
88
+ "Plain cleanup": (
89
+ "You are a transcription cleanup assistant. Rewrite the raw speech "
90
+ "transcript into clear, well-punctuated text. Remove filler words "
91
+ "and false starts, fix grammar. Do not add information that was "
92
+ "not said. Output ONLY the cleaned text."
93
+ ),
94
+ }
95
+
96
+ # ---------------------------------------------------------------------------
97
+ # Model loading (once, at startup) — CPU only. GPU placement is deferred to
98
+ # the @spaces.GPU-decorated inference functions below.
99
+ # ---------------------------------------------------------------------------
100
+
101
+ print(f"Loading ASR model from {WHISPER_REPO_ID} (CPU) ...")
102
+ whisper_processor = WhisperProcessor.from_pretrained(WHISPER_REPO_ID)
103
+ whisper_model = WhisperForConditionalGeneration.from_pretrained(
104
+ WHISPER_REPO_ID,
105
+ torch_dtype=LOAD_DTYPE,
106
+ low_cpu_mem_usage=True,
107
+ )
108
+ whisper_model.eval()
109
+
110
+ print(f"Loading cleanup LLM from {LLM_REPO_ID} (CPU) ...")
111
+ llm_tokenizer = AutoTokenizer.from_pretrained(LLM_REPO_ID)
112
+ llm_model = AutoModelForCausalLM.from_pretrained(
113
+ LLM_REPO_ID,
114
+ torch_dtype=LOAD_DTYPE,
115
+ low_cpu_mem_usage=True,
116
+ )
117
+ llm_model.eval()
118
+
119
+ print("Models loaded on CPU. GPU (if any) is attached lazily per-call.")
120
+
121
+ # Tracks whether each model currently lives on cuda, so repeat calls don't
122
+ # re-transfer weights every time within the same ZeroGPU worker.
123
+ _whisper_gpu_resident = False
124
+ _llm_gpu_resident = False
125
+ _asr_pipe = None # built lazily once we know the device/dtype for this call
126
+
127
+
128
+ # ---------------------------------------------------------------------------
129
+ # Pipeline
130
+ # ---------------------------------------------------------------------------
131
+
132
+ @spaces.GPU
133
+ def _transcribe_on_gpu(audio_path):
134
+ """The only function that touches CUDA for ASR. ZeroGPU attaches a GPU for
135
+ the duration of this call; whisper_model is moved here once (a no-op on
136
+ later calls once resident) and released back to the caller as plain text,
137
+ since nothing outside this function is guaranteed a live CUDA context."""
138
+ global _whisper_gpu_resident, _asr_pipe
139
+
140
+ device = "cuda" if torch.cuda.is_available() else "cpu"
141
+ dtype = torch.float16 if device == "cuda" else torch.float32
142
+
143
+ if not _whisper_gpu_resident and device == "cuda":
144
+ whisper_model.to(device=device, dtype=dtype)
145
+ _whisper_gpu_resident = True
146
+ _asr_pipe = None # rebuild pipe against the now-GPU model
147
+
148
+ if _asr_pipe is None:
149
+ _asr_pipe = pipeline(
150
+ "automatic-speech-recognition",
151
+ model=whisper_model,
152
+ tokenizer=whisper_processor.tokenizer,
153
+ feature_extractor=whisper_processor.feature_extractor,
154
+ torch_dtype=whisper_model.dtype,
155
+ device=device,
156
+ )
157
+
158
+ result = _asr_pipe(audio_path)
159
+ return result["text"].strip()
160
+
161
+
162
+ @spaces.GPU
163
+ def _clean_up_on_gpu(raw_text, mode):
164
+ """The only function that touches CUDA for the cleanup LLM. Same lazy
165
+ move-once pattern as _transcribe_on_gpu."""
166
+ global _llm_gpu_resident
167
+
168
+ device = "cuda" if torch.cuda.is_available() else "cpu"
169
+ dtype = torch.float16 if device == "cuda" else torch.float32
170
+
171
+ if not _llm_gpu_resident and device == "cuda":
172
+ llm_model.to(device=device, dtype=dtype)
173
+ _llm_gpu_resident = True
174
+
175
+ system_prompt = MODE_PROMPTS.get(mode, MODE_PROMPTS["Plain cleanup"])
176
+ messages = [
177
+ {"role": "system", "content": system_prompt},
178
+ {"role": "user", "content": raw_text},
179
+ ]
180
+ prompt = llm_tokenizer.apply_chat_template(
181
+ messages, tokenize=False, add_generation_prompt=True
182
+ )
183
+ inputs = llm_tokenizer(prompt, return_tensors="pt").to(llm_model.device)
184
+
185
+ with torch.no_grad():
186
+ output_ids = llm_model.generate(
187
+ **inputs,
188
+ max_new_tokens=256,
189
+ do_sample=False,
190
+ repetition_penalty=1.1,
191
+ pad_token_id=llm_tokenizer.pad_token_id or llm_tokenizer.eos_token_id,
192
+ )
193
+
194
+ new_tokens = output_ids[0][inputs["input_ids"].shape[1]:]
195
+ cleaned = llm_tokenizer.decode(new_tokens, skip_special_tokens=True).strip()
196
+ return cleaned
197
+
198
+
199
+ def transcribe(audio_path):
200
+ if audio_path is None:
201
+ return "", 0.0, None
202
+ start = time.time()
203
+ try:
204
+ text = _transcribe_on_gpu(audio_path)
205
+ except Exception as e:
206
+ return "", time.time() - start, f"Transcription failed: {e}"
207
+ elapsed = time.time() - start
208
+ return text, elapsed, None
209
+
210
+
211
+ def clean_up(raw_text, mode):
212
+ if not raw_text.strip():
213
+ return "", 0.0, None
214
+ start = time.time()
215
+ try:
216
+ cleaned = _clean_up_on_gpu(raw_text, mode)
217
+ except Exception as e:
218
+ return "", time.time() - start, f"Cleanup failed: {e}"
219
+ elapsed = time.time() - start
220
+ return cleaned, elapsed, None
221
+
222
+
223
+ def run_pipeline(audio_path, mode):
224
+ if audio_path is None:
225
+ return "", "", "Record or upload audio first."
226
+
227
+ raw_text, asr_seconds, asr_error = transcribe(audio_path)
228
+ if asr_error:
229
+ return "", "", asr_error
230
+ if not raw_text:
231
+ return "", "", "Couldn't transcribe that clip — try again."
232
+
233
+ cleaned_text, llm_seconds, llm_error = clean_up(raw_text, mode)
234
+ if llm_error:
235
+ return raw_text, "", llm_error
236
+
237
+ total = asr_seconds + llm_seconds
238
+ stats = (
239
+ f"Transcription: {asr_seconds:.1f}s · "
240
+ f"Cleanup: {llm_seconds:.1f}s · "
241
+ f"Total: {total:.1f}s"
242
+ )
243
+ return raw_text, cleaned_text, stats
244
+
245
+
246
+ # ---------------------------------------------------------------------------
247
+ # UI — a plain, single-screen layout: record/upload, pick a style, run.
248
+ # ---------------------------------------------------------------------------
249
+
250
+ with gr.Blocks(title="Voice → Clean Text") as demo:
251
+ gr.Markdown(
252
+ "# 🎙️ Voice → Clean Text\n"
253
+ "Record or upload audio, pick a style, and get a cleaned-up transcript."
254
+ )
255
+
256
+ with gr.Row():
257
+ with gr.Column(scale=1):
258
+ audio_input = gr.Audio(
259
+ sources=["microphone", "upload"],
260
+ type="filepath",
261
+ label="Speak or upload audio",
262
+ )
263
+ mode = gr.Radio(
264
+ choices=list(MODE_PROMPTS.keys()),
265
+ value="Plain cleanup",
266
+ label="Cleanup style",
267
+ )
268
+ run_btn = gr.Button("Transcribe & Clean Up", variant="primary")
269
+
270
+ with gr.Column(scale=1):
271
+ raw_output = gr.Textbox(label="Raw transcript (verbatim)", lines=5)
272
+ clean_output = gr.Textbox(label="Cleaned text", lines=5)
273
+ stats_output = gr.Markdown()
274
+
275
+ run_btn.click(
276
+ fn=run_pipeline,
277
+ inputs=[audio_input, mode],
278
+ outputs=[raw_output, clean_output, stats_output],
279
+ )
280
+
281
+ if __name__ == "__main__":
282
+ demo.queue().launch()
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ transformers>=4.45.0
2
+ accelerate>=0.34.0
3
+ safetensors>=0.4.5