nifty-coder commited on
Commit
1034c3a
·
1 Parent(s): 638586a

Add R2 storage integration

Browse files
Files changed (2) hide show
  1. main.py +228 -19
  2. requirements.txt +2 -1
main.py CHANGED
@@ -8,7 +8,10 @@ import re
8
  import json
9
  import hashlib
10
  import io
 
11
  from datetime import datetime
 
 
12
  from fastapi.middleware.cors import CORSMiddleware
13
  from fastapi.responses import FileResponse
14
  from pydantic import BaseModel
@@ -121,6 +124,67 @@ try:
121
  except Exception as e:
122
  logger.warning(f"Firebase Admin setup skipped: {e}")
123
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
124
  PROFILES_FILE = os.path.join(CACHE_DIR, "profiles.json")
125
 
126
  class ProfileIn(BaseModel):
@@ -267,41 +331,94 @@ def run_demucs_and_extract(input_path: str, tmpdir: str) -> str:
267
 
268
 
269
  @app.post("/upload")
270
- def process_upload(
271
  file: UploadFile = File(...),
272
  tos_agreed: bool = Form(...),
 
273
  background_tasks: BackgroundTasks = None
274
  ):
275
  if not tos_agreed:
276
  raise HTTPException(status_code=400, detail="You must agree to the Terms of Service to upload content.")
277
-
278
- # (Optional) Content ID check would go here
279
-
 
 
 
 
280
  tmpdir = tempfile.mkdtemp()
281
  try:
282
  input_path = os.path.join(tmpdir, file.filename)
283
  audio_path = os.path.join(tmpdir, "audio.mp3")
284
 
285
- with open(input_path, "wb") as f: f.write(file.file.read())
 
286
 
287
- subprocess.run([FFMPEG_PATH, "-y", "-i", input_path, "-ac", "2", "-ar", "44100", audio_path], check=True)
 
 
 
 
288
  extracted_dir = run_demucs_and_extract(audio_path, tmpdir)
289
 
