Murali Chandran commited on
Commit
0c39aa5
·
1 Parent(s): 45b2ff1

optimised for faster generation

Browse files
Files changed (1) hide show
  1. app.py +77 -128
app.py CHANGED
@@ -1,181 +1,130 @@
1
  #!/usr/bin/env python3
2
  # ------------------------------------------------------------
3
- # Whisper Small LS-100 + Stable Diffusion (CPU-only)
4
- # Works on Hugging Face Spaces free tier (no GPU)
5
  # Author: Murali Chandran (codeninja3d)
6
  # ------------------------------------------------------------
7
 
8
- import os
9
- import gc
10
- import torch
11
- import gradio as gr
12
-
13
- # Prefer torchaudio but safely fall back to soundfile if TorchCodec backend bites
14
  try:
15
- import torchaudio # may try TorchCodec in new versions
16
- _HAS_TORCHAUDIO = True
17
  except Exception:
18
- _HAS_TORCHAUDIO = False
19
  torchaudio = None
20
-
21
- try:
22
- import soundfile as sf # CPU-safe decoder (libsndfile)
23
- except Exception as e:
24
- raise RuntimeError("soundfile (pysoundfile) is required on CPU-only Spaces: pip install soundfile") from e
25
 
26
  from transformers import WhisperProcessor, WhisperForConditionalGeneration
27
  from diffusers import AutoPipelineForText2Image
28
 
29
- # -------------------------------
30
- # Global config & environment
31
- # -------------------------------
32
- DEVICE = "cpu" # free Spaces are CPU-only
33
  ASR_MODEL_ID = "codeninja3d/whisper-small-ls100"
34
- IMG_MODEL_ID = "runwayml/stable-diffusion-v1-5" # SD 1.5 is lighter for CPU
35
- DEFAULT_SIZE = 512 # safe default for CPU Spaces
36
- DEFAULT_STEPS = 15
37
- DEFAULT_CFG = 7.5
38
-
39
- # -------------------------------
40
- # Safe audio loader (CPU, no TorchCodec)
41
- # -------------------------------
42
- def load_audio_cpu(path_or_tuple, target_sr=16000):
43
- """Load mono waveform at target_sr as torch.float32 tensor on CPU.
44
- Accepts (sr, numpy) tuple from Gradio mic OR a filepath for uploads.
45
- """
46
- if isinstance(path_or_tuple, tuple):
47
- sr, wav_np = path_or_tuple
48
- wav = torch.tensor(wav_np, dtype=torch.float32)
49
- # Gradio numpy shape: [samples, channels] → make [1, samples] mono
50
  if wav.ndim > 1:
51
  wav = wav.mean(dim=-1, keepdim=True).T
52
  else:
53
- path = path_or_tuple
54
- # Try torchaudio first (if present), otherwise soundfile
55
- if _HAS_TORCHAUDIO:
56
  try:
57
- wav, sr = torchaudio.load(path)
58
  except Exception:
59
- data, sr = sf.read(path)
60
  wav = torch.tensor(data, dtype=torch.float32)
61
  else:
62
- data, sr = sf.read(path)
63
  wav = torch.tensor(data, dtype=torch.float32)
64
-
65
  if wav.ndim > 1:
66
  wav = wav.mean(dim=0, keepdim=True)
 
 
 
 
67
 
68
- if sr != target_sr:
69
- if _HAS_TORCHAUDIO:
70
- wav = torchaudio.functional.resample(wav, sr, target_sr)
71
- else:
72
- # Basic resample with torch if torchaudio not available
73
- import torch.nn.functional as F
74
- wav = wav.unsqueeze(0) # [1,1,T]
75
- T = wav.shape[-1]
76
- new_T = int(T * target_sr / sr)
77
- wav = F.interpolate(wav, size=new_T, mode="linear", align_corners=False).squeeze(0)
78
- sr = target_sr
79
-
80
- # normalize to [-1, 1]
81
- maxv = wav.abs().max().clamp(min=1e-8)
82
- wav = wav / maxv
83
- return wav.squeeze(0), sr
84
-
85
- # -------------------------------
86
- # Load models
87
- # -------------------------------
88
  processor = WhisperProcessor.from_pretrained(ASR_MODEL_ID)
89
  asr_model = WhisperForConditionalGeneration.from_pretrained(ASR_MODEL_ID).to(DEVICE).eval()
90
 
91
- pipe = AutoPipelineForText2Image.from_pretrained(
92
- IMG_MODEL_ID,
93
- torch_dtype=torch.float32, # CPU
94
- ).to(DEVICE)
95
- pipe.set_progress_bar_config(disable=True)
 
 
 
 
 
 
96
 
97
- # -------------------------------
98
- # Core function
99
- # -------------------------------
100
- def transcribe_and_generate(audio, size_choice, steps, cfg):
101
  if audio is None:
