gcharanteja commited on
Commit
9d7ff8b
·
1 Parent(s): 739c42a

url fixced

Browse files
Files changed (2) hide show
  1. app.py +21 -5
  2. main.py +27 -11
app.py CHANGED
@@ -11,6 +11,22 @@ import httpx
11
  BASE_URL = os.getenv("API_BASE_URL", "http://127.0.0.1:7860")
12
 
13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  def create_gradio_app():
15
  """Create and return the Gradio Blocks app for Music Memories."""
16
 
@@ -160,15 +176,15 @@ def create_gradio_app():
160
  except Exception as e:
161
  return "Error", {"error": str(e)}
162
 
163
- def song_stream_url_fn(song_id):
164
  try:
165
  song_id_i = _maybe_int(song_id)
166
  if song_id_i is None:
167
  raise ValueError("song_id is required")
168
- location = _redirect_location(f"/songs/{song_id_i}/stream")
169
- if not location:
170
- return "No redirect returned", ""
171
- return "Success!", location
172
  except Exception as e:
173
  return "Error", str(e)
174
 
 
11
  BASE_URL = os.getenv("API_BASE_URL", "http://127.0.0.1:7860")
12
 
13
 
14
+ def _public_base_url(request: gr.Request | None) -> str:
15
+ if request is None:
16
+ return os.getenv("PUBLIC_BASE_URL", "").rstrip("/")
17
+ headers = {k.lower(): v for k, v in dict(request.headers).items()}
18
+ origin = headers.get("origin")
19
+ if origin:
20
+ return origin.rstrip("/")
21
+ proto = headers.get("x-forwarded-proto")
22
+ host = headers.get("x-forwarded-host") or headers.get("host")
23
+ if proto and host:
24
+ return f"{proto}://{host}".rstrip("/")
25
+ if host:
26
+ return f"https://{host}".rstrip("/")
27
+ return os.getenv("PUBLIC_BASE_URL", "").rstrip("/")
28
+
29
+
30
  def create_gradio_app():
31
  """Create and return the Gradio Blocks app for Music Memories."""
32
 
 
176
  except Exception as e:
177
  return "Error", {"error": str(e)}
178
 
179
+ def song_stream_url_fn(song_id, request: gr.Request | None = None):
180
  try:
181
  song_id_i = _maybe_int(song_id)
182
  if song_id_i is None:
183
  raise ValueError("song_id is required")
184
+ public_base = _public_base_url(request)
185
+ if public_base:
186
+ return "Success!", f"{public_base}/songs/{song_id_i}/stream"
187
+ return "Success!", f"/songs/{song_id_i}/stream"
188
  except Exception as e:
189
  return "Error", str(e)
190
 
main.py CHANGED
@@ -1,5 +1,5 @@
1
  from contextlib import asynccontextmanager
2
- from fastapi import FastAPI, Query, HTTPException, UploadFile, File, Form
3
  from fastapi.responses import JSONResponse, RedirectResponse, StreamingResponse
4
  import gradio as gr
5
  from app import gradio_app
@@ -201,6 +201,7 @@ async def get_song(song_id: int):
201
 
202
  @app.post("/songs")
