Spaces:
Runtime error
Runtime error
nifty-coder commited on
Commit ·
652ff30
1
Parent(s): 1034c3a
R2 further integration and Recaptcha
Browse files- main.py +139 -3
- requirements.txt +2 -1
main.py
CHANGED
|
@@ -9,6 +9,7 @@ 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
|
|
@@ -151,6 +152,41 @@ if all([R2_ENDPOINT, R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY, R2_BUCKET_NAME]):
|
|
| 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 |
"""
|
|
@@ -334,11 +370,17 @@ def run_demucs_and_extract(input_path: str, tmpdir: str) -> str:
|
|
| 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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 342 |
|
| 343 |
# Verify Firebase token and get UID
|
| 344 |
uid = verify_firebase_token(authorization) if authorization else None
|
|
@@ -365,7 +407,7 @@ async def process_upload(
|
|
| 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:
|
|
@@ -373,12 +415,20 @@ async def process_upload(
|
|
| 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={
|
|
|
|
|
|
|
|
|
|
| 382 |
)
|
| 383 |
uploaded_files.append(filename)
|
| 384 |
logger.info(f"Uploaded {filename} to R2")
|
|
@@ -391,6 +441,7 @@ async def process_upload(
|
|
| 391 |
"song_id": song_id,
|
| 392 |
"uid": uid,
|
| 393 |
"files": uploaded_files,
|
|
|
|
| 394 |
"message": "Upload successful. Files stored in R2."
|
| 395 |
}
|
| 396 |
|
|
@@ -577,6 +628,91 @@ async def list_stems(
|
|
| 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
|
|
|
|
| 9 |
import hashlib
|
| 10 |
import io
|
| 11 |
import uuid
|
| 12 |
+
import requests
|
| 13 |
from datetime import datetime
|
| 14 |
import boto3
|
| 15 |
from botocore.client import Config
|
|
|
|
| 152 |
else:
|
| 153 |
logger.warning("R2 credentials not found. File storage will use local temp directory.")
|
| 154 |
|
| 155 |
+
# --- reCAPTCHA Verification ---
|
| 156 |
+
RECAPTCHA_SECRET_KEY = os.environ.get('RECAPTCHA_SECRET_KEY')
|
| 157 |
+
|
| 158 |
+
def verify_recaptcha(token: str, action: str = 'upload') -> bool:
|
| 159 |
+
"""Verify Google reCAPTCHA v3 token"""
|
| 160 |
+
if not RECAPTCHA_SECRET_KEY:
|
| 161 |
+
logger.warning("RECAPTCHA_SECRET_KEY not found. Skipping verification.")
|
| 162 |
+
return True
|
| 163 |
+
|
| 164 |
+
try:
|
| 165 |
+
response = requests.post(
|
| 166 |
+
'https://www.google.com/recaptcha/api/siteverify',
|
| 167 |
+
data={
|
| 168 |
+
'secret': RECAPTCHA_SECRET_KEY,
|
| 169 |
+
'response': token
|
| 170 |
+
},
|
| 171 |
+
timeout=10
|
| 172 |
+
)
|
| 173 |
+
result = response.json()
|
| 174 |
+
|
| 175 |
+
if result.get('success') and result.get('action') == action:
|
| 176 |
+
score = result.get('score', 0)
|
| 177 |
+
if score >= 0.5:
|
| 178 |
+
logger.info(f"reCAPTCHA verified for action '{action}' with score {score}")
|
| 179 |
+
return True
|
| 180 |
+
else:
|
| 181 |
+
logger.warning(f"reCAPTCHA score too low: {score} for action '{action}'")
|
| 182 |
+
return False
|
| 183 |
+
|
| 184 |
+
logger.warning(f"reCAPTCHA verification failed: {result}")
|
| 185 |
+
return False
|
| 186 |
+
except Exception as e:
|
| 187 |
+
logger.error(f"reCAPTCHA verification error: {e}")
|
| 188 |
+
return False
|
| 189 |
+
|
| 190 |
# --- JWT Verification ---
|
| 191 |
def verify_firebase_token(authorization: str) -> str:
|
| 192 |
"""
|
|
|
|
| 370 |
async def process_upload(
|
| 371 |
file: UploadFile = File(...),
|
| 372 |
tos_agreed: bool = Form(...),
|
| 373 |
+
recaptcha_token: str = Form(None),
|
| 374 |
authorization: str = Header(None),
|
| 375 |
background_tasks: BackgroundTasks = None
|
| 376 |
):
|
| 377 |
if not tos_agreed:
|
| 378 |
+
raise HTTPException(status_code=400, detail="You must agree to the Terms of Service.")
|
| 379 |
+
|
| 380 |
+
# Verify reCAPTCHA
|
| 381 |
+
if recaptcha_token:
|
| 382 |
+
if not verify_recaptcha(recaptcha_token, 'upload'):
|
| 383 |
+
raise HTTPException(status_code=403, detail="Bot detection failed. Please try again.")
|
| 384 |
|
| 385 |
# Verify Firebase token and get UID
|
| 386 |
uid = verify_firebase_token(authorization) if authorization else None
|
|
|
|
| 407 |
if R2_ENABLED and uid:
|
| 408 |
logger.info(f"Uploading stems to R2 for user {uid}, song {song_id}")
|
| 409 |
|
| 410 |
+
# Upload each stem to R2 with metadata
|
| 411 |
uploaded_files = []
|
| 412 |
for root, dirs, files in os.walk(extracted_dir):
|
| 413 |
for filename in files:
|
|
|
|
| 415 |
file_path = os.path.join(root, filename)
|
| 416 |
s3_key = f"uploads/{uid}/{song_id}/{filename}"
|
| 417 |
|
| 418 |
+
# Store original filename as metadata on first file
|
| 419 |
+
metadata = {}
|
| 420 |
+
if not uploaded_files: # First file
|
| 421 |
+
metadata['original-filename'] = file.filename
|
| 422 |
+
|
| 423 |
with open(file_path, 'rb') as f:
|
| 424 |
s3_client.upload_fileobj(
|
| 425 |
f,
|
| 426 |
R2_BUCKET_NAME,
|
| 427 |
s3_key,
|
| 428 |
+
ExtraArgs={
|
| 429 |
+
'ContentType': 'audio/mpeg',
|
| 430 |
+
'Metadata': metadata
|
| 431 |
+
}
|
| 432 |
)
|
| 433 |
uploaded_files.append(filename)
|
| 434 |
logger.info(f"Uploaded {filename} to R2")
|
|
|
|
| 441 |
"song_id": song_id,
|
| 442 |
"uid": uid,
|
| 443 |
"files": uploaded_files,
|
| 444 |
+
"title": file.filename,
|
| 445 |
"message": "Upload successful. Files stored in R2."
|
| 446 |
}
|
| 447 |
|
|
|
|
| 628 |
raise HTTPException(status_code=500, detail="Failed to list stems")
|
| 629 |
|
| 630 |
|
| 631 |
+
@app.get("/my-songs")
|
| 632 |
+
async def list_my_songs(
|
| 633 |
+
authorization: str = Header(...)
|
| 634 |
+
):
|
| 635 |
+
"""
|
| 636 |
+
List all songs for the authenticated user.
|
| 637 |
+
Returns song_id and metadata for each song.
|
| 638 |
+
"""
|
| 639 |
+
if not R2_ENABLED:
|
| 640 |
+
raise HTTPException(status_code=503, detail="R2 storage not configured")
|
| 641 |
+
|
| 642 |
+
# Verify token and get UID
|
| 643 |
+
uid = verify_firebase_token(authorization)
|
| 644 |
+
|
| 645 |
+
# List all objects for this user
|
| 646 |
+
prefix = f"uploads/{uid}/"
|
| 647 |
+
|
| 648 |
+
try:
|
| 649 |
+
response = s3_client.list_objects_v2(
|
| 650 |
+
Bucket=R2_BUCKET_NAME,
|
| 651 |
+
Prefix=prefix,
|
| 652 |
+
Delimiter='/'
|
| 653 |
+
)
|
| 654 |
+
|
| 655 |
+
songs = []
|
| 656 |
+
|
| 657 |
+
# Get unique song_ids from CommonPrefixes (directories)
|
| 658 |
+
if 'CommonPrefixes' in response:
|
| 659 |
+
for prefix_obj in response['CommonPrefixes']:
|
| 660 |
+
# Extract song_id from prefix: uploads/{uid}/{song_id}/
|
| 661 |
+
parts = prefix_obj['Prefix'].rstrip('/').split('/')
|
| 662 |
+
if len(parts) >= 3:
|
| 663 |
+
song_id = parts[2]
|
| 664 |
+
|
| 665 |
+
# List files in this song directory
|
| 666 |
+
song_prefix = f"uploads/{uid}/{song_id}/"
|
| 667 |
+
song_response = s3_client.list_objects_v2(
|
| 668 |
+
Bucket=R2_BUCKET_NAME,
|
| 669 |
+
Prefix=song_prefix
|
| 670 |
+
)
|
| 671 |
+
|
| 672 |
+
files = []
|
| 673 |
+
original_title = None
|
| 674 |
+
|
| 675 |
+
if 'Contents' in song_response:
|
| 676 |
+
for idx, obj in enumerate(song_response['Contents']):
|
| 677 |
+
filename = obj['Key'].split('/')[-1]
|
| 678 |
+
if filename:
|
| 679 |
+
files.append({
|
| 680 |
+
"filename": filename,
|
| 681 |
+
"size": obj['Size'],
|
| 682 |
+
"last_modified": obj['LastModified'].isoformat()
|
| 683 |
+
})
|
| 684 |
+
|
| 685 |
+
# Get metadata from first file to retrieve original filename
|
| 686 |
+
if idx == 0 and not original_title:
|
| 687 |
+
try:
|
| 688 |
+
head_response = s3_client.head_object(
|
| 689 |
+
Bucket=R2_BUCKET_NAME,
|
| 690 |
+
Key=obj['Key']
|
| 691 |
+
)
|
| 692 |
+
metadata = head_response.get('Metadata', {})
|
| 693 |
+
original_title = metadata.get('original-filename')
|
| 694 |
+
except Exception as e:
|
| 695 |
+
logger.warning(f"Failed to get metadata for {obj['Key']}: {e}")
|
| 696 |
+
|
| 697 |
+
if files: # Only include songs that have files
|
| 698 |
+
songs.append({
|
| 699 |
+
"song_id": song_id,
|
| 700 |
+
"title": original_title or f"Song {song_id[:8]}",
|
| 701 |
+
"files": files,
|
| 702 |
+
"file_count": len(files),
|
| 703 |
+
"created_at": files[0]['last_modified'] if files else None
|
| 704 |
+
})
|
| 705 |
+
|
| 706 |
+
return {
|
| 707 |
+
"uid": uid,
|
| 708 |
+
"songs": songs,
|
| 709 |
+
"count": len(songs)
|
| 710 |
+
}
|
| 711 |
+
except Exception as e:
|
| 712 |
+
logger.error(f"Failed to list user songs: {e}")
|
| 713 |
+
raise HTTPException(status_code=500, detail="Failed to list songs")
|
| 714 |
+
|
| 715 |
+
|
| 716 |
if __name__ == "__main__":
|
| 717 |
import uvicorn
|
| 718 |
# Default to 7860 for Hugging Face Spaces
|
requirements.txt
CHANGED
|
@@ -10,4 +10,5 @@ torch
|
|
| 10 |
torchaudio
|
| 11 |
torchcodec
|
| 12 |
demucs
|
| 13 |
-
boto3>=1.34.0
|
|
|
|
|
|
| 10 |
torchaudio
|
| 11 |
torchcodec
|
| 12 |
demucs
|
| 13 |
+
boto3>=1.34.0
|
| 14 |
+
requests
|