102
  return "⚠️ Please record or upload an audio clip.", None
103
 
104
- # --- Audio preprocessing ---
105
- wav, _ = load_audio_cpu(audio, target_sr=16000)
106
- inputs = processor.feature_extractor(
107
- wav.numpy(), sampling_rate=16000, return_tensors="pt"
108
- ).to(DEVICE)
109
-
110
  forced_ids = processor.get_decoder_prompt_ids(language="en", task="transcribe")
111
 
112
  with torch.no_grad():
113
- ids = asr_model.generate(
114
- **inputs,
115
- forced_decoder_ids=forced_ids,
116
- max_new_tokens=192,
117
- num_beams=3,
118
- early_stopping=True,
119
- )
120
  text = processor.tokenizer.batch_decode(ids, skip_special_tokens=True)[0].strip()
121
 
122
- # --- Diffusion generation (CPU) ---
 
 
 
 
 
 
 
 
 
123
  prompt = f"photorealistic, soft light, {text}, detailed"
124
- width = height = int(size_choice)
 
125
 
126
  try:
127
  with torch.inference_mode():
128
- image = pipe(
129
- prompt=prompt,
130
- num_inference_steps=int(steps),
131
- guidance_scale=float(cfg),
132
- width=width,
133
- height=height,
134
- ).images[0]
135
- gc.collect()
136
  return text, image
137
  except Exception as e:
138
- # Graceful fallback if OOM or other runtime error: retry smaller size
139
- if width > 512:
140
- try:
141
- with torch.inference_mode():
142
- image = pipe(
143
- prompt=prompt,
144
- num_inference_steps=int(steps),
145
- guidance_scale=float(cfg),
146
- width=512,
147
- height=512,
148
- ).images[0]
149
- gc.collect()
150
- return text + "\n\n(ℹ️ Auto-fallback to 512×512 due to CPU limits)", image
151
- except Exception:
152
- pass
153
- return text + f"\n\n❗ Image generation failed: {type(e).__name__}: {e}", None
154
 
155
- # -------------------------------
156
  # Gradio UI
157
- # -------------------------------
158
  with gr.Blocks(theme="soft") as demo:
159
- gr.Markdown("## 🎙️ Whisper → 🖼️ Image (CPU-only demo)\nUpload/record audio; get transcription and a generated image.")
 
 
 
 
160
  with gr.Row():
161
  audio_in = gr.Audio(type="numpy", label="🎧 Record or Upload Audio")
162
- with gr.Column():
163
- size_choice = gr.Dropdown([
164
- "384", "512", "640", "768"
165
- ], value=str(DEFAULT_SIZE), label="Image Size (square)")
166
- steps = gr.Slider(5, 30, value=DEFAULT_STEPS, step=1, label="Diffusion Steps")
167
- cfg = gr.Slider(1.0, 12.0, value=DEFAULT_CFG, step=0.5, label="CFG (guidance)")
168
- with gr.Row():
169
- text_out = gr.Textbox(label="📄 Transcription")
170
- img_out = gr.Image(label="🖼️ Generated Image", show_label=True)
171
 
 
 
172
  run_btn = gr.Button("Transcribe + Generate", variant="primary")
 
173
  run_btn.click(
174
  fn=transcribe_and_generate,
175
- inputs=[audio_in, size_choice, steps, cfg],
176
- outputs=[text_out, img_out]
177
  )
178
 
179
- # Limit concurrency for CPU stability
180
- demo.queue().launch(server_name="0.0.0.0", server_port=7860)
181
-
 
1
  #!/usr/bin/env python3
2
  # ------------------------------------------------------------
3
+ # Whisper Small LS-100 → Text → Image (CPU optimized)
4
+ # Adds ⚡ Fast / 🎨 Quality mode for Hugging Face Spaces
5
  # Author: Murali Chandran (codeninja3d)
6
  # ------------------------------------------------------------
7
 
8
+ import os, gc, torch, gradio as gr
 
 
 
 
 
9
  try:
10
+ import torchaudio
 
11
  except Exception:
 
12
  torchaudio = None
13
+ import soundfile as sf
 
 
 
 
14
 
15
  from transformers import WhisperProcessor, WhisperForConditionalGeneration
16
  from diffusers import AutoPipelineForText2Image
17
 
18
+ # ------------------------------------------------------------
19
+ # Config
20
+ # ------------------------------------------------------------
21
+ DEVICE = "cpu"
22
  ASR_MODEL_ID = "codeninja3d/whisper-small-ls100"
23
+
24
+ # ------------------------------------------------------------
25
+ # Helpers
26
+ # ------------------------------------------------------------
27
+ def load_audio(audio, target_sr=16000):
28
+ """Load and normalize mono waveform (CPU-safe)."""
29
+ if isinstance(audio, tuple):
30
+ sr, arr = audio
31
+ wav = torch.tensor(arr, dtype=torch.float32)
 
 
 
 
 
 
 
