cazyundee commited on
Commit
4d82070
·
verified ·
1 Parent(s): b7bdd13

Clean Respite API: FastAPI app with Gradio mounted, no GPU touch

Browse files
Files changed (1) hide show
  1. app.py +55 -84
app.py CHANGED
@@ -7,7 +7,6 @@ import traceback
7
  import torch
8
  import torchaudio
9
  import gradio as gr
10
- import spaces
11
  from fastapi import FastAPI
12
  from fastapi.responses import JSONResponse
13
  from einops import rearrange
@@ -22,14 +21,6 @@ hf_token = os.environ.get("HF_TOKEN")
22
  if hf_token:
23
  login(token=hf_token)
24
 
25
- try:
26
- @spaces.GPU(duration=1)
27
- def _gpu_startup_touch():
28
- return "ok"
29
- _gpu_startup_touch()
30
- except Exception as e:
31
- print(f"Warning: ZeroGPU touch failed (running CPU-only): {e}", flush=True)
32
-
33
 
34
  def _log(message):
35
  print(message.encode("ascii", "backslashreplace").decode("ascii"), flush=True)
@@ -54,7 +45,7 @@ API_RESOURCES = {
54
  "audio_generation": {
55
  "name": "Audio generation",
56
  "description": "Generate music or sound effects from a text prompt.",
57
- "endpoint": "/api/audio/generate",
58
  "method": "POST",
59
  "input": {
60
  "prompt": "string",
@@ -136,86 +127,66 @@ def generate_audio(prompt, duration, steps, cfg_scale, seed, model_name):
136
 
137
 
138
  # ---------------------------------------------------------------------------
139
- # Gradio UI
140
  # ---------------------------------------------------------------------------
141
 
142
- with gr.Blocks(title="Respite API") as demo:
143
- gr.Markdown("# Respite API - Music & SFX Generation")
144
- gr.Markdown(
145
- "Generate music and sound effects using "
146
- "Stability AI's Stable Audio 3 Small models."
147
- )
148
-
149
- with gr.Row():
150
- with gr.Column():
151
- model_name = gr.Dropdown(
152
- choices=["small-music", "small-sfx"],
153
- value="small-music", label="Model",
154
- )
155
- prompt = gr.Textbox(
156
- label="Prompt",
157
- placeholder="Describe the music or sound effect you want to generate...",
158
- lines=2,
159
- )
160
- duration = gr.Slider(minimum=1, maximum=120, value=30, step=1, label="Duration (seconds)")
161
- steps = gr.Slider(minimum=1, maximum=50, value=8, step=1, label="Steps")
162
- cfg_scale = gr.Slider(minimum=0.0, maximum=10.0, value=1.0, step=0.1, label="CFG Scale")
163
- seed = gr.Number(value=-1, label="Seed (-1 for random)")
164
- btn = gr.Button("Generate", variant="primary")
165
-
166
- with gr.Column():
167
- audio_output = gr.Audio(label="Generated Audio", type="filepath")
168
-
169
- btn.click(
170
- fn=generate_audio,
171
- inputs=[prompt, duration, steps, cfg_scale, seed, model_name],
172
- outputs=audio_output,
173
- )
 
 
 
174
 
175
 
176
  # ---------------------------------------------------------------------------
177
- # Inject discovery routes into Gradio's internal FastAPI server.
178
- #
179
- # The HF Spaces Gradio runner calls demo.launch() directly, so our own
180
- # FastAPI app is never served. We monkey-patch Blocks.launch so that
181
- # AFTER Gradio creates its server, we inject routes onto that server.
182
  # ---------------------------------------------------------------------------
183
 
184
- _original_blocks_launch = gr.Blocks.launch
185
 
186
 
187
- def _patched_blocks_launch(self, *args, **kwargs):
188
- _log("Intercepted Blocks.launch() - calling original...")
189
- try:
190
- result = _original_blocks_launch(self, *args, **kwargs)
191
- except Exception:
192
- _log("ERROR in original launch:")
193
- _log(traceback.format_exc())
194
- raise
195
-
196
- if self is demo:
197
- try:
198
- fa_app = getattr(self, "app", None)
199
- _log(f"demo.app is: {fa_app}")
200
- if fa_app is not None:
201
- @fa_app.get("/respite/resources")
202
- def _resources():
203
- return JSONResponse({"resources": API_RESOURCES})
204
-
205
- @fa_app.get("/respite/specs")
206
- def _specs():
207
- return JSONResponse({**API_SPECS, "runtime": _get_runtime_specs()})
208
-
209
- _log("Respite API routes injected successfully")
210
- else:
211
- _log("Warning: demo.app is None after launch")
212
- except Exception:
213
- _log("ERROR injecting routes:")
214
- _log(traceback.format_exc())
215
-
216
- return result
217
-
218
-
219
- gr.Blocks.launch = _patched_blocks_launch
220
-
221
- demo.queue(max_size=4, default_concurrency_limit=1)
 
7
  import torch
8
  import torchaudio
9
  import gradio as gr
 
10
  from fastapi import FastAPI
11
  from fastapi.responses import JSONResponse
12
  from einops import rearrange
 
21
  if hf_token:
22
  login(token=hf_token)
23
 
 
 
 
 
 
 
 
 
24
 
25
  def _log(message):
26
  print(message.encode("ascii", "backslashreplace").decode("ascii"), flush=True)
 
45
  "audio_generation": {
46
  "name": "Audio generation",
47
  "description": "Generate music or sound effects from a text prompt.",
48
+ "endpoint": "/respite/audio/generate",
49
  "method": "POST",
50
  "input": {
51
  "prompt": "string",
 
127
 
128
 
129
  # ---------------------------------------------------------------------------
130
+ # Gradio UI (built inside a function to keep it out of global scope)
131
  # ---------------------------------------------------------------------------
132
 
133
+ def _build_ui():
134
+ with gr.Blocks(title="Respite API") as ui:
135
+ gr.Markdown("# Respite API - Music & SFX Generation")
136
+ gr.Markdown(
137
+ "Generate music and sound effects using "
138
+ "Stability AI's Stable Audio 3 Small models."
139
+ )
140
+
141
+ with gr.Row():
142
+ with gr.Column():
143
+ model_name = gr.Dropdown(
144
+ choices=["small-music", "small-sfx"],
145
+ value="small-music", label="Model",
146
+ )
147
+ prompt = gr.Textbox(
148
+ label="Prompt",
149
+ placeholder="Describe the music or sound effect you want to generate...",
150
+ lines=2,
151
+ )
152
+ duration = gr.Slider(minimum=1, maximum=120, value=30, step=1, label="Duration (seconds)")
153
+ steps = gr.Slider(minimum=1, maximum=50, value=8, step=1, label="Steps")
154
+ cfg_scale = gr.Slider(minimum=0.0, maximum=10.0, value=1.0, step=0.1, label="CFG Scale")
155
+ seed = gr.Number(value=-1, label="Seed (-1 for random)")
156
+ btn = gr.Button("Generate", variant="primary")
157
+
158
+ with gr.Column():
159
+ audio_output = gr.Audio(label="Generated Audio", type="filepath")
160
+
161
+ btn.click(
162
+ fn=generate_audio,
163
+ inputs=[prompt, duration, steps, cfg_scale, seed, model_name],
164
+ outputs=audio_output,
165
+ )
166
+
167
+ return ui
168
 
169
 
170
  # ---------------------------------------------------------------------------
171
+ # FastAPI application with discovery routes
 
 
 
 
172
  # ---------------------------------------------------------------------------
173
 
174
+ app = FastAPI(title="Respite API")
175
 
176
 
177
+ @app.get("/respite/resources")
178
+ def resources():
179
+ return JSONResponse({"resources": API_RESOURCES})
180
+
181
+
182
+ @app.get("/respite/specs")
183
+ def specs():
184
+ return JSONResponse({**API_SPECS, "runtime": _get_runtime_specs()})
185
+
186
+
187
+ # Mount the Gradio UI onto the FastAPI app.
188
+ # The HF Spaces Gradio runner should detect `app` (FastAPI) as the
189
+ # entrypoint and serve it directly.
190
+ app = gr.mount_gradio_app(app, _build_ui(), path="/")
191
+
192
+ _log("Respite API application initialized")