Spaces:
Runtime error
Runtime error
nifty-coder commited on
Commit ·
888e323
1
Parent(s): 7672051
Fixed errors
Browse files- __pycache__/main.cpython-314.pyc +0 -0
- main.py +172 -117
__pycache__/main.cpython-314.pyc
CHANGED
|
Binary files a/__pycache__/main.cpython-314.pyc and b/__pycache__/main.cpython-314.pyc differ
|
|
|
main.py
CHANGED
|
@@ -386,6 +386,18 @@ def get_current_user(authorization: str | None = Header(None)):
|
|
| 386 |
"""
|
| 387 |
return get_authenticated_user(authorization)
|
| 388 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 389 |
@app.get("/api/profile", response_model=ProfileOut)
|
| 390 |
def get_profile(user=Depends(get_current_user)):
|
| 391 |
profiles = load_profiles()
|
|
@@ -660,7 +672,10 @@ async def process_upload(
|
|
| 660 |
|
| 661 |
# If R2 is enabled and user is authenticated, upload to R2
|
| 662 |
if R2_ENABLED and uid:
|
| 663 |
-
|
|
|
|
|
|
|
|
|
|
| 664 |
|
| 665 |
# Upload each stem to R2 with metadata
|
| 666 |
uploaded_files = []
|
|
@@ -668,7 +683,8 @@ async def process_upload(
|
|
| 668 |
for filename in files:
|
| 669 |
if filename.endswith('.mp3'):
|
| 670 |
file_path = os.path.join(root, filename)
|
| 671 |
-
|
|
|
|
| 672 |
|
| 673 |
# Store original filename as metadata on all files for robustness
|
| 674 |
metadata = {'original-filename': file.filename}
|
|
@@ -812,11 +828,26 @@ async def get_presigned_url(
|
|
| 812 |
if not R2_ENABLED:
|
| 813 |
raise HTTPException(status_code=503, detail="R2 storage not configured")
|
| 814 |
|
| 815 |
-
# Verify token and get
|
| 816 |
-
|
|
|
|
| 817 |
|
| 818 |
-
#
|
| 819 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 820 |
|
| 821 |
try:
|
| 822 |
# Generate presigned URL (1 hour expiry)
|
|
@@ -824,7 +855,7 @@ async def get_presigned_url(
|
|
| 824 |
'get_object',
|
| 825 |
Params={
|
| 826 |
'Bucket': R2_BUCKET_NAME,
|
| 827 |
-
'Key':
|
| 828 |
},
|
| 829 |
ExpiresIn=3600 # 1 hour
|
| 830 |
)
|
|
@@ -851,29 +882,40 @@ async def list_stems(
|
|
| 851 |
if not R2_ENABLED:
|
| 852 |
raise HTTPException(status_code=503, detail="R2 storage not configured")
|
| 853 |
|
| 854 |
-
# Verify token and get
|
| 855 |
-
|
| 856 |
|
| 857 |
-
# List objects in R2 with
|
| 858 |
-
|
|
|
|
|
|
|
|
|
|
| 859 |
|
| 860 |
try:
|
| 861 |
-
|
| 862 |
-
|
| 863 |
-
|
| 864 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 865 |
|
| 866 |
-
|
| 867 |
-
|
| 868 |
-
for obj in response['Contents']:
|
| 869 |
-
# Extract filename from key
|
| 870 |
-
filename = obj['Key'].split('/')[-1]
|
| 871 |
-
if filename: # Skip directory markers
|
| 872 |
-
files.append({
|
| 873 |
-
"filename": filename,
|
| 874 |
-
"size": obj['Size'],
|
| 875 |
-
"last_modified": obj['LastModified'].isoformat()
|
| 876 |
-
})
|
| 877 |
|
| 878 |
return {
|
| 879 |
"song_id": song_id,
|
|
@@ -897,71 +939,78 @@ async def list_my_songs(
|
|
| 897 |
raise HTTPException(status_code=503, detail="R2 storage not configured")
|
| 898 |
|
| 899 |
# Verify token and get UID
|
| 900 |
-
|
|
|
|
| 901 |
|
| 902 |
-
# List
|
| 903 |
-
|
|
|
|
|
|
|
| 904 |
|
| 905 |
try:
|
| 906 |
-
|
| 907 |
-
|
| 908 |
-
|
| 909 |
-
|
| 910 |
-
|
| 911 |
-
|
| 912 |
-
|
| 913 |
-
|
| 914 |
-
|
| 915 |
-
|
| 916 |
-
|
| 917 |
-
|
| 918 |
-
|
| 919 |
-
|
| 920 |
-
|
| 921 |
-
|
| 922 |
-
|
| 923 |
-
|
| 924 |
-
|
| 925 |
-
|
| 926 |
-
|
| 927 |
-
|
| 928 |
-
|
| 929 |
-
|
| 930 |
-
|
| 931 |
-
|
| 932 |
-
|
| 933 |
-
|
| 934 |
-
|
| 935 |
-
|
| 936 |
-
|
| 937 |
-
|
| 938 |
-
|
| 939 |
-
|
| 940 |
-
|
| 941 |
-
|
| 942 |
-
|
| 943 |
-
|
| 944 |
-
|
| 945 |
-
|
| 946 |
-
|
| 947 |
-
|
| 948 |
-
|
| 949 |
-
|
| 950 |
-
|
| 951 |
-
|
| 952 |
-
|
| 953 |
-
|
| 954 |
-
logger.warning(f"Failed to get metadata for {obj['Key']}: {e}")
|
| 955 |
|
| 956 |
if files: # Only include songs that have files
|
|
|
|
|
|
|
| 957 |
songs.append({
|
| 958 |
"song_id": song_id,
|
| 959 |
"title": original_title or f"Song {song_id[:8]}",
|
| 960 |
"files": files,
|
| 961 |
"file_count": len(files),
|
| 962 |
-
"created_at":
|
| 963 |
})
|
| 964 |
|
|
|
|
|
|
|
|
|
|
| 965 |
return {
|
| 966 |
"uid": uid,
|
| 967 |
"songs": songs,
|
|
@@ -984,26 +1033,30 @@ async def delete_song(
|
|
| 984 |
if not R2_ENABLED:
|
| 985 |
raise HTTPException(status_code=503, detail="R2 storage not configured")
|
| 986 |
|
| 987 |
-
# Verify token and get
|
| 988 |
-
|
| 989 |
|
| 990 |
-
# Construct
|
| 991 |
-
|
| 992 |
|
| 993 |
try:
|
| 994 |
-
|
| 995 |
-
|
| 996 |
-
|
| 997 |
-
|
| 998 |
-
|
| 999 |
-
|
| 1000 |
-
if 'Contents' in response:
|
| 1001 |
-
delete_objects = {'Objects': [{'Key': obj['Key']} for obj in response['Contents']]}
|
| 1002 |
-
s3_client.delete_objects(
|
| 1003 |
Bucket=R2_BUCKET_NAME,
|
| 1004 |
-
|
| 1005 |
)
|
| 1006 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1007 |
|
| 1008 |
return {"message": f"Song {song_id} deleted successfully"}
|
| 1009 |
except Exception as e:
|
|
@@ -1021,35 +1074,37 @@ async def delete_all_songs(
|
|
| 1021 |
if not R2_ENABLED:
|
| 1022 |
raise HTTPException(status_code=503, detail="R2 storage not configured")
|
| 1023 |
|
| 1024 |
-
# Verify token and get
|
| 1025 |
-
|
|
|
|
| 1026 |
|
| 1027 |
-
# Construct
|
| 1028 |
-
|
| 1029 |
|
| 1030 |
try:
|
| 1031 |
-
# Paginating delete if there are many objects
|
| 1032 |
deleted_count = 0
|
| 1033 |
-
|
| 1034 |
-
|
| 1035 |
-
|
| 1036 |
-
|
| 1037 |
-
|
| 1038 |
-
|
| 1039 |
-
|
| 1040 |
-
break
|
| 1041 |
|
| 1042 |
-
|
| 1043 |
-
|
| 1044 |
-
|
| 1045 |
-
|
| 1046 |
-
|
| 1047 |
-
|
| 1048 |
-
|
| 1049 |
-
|
| 1050 |
-
|
| 1051 |
-
break
|
| 1052 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1053 |
logger.info(f"Deleted all {deleted_count} objects for user {uid}")
|
| 1054 |
return {"message": f"All {deleted_count} objects deleted successfully"}
|
| 1055 |
except Exception as e:
|
|
|
|
| 386 |
"""
|
| 387 |
return get_authenticated_user(authorization)
|
| 388 |
|
| 389 |
+
def get_user_storage_prefixes(user: dict) -> list[str]:
|
| 390 |
+
"""
|
| 391 |
+
Returns the storage prefix for R2 for a given user.
|
| 392 |
+
Uses the Python str(dict) representation as requested: {'user_id': 'uid', 'email': 'email'}
|
| 393 |
+
"""
|
| 394 |
+
uid = user['user_id']
|
| 395 |
+
email = user['email']
|
| 396 |
+
|
| 397 |
+
# User requested to ONLY use this specific format
|
| 398 |
+
prefix_dict = {"user_id": uid, "email": email}
|
| 399 |
+
return [f"uploads/{str(prefix_dict)}/"]
|
| 400 |
+
|
| 401 |
@app.get("/api/profile", response_model=ProfileOut)
|
| 402 |
def get_profile(user=Depends(get_current_user)):
|
| 403 |
profiles = load_profiles()
|
|
|
|
| 672 |
|
| 673 |
# If R2 is enabled and user is authenticated, upload to R2
|
| 674 |
if R2_ENABLED and uid:
|
| 675 |
+
user = get_authenticated_user(authorization)
|
| 676 |
+
user_prefix = get_user_storage_prefixes(user)[0] # Get the only prefix we now support
|
| 677 |
+
|
| 678 |
+
logger.info(f"Uploading stems to R2 for user {uid}, song {song_id} to prefix {user_prefix}")
|
| 679 |
|
| 680 |
# Upload each stem to R2 with metadata
|
| 681 |
uploaded_files = []
|
|
|
|
| 683 |
for filename in files:
|
| 684 |
if filename.endswith('.mp3'):
|
| 685 |
file_path = os.path.join(root, filename)
|
| 686 |
+
# Construct key using the prefix: uploads/{dict_str}/{song_id}/{filename}
|
| 687 |
+
s3_key = f"{user_prefix}{song_id}/{filename}"
|
| 688 |
|
| 689 |
# Store original filename as metadata on all files for robustness
|
| 690 |
metadata = {'original-filename': file.filename}
|
|
|
|
| 828 |
if not R2_ENABLED:
|
| 829 |
raise HTTPException(status_code=503, detail="R2 storage not configured")
|
| 830 |
|
| 831 |
+
# Verify token and get user
|
| 832 |
+
user = get_authenticated_user(authorization)
|
| 833 |
+
uid = user['user_id']
|
| 834 |
|
| 835 |
+
# candidate prefixes
|
| 836 |
+
prefixes = get_user_storage_prefixes(user)
|
| 837 |
+
|
| 838 |
+
found_key = None
|
| 839 |
+
for prefix in prefixes:
|
| 840 |
+
s3_key = f"{prefix}{request.song_id}/{request.filename}"
|
| 841 |
+
try:
|
| 842 |
+
# Check if file exists
|
| 843 |
+
s3_client.head_object(Bucket=R2_BUCKET_NAME, Key=s3_key)
|
| 844 |
+
found_key = s3_key
|
| 845 |
+
break
|
| 846 |
+
except:
|
| 847 |
+
continue
|
| 848 |
+
|
| 849 |
+
if not found_key:
|
| 850 |
+
raise HTTPException(status_code=404, detail="File not found")
|
| 851 |
|
| 852 |
try:
|
| 853 |
# Generate presigned URL (1 hour expiry)
|
|
|
|
| 855 |
'get_object',
|
| 856 |
Params={
|
| 857 |
'Bucket': R2_BUCKET_NAME,
|
| 858 |
+
'Key': found_key
|
| 859 |
},
|
| 860 |
ExpiresIn=3600 # 1 hour
|
| 861 |
)
|
|
|
|
| 882 |
if not R2_ENABLED:
|
| 883 |
raise HTTPException(status_code=503, detail="R2 storage not configured")
|
| 884 |
|
| 885 |
+
# Verify token and get user
|
| 886 |
+
user = get_authenticated_user(authorization)
|
| 887 |
|
| 888 |
+
# List objects in R2 with both potential prefixes
|
| 889 |
+
prefixes = get_user_storage_prefixes(user)
|
| 890 |
+
|
| 891 |
+
files = []
|
| 892 |
+
found_song = False
|
| 893 |
|
| 894 |
try:
|
| 895 |
+
for user_prefix in prefixes:
|
| 896 |
+
prefix = f"{user_prefix}{song_id}/"
|
| 897 |
+
response = s3_client.list_objects_v2(
|
| 898 |
+
Bucket=R2_BUCKET_NAME,
|
| 899 |
+
Prefix=prefix
|
| 900 |
+
)
|
| 901 |
+
|
| 902 |
+
if 'Contents' in response:
|
| 903 |
+
found_song = True
|
| 904 |
+
for obj in response['Contents']:
|
| 905 |
+
# Extract filename from key
|
| 906 |
+
filename = obj['Key'].split('/')[-1]
|
| 907 |
+
if filename: # Skip directory markers
|
| 908 |
+
files.append({
|
| 909 |
+
"filename": filename,
|
| 910 |
+
"size": obj['Size'],
|
| 911 |
+
"last_modified": obj['LastModified'].isoformat()
|
| 912 |
+
})
|
| 913 |
+
# If we found files in any prefix, we stop (avoiding duplicates if it exists in both, which shouldn't happen)
|
| 914 |
+
if files:
|
| 915 |
+
break
|
| 916 |
|
| 917 |
+
if not found_song and not files:
|
| 918 |
+
raise HTTPException(status_code=404, detail="Song not found")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 919 |
|
| 920 |
return {
|
| 921 |
"song_id": song_id,
|
|
|
|
| 939 |
raise HTTPException(status_code=503, detail="R2 storage not configured")
|
| 940 |
|
| 941 |
# Verify token and get UID
|
| 942 |
+
user = get_authenticated_user(authorization)
|
| 943 |
+
uid = user['user_id']
|
| 944 |
|
| 945 |
+
# List candidate user prefixes
|
| 946 |
+
user_prefixes = get_user_storage_prefixes(user)
|
| 947 |
+
|
| 948 |
+
songs = []
|
| 949 |
|
| 950 |
try:
|
| 951 |
+
for user_prefix in user_prefixes:
|
| 952 |
+
response = s3_client.list_objects_v2(
|
| 953 |
+
Bucket=R2_BUCKET_NAME,
|
| 954 |
+
Prefix=user_prefix,
|
| 955 |
+
Delimiter='/'
|
| 956 |
+
)
|
| 957 |
+
|
| 958 |
+
# Get unique song_ids from CommonPrefixes (directories)
|
| 959 |
+
if 'CommonPrefixes' in response:
|
| 960 |
+
for prefix_obj in response['CommonPrefixes']:
|
| 961 |
+
current_song_dir_prefix = prefix_obj['Prefix']
|
| 962 |
+
# Extract song_id from prefix: uploads/.../{song_id}/
|
| 963 |
+
parts = current_song_dir_prefix.rstrip('/').split('/')
|
| 964 |
+
if len(parts) >= 3:
|
| 965 |
+
song_id = parts[-1] # The last part is the song_id
|
| 966 |
+
|
| 967 |
+
# List files in this specific song directory
|
| 968 |
+
song_response = s3_client.list_objects_v2(
|
| 969 |
+
Bucket=R2_BUCKET_NAME,
|
| 970 |
+
Prefix=current_song_dir_prefix
|
| 971 |
+
)
|
| 972 |
+
|
| 973 |
+
files = []
|
| 974 |
+
original_title = None
|
| 975 |
+
|
| 976 |
+
if 'Contents' in song_response:
|
| 977 |
+
for idx, obj in enumerate(song_response['Contents']):
|
| 978 |
+
filename = obj['Key'].split('/')[-1]
|
| 979 |
+
if filename:
|
| 980 |
+
files.append({
|
| 981 |
+
"filename": filename,
|
| 982 |
+
"size": obj['Size'],
|
| 983 |
+
"last_modified": obj['LastModified'].isoformat()
|
| 984 |
+
})
|
| 985 |
+
|
| 986 |
+
# Get metadata from file to retrieve original filename
|
| 987 |
+
if not original_title:
|
| 988 |
+
try:
|
| 989 |
+
head_response = s3_client.head_object(
|
| 990 |
+
Bucket=R2_BUCKET_NAME,
|
| 991 |
+
Key=obj['Key']
|
| 992 |
+
)
|
| 993 |
+
# Use case-insensitive check for metadata keys
|
| 994 |
+
metadata = head_response.get('Metadata', {})
|
| 995 |
+
# Boto3/S3 often normalizes keys to lowercase
|
| 996 |
+
original_title = metadata.get('original-filename') or metadata.get('original-filename'.lower())
|
| 997 |
+
except Exception as e:
|
| 998 |
+
logger.warning(f"Failed to get metadata for {obj['Key']}: {e}")
|
|
|
|
| 999 |
|
| 1000 |
if files: # Only include songs that have files
|
| 1001 |
+
# Use the latest modification time among all files in the song
|
| 1002 |
+
latest_time = max(f['last_modified'] for f in files)
|
| 1003 |
songs.append({
|
| 1004 |
"song_id": song_id,
|
| 1005 |
"title": original_title or f"Song {song_id[:8]}",
|
| 1006 |
"files": files,
|
| 1007 |
"file_count": len(files),
|
| 1008 |
+
"created_at": latest_time
|
| 1009 |
})
|
| 1010 |
|
| 1011 |
+
# Sort songs by created_at descending (recency)
|
| 1012 |
+
songs.sort(key=lambda x: x.get('created_at') or '', reverse=True)
|
| 1013 |
+
|
| 1014 |
return {
|
| 1015 |
"uid": uid,
|
| 1016 |
"songs": songs,
|
|
|
|
| 1033 |
if not R2_ENABLED:
|
| 1034 |
raise HTTPException(status_code=503, detail="R2 storage not configured")
|
| 1035 |
|
| 1036 |
+
# Verify token and get user
|
| 1037 |
+
user = get_authenticated_user(authorization)
|
| 1038 |
|
| 1039 |
+
# Construct candidate prefixes
|
| 1040 |
+
user_prefixes = get_user_storage_prefixes(user)
|
| 1041 |
|
| 1042 |
try:
|
| 1043 |
+
deleted_any = False
|
| 1044 |
+
for user_prefix in user_prefixes:
|
| 1045 |
+
prefix = f"{user_prefix}{song_id}/"
|
| 1046 |
+
# Find all objects to delete
|
| 1047 |
+
response = s3_client.list_objects_v2(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1048 |
Bucket=R2_BUCKET_NAME,
|
| 1049 |
+
Prefix=prefix
|
| 1050 |
)
|
| 1051 |
+
|
| 1052 |
+
if 'Contents' in response:
|
| 1053 |
+
delete_objects = {'Objects': [{'Key': obj['Key']} for obj in response['Contents']]}
|
| 1054 |
+
s3_client.delete_objects(
|
| 1055 |
+
Bucket=R2_BUCKET_NAME,
|
| 1056 |
+
Delete=delete_objects
|
| 1057 |
+
)
|
| 1058 |
+
logger.info(f"Deleted {len(delete_objects['Objects'])} objects for song {song_id} in prefix {prefix}")
|
| 1059 |
+
deleted_any = True
|
| 1060 |
|
| 1061 |
return {"message": f"Song {song_id} deleted successfully"}
|
| 1062 |
except Exception as e:
|
|
|
|
| 1074 |
if not R2_ENABLED:
|
| 1075 |
raise HTTPException(status_code=503, detail="R2 storage not configured")
|
| 1076 |
|
| 1077 |
+
# Verify token and get user
|
| 1078 |
+
user = get_authenticated_user(authorization)
|
| 1079 |
+
uid = user['user_id']
|
| 1080 |
|
| 1081 |
+
# Construct candidate prefixes
|
| 1082 |
+
user_prefixes = get_user_storage_prefixes(user)
|
| 1083 |
|
| 1084 |
try:
|
|
|
|
| 1085 |
deleted_count = 0
|
| 1086 |
+
for prefix in user_prefixes:
|
| 1087 |
+
# Paginating delete if there are many objects
|
| 1088 |
+
while True:
|
| 1089 |
+
response = s3_client.list_objects_v2(
|
| 1090 |
+
Bucket=R2_BUCKET_NAME,
|
| 1091 |
+
Prefix=prefix
|
| 1092 |
+
)
|
|
|
|
| 1093 |
|
| 1094 |
+
if 'Contents' not in response:
|
| 1095 |
+
break
|
| 1096 |
+
|
| 1097 |
+
delete_objects = {'Objects': [{'Key': obj['Key']} for obj in response['Contents']]}
|
| 1098 |
+
s3_client.delete_objects(
|
| 1099 |
+
Bucket=R2_BUCKET_NAME,
|
| 1100 |
+
Delete=delete_objects
|
| 1101 |
+
)
|
| 1102 |
+
deleted_count += len(delete_objects['Objects'])
|
|
|
|
| 1103 |
|
| 1104 |
+
# If there are more objects, they will be picked up in next iteration
|
| 1105 |
+
if not response.get('IsTruncated'):
|
| 1106 |
+
break
|
| 1107 |
+
|
| 1108 |
logger.info(f"Deleted all {deleted_count} objects for user {uid}")
|
| 1109 |
return {"message": f"All {deleted_count} objects deleted successfully"}
|
| 1110 |
except Exception as e:
|