32
  if wav.ndim > 1:
33
  wav = wav.mean(dim=-1, keepdim=True).T
34
  else:
35
+ if torchaudio:
 
 
36
  try:
37
+ wav, sr = torchaudio.load(audio)
38
  except Exception:
39
+ data, sr = sf.read(audio)
40
  wav = torch.tensor(data, dtype=torch.float32)
41
  else:
42
+ data, sr = sf.read(audio)
43
  wav = torch.tensor(data, dtype=torch.float32)
 
44
  if wav.ndim > 1:
45
  wav = wav.mean(dim=0, keepdim=True)
46
+ if sr != target_sr and torchaudio:
47
+ wav = torchaudio.functional.resample(wav, sr, target_sr)
48
+ wav = wav / wav.abs().max()
49
+ return wav.squeeze(0)
50
 
51
+ # ------------------------------------------------------------
52
+ # Load Whisper
53
+ # ------------------------------------------------------------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
  processor = WhisperProcessor.from_pretrained(ASR_MODEL_ID)
55
  asr_model = WhisperForConditionalGeneration.from_pretrained(ASR_MODEL_ID).to(DEVICE).eval()
56
 
57
+ # ------------------------------------------------------------
58
+ # Load both diffusion models lazily (to save RAM)
59
+ # ------------------------------------------------------------
60
+ pipe_cache = {}
61
+
62
+ def get_pipeline(model_id):
63
+ if model_id not in pipe_cache:
64
+ pipe = AutoPipelineForText2Image.from_pretrained(model_id, torch_dtype=torch.float32).to(DEVICE)
65
+ pipe.set_progress_bar_config(disable=True)
66
+ pipe_cache[model_id] = pipe
67
+ return pipe_cache[model_id]
68
 
69
+ # ------------------------------------------------------------
70
+ # Main logic
71
+ # ------------------------------------------------------------
72
+ def transcribe_and_generate(audio, mode):
73
  if audio is None:
74
  return "⚠️ Please record or upload an audio clip.", None
75
 
76
+ # --- Transcribe ---
77
+ wav = load_audio(audio)
78
+ inputs = processor.feature_extractor(wav.numpy(), sampling_rate=16000, return_tensors="pt").to(DEVICE)
 
 
 
79
  forced_ids = processor.get_decoder_prompt_ids(language="en", task="transcribe")
80
 
81
  with torch.no_grad():
82
+ ids = asr_model.generate(**inputs, forced_decoder_ids=forced_ids, max_new_tokens=192, num_beams=3)
 
 
 
 
 
 
83
  text = processor.tokenizer.batch_decode(ids, skip_special_tokens=True)[0].strip()
84
 
85
+ # --- Image generation ---
86
+ if mode == "Fast":
87
+ model_id = "stabilityai/sd-turbo"
88
+ width = height = 384
89
+ steps, cfg = 4, 1.0
90
+ else:
91
+ model_id = "runwayml/stable-diffusion-v1-5"
92
+ width = height = 512
93
+ steps, cfg = 15, 7.5
94
+
95
  prompt = f"photorealistic, soft light, {text}, detailed"
96
+ gc.collect()
97
+ pipe = get_pipeline(model_id)
98
 
99
  try:
100
  with torch.inference_mode():
101
+ image = pipe(prompt=prompt, num_inference_steps=steps,
102
+ guidance_scale=cfg, width=width, height=height).images[0]
 
 
 
 
 
 
103
  return text, image
104
  except Exception as e:
105
+ return f"{text}\\n\\n❗ Image generation failed: {e}", None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106
 
107
+ # ------------------------------------------------------------
108
  # Gradio UI
109
+ # ------------------------------------------------------------
110
  with gr.Blocks(theme="soft") as demo:
111
+ gr.Markdown("""
112
+ ## 🎙️ Whisper → 🖼️ Image Generator
113
+ Choose **Fast** (⚡ quick demo) or **Quality** (🎨 detailed, slower).
114
+ """)
115
+
116
  with gr.Row():
117
  audio_in = gr.Audio(type="numpy", label="🎧 Record or Upload Audio")
118
+ mode = gr.Radio(["Fast", "Quality"], value="Fast", label="Mode")
 
 
 
 
 
 
 
 
119
 
120
+ text_out = gr.Textbox(label="📄 Transcription")
121
+ img_out = gr.Image(label="🖼️ Generated Image")
122
  run_btn = gr.Button("Transcribe + Generate", variant="primary")
123
+
124
  run_btn.click(
125
  fn=transcribe_and_generate,
126
+ inputs=[audio_in, mode],
127
+ outputs=[text_out, img_out],
128
  )
129
 
130
+ demo.launch(server_name="0.0.0.0", server_port=7860)