203
  async def create_song(
 
204
  title: str = Form(...),
205
  artist: str = Form(...),
206
  album: str = Form(None),
@@ -241,10 +242,14 @@ async def create_song(
241
 
242
  response = {"status": "success", "song": song}
243
  if minio_info:
 
 
244
  response["audio"] = {
245
  "uploaded": True,
246
  "size": minio_info["size"],
247
- "stream_url": minio_info["presigned_url"],
 
 
248
  }
249
  return response
250
 
@@ -271,14 +276,23 @@ async def delete_song_endpoint(song_id: int):
271
 
272
  @app.get("/songs/{song_id}/stream")
273
  async def stream_song(song_id: int):
274
- """Stream an MP3 file from MinIO (redirects to presigned URL)."""
275
- stream_info = stream_mp3_file(song_id)
276
- if not stream_info:
277
- # Fallback: try to get from local storage
 
 
 
278
  raise HTTPException(status_code=404, detail="Audio file not found")
279
-
280
- # Redirect to MinIO presigned URL for direct streaming
281
- return RedirectResponse(url=stream_info["presigned_url"])
 
 
 
 
 
 
282
 
283
 
284
  @app.get("/songs/{song_id}/download")
@@ -299,7 +313,7 @@ async def download_song(song_id: int):
299
 
300
 
301
  @app.post("/songs/{song_id}/upload-audio")
302
- async def upload_audio(song_id: int, audio_file: UploadFile = File(...)):
303
  """Upload/update MP3 file for an existing song."""
304
  # Verify song exists
305
  song = get_song_by_id(song_id)
@@ -336,7 +350,9 @@ async def upload_audio(song_id: int, audio_file: UploadFile = File(...)):
336
  "audio": {
337
  "uploaded": True,
338
  "size": minio_info["size"],
339
- "stream_url": minio_info["presigned_url"],
 
 
340
  },
341
  }
342
 
 
1
  from contextlib import asynccontextmanager
2
+ from fastapi import FastAPI, Query, HTTPException, UploadFile, File, Form, Request
3
  from fastapi.responses import JSONResponse, RedirectResponse, StreamingResponse
4
  import gradio as gr
5
  from app import gradio_app
 
201
 
202
  @app.post("/songs")
203
  async def create_song(
204
+ request: Request,
205
  title: str = Form(...),
206
  artist: str = Form(...),
207
  album: str = Form(None),
 
242
 
243
  response = {"status": "success", "song": song}
244
  if minio_info:
245
+ public_stream_url = f"{request.base_url}songs/{song['id']}/stream"
246
+ public_download_url = f"{request.base_url}songs/{song['id']}/download"
247
  response["audio"] = {
248
  "uploaded": True,
249
  "size": minio_info["size"],
250
+ "stream_url": public_stream_url,
251
+ "download_url": public_download_url,
252
+ "minio_presigned_url": minio_info["presigned_url"],
253
  }
254
  return response
255
 
 
276
 
277
  @app.get("/songs/{song_id}/stream")
278
  async def stream_song(song_id: int):
279
+ """Stream an MP3 file through the FastAPI app domain.
280
+
281
+ NOTE: Redirecting to a MinIO presigned URL may point at an internal hostname (e.g. 127.0.0.1)
282
+ in hosted environments like Hugging Face Spaces, which browsers cannot reach.
283
+ """
284
+ file_data = download_mp3_file(song_id)
285
+ if not file_data:
286
  raise HTTPException(status_code=404, detail="Audio file not found")
287
+
288
+ song = get_song_by_id(song_id)
289
+ filename = f"{song.get('title', 'song')}_{song_id}.mp3" if song else f"song_{song_id}.mp3"
290
+
291
+ return StreamingResponse(
292
+ io.BytesIO(file_data),
293
+ media_type="audio/mpeg",
294
+ headers={"Content-Disposition": f"inline; filename={filename}"},
295
+ )
296
 
297
 
298
  @app.get("/songs/{song_id}/download")
 
313
 
314
 
315
  @app.post("/songs/{song_id}/upload-audio")
316
+ async def upload_audio(request: Request, song_id: int, audio_file: UploadFile = File(...)):
317
  """Upload/update MP3 file for an existing song."""
318
  # Verify song exists
319
  song = get_song_by_id(song_id)
 
350
  "audio": {
351
  "uploaded": True,
352
  "size": minio_info["size"],
353
+ "stream_url": f"{request.base_url}songs/{song_id}/stream",
354
+ "download_url": f"{request.base_url}songs/{song_id}/download",
355
+ "minio_presigned_url": minio_info["presigned_url"],
356
  },
357
  }
358