290
- logger.info(f"Zipping directory: {extracted_dir}, Contents: {os.listdir(extracted_dir)}")
291
- final_zip_path = os.path.join(tmpdir, "extracted_stems.zip")
292
- with zipfile.ZipFile(final_zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
 
 
 
293
  for root, dirs, files in os.walk(extracted_dir):
294
- for file in files:
295
- file_path = os.path.join(root, file)
296
- arcname = os.path.relpath(file_path, extracted_dir)
297
- zipf.write(file_path, arcname)
298
-
299
- digest = hashlib.sha256(open(final_zip_path, 'rb').read()).hexdigest()
300
- cache_path = os.path.join(CACHE_DIR, f"{digest}.zip")
301
- shutil.copyfile(final_zip_path, cache_path)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
302
 
303
- if background_tasks: background_tasks.add_task(shutil.rmtree, tmpdir, True)
304
- return FileResponse(cache_path, filename="extracted_stems.zip", media_type="application/zip", headers={"X-Cache-Key": digest})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
305
  except HTTPException as he:
306
  shutil.rmtree(tmpdir, ignore_errors=True)
307
  raise he
@@ -368,6 +485,98 @@ def get_stem(key: str, filename: str):
368
  logger.error(f"Error extracting stem: {e}")
369
  raise HTTPException(status_code=500, detail="Failed to extract stem from archive")
370
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
371
  if __name__ == "__main__":
372
  import uvicorn
373
  # Default to 7860 for Hugging Face Spaces
 
8
  import json
9
  import hashlib
10
  import io
11
+ import uuid
12
  from datetime import datetime
13
+ import boto3
14
+ from botocore.client import Config
15
  from fastapi.middleware.cors import CORSMiddleware
16
  from fastapi.responses import FileResponse
17
  from pydantic import BaseModel
 
124
  except Exception as e:
125
  logger.warning(f"Firebase Admin setup skipped: {e}")
126
 
127
+ # --- Cloudflare R2 Setup ---
128
+ R2_ENDPOINT = os.environ.get('R2_ENDPOINT')
129
+ R2_ACCESS_KEY_ID = os.environ.get('R2_ACCESS_KEY_ID')
130
+ R2_SECRET_ACCESS_KEY = os.environ.get('R2_SECRET_ACCESS_KEY')
131
+ R2_BUCKET_NAME = os.environ.get('R2_BUCKET_NAME')
132
+ R2_ACCOUNT_ID = os.environ.get('R2_ACCOUNT_ID')
133
+
134
+ s3_client = None
135
+ R2_ENABLED = False
136
+
137
+ if all([R2_ENDPOINT, R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY, R2_BUCKET_NAME]):
138
+ try:
139
+ s3_client = boto3.client(
140
+ 's3',
141
+ endpoint_url=R2_ENDPOINT,
142
+ aws_access_key_id=R2_ACCESS_KEY_ID,
143
+ aws_secret_access_key=R2_SECRET_ACCESS_KEY,
144
+ config=Config(signature_version='s3v4'),
145
+ region_name='auto' # R2 uses 'auto' for region
146
+ )
147
+ R2_ENABLED = True
148
+ logger.info(f"R2 client initialized for bucket: {R2_BUCKET_NAME}")
149
+ except Exception as e:
150
+ logger.error(f"Failed to initialize R2 client: {e}")
151
+ else:
152
+ logger.warning("R2 credentials not found. File storage will use local temp directory.")
153
+
154
+ # --- JWT Verification ---
155
+ def verify_firebase_token(authorization: str) -> str:
156
+ """
157
+ Verify Firebase ID token from Authorization header.
158
+ Returns the user's UID if valid.
159
+ Raises HTTPException if invalid.
160
+ """
161
+ if not FIREBASE_INITIALIZED:
162
+ raise HTTPException(status_code=500, detail="Firebase not initialized")
163
+
164
+ if not authorization:
165
+ raise HTTPException(status_code=401, detail="Missing Authorization header")
166
+
167
+ # Extract token from "Bearer <token>" format
168
+ parts = authorization.split(' ')
169
+ if len(parts) != 2 or parts[0].lower() != 'bearer':
170
+ raise HTTPException(status_code=401, detail="Invalid Authorization header format")
171
+
172
+ token = parts[1]
173
+
174
+ try:
175
+ decoded_token = firebase_auth.verify_id_token(token)
176
+ uid = decoded_token.get('uid')
177
+ if not uid:
178
+ raise HTTPException(status_code=401, detail="Invalid token: missing uid")
179
+ return uid
180
+ except firebase_admin.exceptions.InvalidArgumentError:
181
+ raise HTTPException(status_code=401, detail="Invalid token format")
182
+ except firebase_admin.exceptions.ExpiredIdTokenError:
183
+ raise HTTPException(status_code=401, detail="Token expired")
184
+ except Exception as e:
185
+ logger.error(f"Token verification failed: {e}")
186
+ raise HTTPException(status_code=401, detail="Token verification failed")
187
+
188
  PROFILES_FILE = os.path.join(CACHE_DIR, "profiles.json")
189
 
190
  class ProfileIn(BaseModel):
 
331
 
332
 
333
  @app.post("/upload")
334
+ async def process_upload(
335
  file: UploadFile = File(...),
336
  tos_agreed: bool = Form(...),
337
+ authorization: str = Header(None),
338
  background_tasks: BackgroundTasks = None
339
  ):
340
  if not tos_agreed:
341
  raise HTTPException(status_code=400, detail="You must agree to the Terms of Service to upload content.")
342
+
343
+ # Verify Firebase token and get UID
344
+ uid = verify_firebase_token(authorization) if authorization else None
345
+
346
+ # Generate unique song ID
347
+ song_id = str(uuid.uuid4())
348
+
349
  tmpdir = tempfile.mkdtemp()
350
  try:
351
  input_path = os.path.join(tmpdir, file.filename)
352
  audio_path = os.path.join(tmpdir, "audio.mp3")
353
 
354
+ with open(input_path, "wb") as f:
355
+ f.write(file.file.read())
356
 
357
+ # Convert to standard format
358
+ subprocess.run([FFMPEG_PATH, "-y", "-i", input_path, "-ac", "2", "-ar", "44100", audio_path],
359
+ check=True, capture_output=True, text=True)
360
+
361
+ # Process with Demucs
362
  extracted_dir = run_demucs_and_extract(audio_path, tmpdir)
363
 
364
+ # If R2 is enabled and user is authenticated, upload to R2
365
+ if R2_ENABLED and uid:
366
+ logger.info(f"Uploading stems to R2 for user {uid}, song {song_id}")
367
+
368
+ # Upload each stem to R2
369
+ uploaded_files = []
370
  for root, dirs, files in os.walk(extracted_dir):
371
+ for filename in files:
372
+ if filename.endswith('.mp3'):
373
+ file_path = os.path.join(root, filename)
374
+ s3_key = f"uploads/{uid}/{song_id}/{filename}"
375
+
376
+ with open(file_path, 'rb') as f:
377
+ s3_client.upload_fileobj(
378
+ f,
379
+ R2_BUCKET_NAME,
380
+ s3_key,
381
+ ExtraArgs={'ContentType': 'audio/mpeg'}
382
+ )
383
+ uploaded_files.append(filename)
384
+ logger.info(f"Uploaded {filename} to R2")
385
+
386
+ # Clean up temp directory
387
+ if background_tasks:
388
+ background_tasks.add_task(shutil.rmtree, tmpdir, True)
389
+
390
+ return {
391
+ "song_id": song_id,
392
+ "uid": uid,
393
+ "files": uploaded_files,
394
+ "message": "Upload successful. Files stored in R2."
395
+ }
396
 
397
+ else:
398
+ # Fallback to local ZIP storage (backward compatibility)
399
+ logger.info(f"Using local storage for song {song_id}")
400
+ final_zip_path = os.path.join(tmpdir, "extracted_stems.zip")
401
+ with zipfile.ZipFile(final_zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
402
+ for root, dirs, files in os.walk(extracted_dir):
403
+ for file in files:
404
+ file_path = os.path.join(root, file)
405
+ arcname = os.path.relpath(file_path, extracted_dir)
406
+ zipf.write(file_path, arcname)
407
+
408
+ digest = hashlib.sha256(open(final_zip_path, 'rb').read()).hexdigest()
409
+ cache_path = os.path.join(CACHE_DIR, f"{digest}.zip")
410
+ shutil.copyfile(final_zip_path, cache_path)
411
+
412
+ if background_tasks:
413
+ background_tasks.add_task(shutil.rmtree, tmpdir, True)
414
+
415
+ return FileResponse(
416
+ cache_path,
417
+ filename="extracted_stems.zip",
418
+ media_type="application/zip",
419
+ headers={"X-Cache-Key": digest}
420
+ )
421
+
422
  except HTTPException as he:
423
  shutil.rmtree(tmpdir, ignore_errors=True)
424
  raise he
 
485
  logger.error(f"Error extracting stem: {e}")
486
  raise HTTPException(status_code=500, detail="Failed to extract stem from archive")
487
 
488
+
489
+ # --- R2 Presigned URL Endpoints ---
490
+
491
+ class PresignedUrlRequest(BaseModel):
492
+ song_id: str
493
+ filename: str
494
+
495
+ @app.post("/presigned-url")
496
+ async def get_presigned_url(
497
+ request: PresignedUrlRequest,
498
+ authorization: str = Header(...)
499
+ ):
500
+ """
501
+ Generate a presigned URL for accessing a file in R2.
502
+ Requires Firebase authentication.
503
+ """
504
+ if not R2_ENABLED:
505
+ raise HTTPException(status_code=503, detail="R2 storage not configured")
506
+
507
+ # Verify token and get UID
508
+ uid = verify_firebase_token(authorization)
509
+
510
+ # Construct S3 key
511
+ s3_key = f"uploads/{uid}/{request.song_id}/{request.filename}"
512
+
513
+ try:
514
+ # Generate presigned URL (1 hour expiry)
515
+ presigned_url = s3_client.generate_presigned_url(
516
+ 'get_object',
517
+ Params={
518
+ 'Bucket': R2_BUCKET_NAME,
519
+ 'Key': s3_key
520
+ },
521
+ ExpiresIn=3600 # 1 hour
522
+ )
523
+
524
+ return {
525
+ "url": presigned_url,
526
+ "expires_in": 3600,
527
+ "filename": request.filename
528
+ }
529
+ except Exception as e:
530
+ logger.error(f"Failed to generate presigned URL: {e}")
531
+ raise HTTPException(status_code=500, detail="Failed to generate presigned URL")
532
+
533
+
534
+ @app.get("/list-stems/{song_id}")
535
+ async def list_stems(
536
+ song_id: str,
537
+ authorization: str = Header(...)
538
+ ):
539
+ """
540
+ List all stem files for a given song ID.
541
+ Requires Firebase authentication.
542
+ """
543
+ if not R2_ENABLED:
544
+ raise HTTPException(status_code=503, detail="R2 storage not configured")
545
+
546
+ # Verify token and get UID
547
+ uid = verify_firebase_token(authorization)
548
+
549
+ # List objects in R2 with the prefix
550
+ prefix = f"uploads/{uid}/{song_id}/"
551
+
552
+ try:
553
+ response = s3_client.list_objects_v2(
554
+ Bucket=R2_BUCKET_NAME,
555
+ Prefix=prefix
556
+ )
557
+
558
+ files = []
559
+ if 'Contents' in response:
560
+ for obj in response['Contents']:
561
+ # Extract filename from key
562
+ filename = obj['Key'].split('/')[-1]
563
+ if filename: # Skip directory markers
564
+ files.append({
565
+ "filename": filename,
566
+ "size": obj['Size'],
567
+ "last_modified": obj['LastModified'].isoformat()
568
+ })
569
+
570
+ return {
571
+ "song_id": song_id,
572
+ "files": files,
573
+ "count": len(files)
574
+ }
575
+ except Exception as e:
576
+ logger.error(f"Failed to list stems: {e}")
577
+ raise HTTPException(status_code=500, detail="Failed to list stems")
578
+
579
+
580
  if __name__ == "__main__":
581
  import uvicorn
582
  # Default to 7860 for Hugging Face Spaces
requirements.txt CHANGED
@@ -9,4 +9,5 @@ firebase-admin
9
  torch
10
  torchaudio
11
  torchcodec
12
- demucs
 
 
9
  torch
10
  torchaudio
11
  torchcodec
12
+ demucs
13
+ boto3>=1.34.0