Spaces:
Runtime error
Runtime error
nifty-coder commited on
Commit ·
9db4736
0
Parent(s):
working
Browse files- .DS_Store +0 -0
- .gitignore +2 -0
- README.md +211 -0
- __pycache__/main.cpython-312.pyc +0 -0
- __pycache__/main.cpython-313.pyc +0 -0
- __pycache__/main.cpython-314.pyc +0 -0
- build.sh +14 -0
- install.sh +17 -0
- main.py +474 -0
- requirements-base.txt +11 -0
- requirements-demucs.txt +10 -0
- requirements.txt +16 -0
.DS_Store
ADDED
|
Binary file (6.15 kB). View file
|
|
|
.gitignore
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
aimusicapp-a2b65-firebase-adminsdk-fbsvc-f9be37b6c3.json
|
| 2 |
+
.env
|
README.md
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# AI Music App Backend
|
| 2 |
+
|
| 3 |
+
A FastAPI backend for processing audio files and YouTube videos to separate them into individual stems (drums, bass, vocals, etc.) using the Demucs AI model.
|
| 4 |
+
|
| 5 |
+
## Features
|
| 6 |
+
|
| 7 |
+
- **YouTube Audio Processing**: Download and separate audio from YouTube videos
|
| 8 |
+
- **File Upload Processing**: Upload and separate audio files
|
| 9 |
+
- **Stem Separation**: Separate audio into drums, bass, vocals, and other instruments
|
| 10 |
+
- **ZIP Download**: Download separated stems as a ZIP file
|
| 11 |
+
- **Secure Profile Management**: User profile management with Firebase authentication and Supabase storage
|
| 12 |
+
|
| 13 |
+
## API Endpoints
|
| 14 |
+
|
| 15 |
+
### Audio Processing
|
| 16 |
+
- `GET /` - Health check endpoint
|
| 17 |
+
- `POST /youtube` - Process YouTube video audio
|
| 18 |
+
- `POST /upload` - Process uploaded audio file
|
| 19 |
+
|
| 20 |
+
### Profile Management (Requires Firebase Authentication)
|
| 21 |
+
- `GET /api/profile` - Get user profile
|
| 22 |
+
- `POST /api/profile` - Create new user profile
|
| 23 |
+
- `PUT /api/profile` - Update user profile
|
| 24 |
+
- `DELETE /api/profile` - Delete user profile
|
| 25 |
+
|
| 26 |
+
## Running the Server
|
| 27 |
+
|
| 28 |
+
```bash
|
| 29 |
+
python -m uvicorn main:app --reload --host 0.0.0.0 --port 8000
|
| 30 |
+
```
|
| 31 |
+
|
| 32 |
+
## Usage
|
| 33 |
+
|
| 34 |
+
### Process YouTube Video
|
| 35 |
+
```bash
|
| 36 |
+
curl -X POST "http://localhost:8000/youtube" \
|
| 37 |
+
-H "Content-Type: application/json" \
|
| 38 |
+
-d '{"youtube_url": "https://www.youtube.com/watch?v=VIDEO_ID"}'
|
| 39 |
+
```
|
| 40 |
+
|
| 41 |
+
### Upload Audio File
|
| 42 |
+
```bash
|
| 43 |
+
curl -X POST "http://localhost:8000/upload" \
|
| 44 |
+
-F "file=@audio_file.mp3"
|
| 45 |
+
```
|
| 46 |
+
|
| 47 |
+
## Profile Management API Usage
|
| 48 |
+
|
| 49 |
+
All profile endpoints require Firebase authentication. Include the Firebase ID token in the Authorization header:
|
| 50 |
+
|
| 51 |
+
### Get User Profile
|
| 52 |
+
```bash
|
| 53 |
+
curl -X GET "http://localhost:8000/api/profile" \
|
| 54 |
+
-H "Authorization: Bearer YOUR_FIREBASE_ID_TOKEN"
|
| 55 |
+
```
|
| 56 |
+
|
| 57 |
+
### Create User Profile
|
| 58 |
+
```bash
|
| 59 |
+
curl -X POST "http://localhost:8000/api/profile" \
|
| 60 |
+
-H "Authorization: Bearer YOUR_FIREBASE_ID_TOKEN" \
|
| 61 |
+
-H "Content-Type: application/json" \
|
| 62 |
+
-d '{
|
| 63 |
+
"display_name": "John Doe",
|
| 64 |
+
"profile_picture": "https://example.com/avatar.jpg"
|
| 65 |
+
}'
|
| 66 |
+
```
|
| 67 |
+
|
| 68 |
+
### Update User Profile
|
| 69 |
+
```bash
|
| 70 |
+
curl -X PUT "http://localhost:8000/api/profile" \
|
| 71 |
+
-H "Authorization: Bearer YOUR_FIREBASE_ID_TOKEN" \
|
| 72 |
+
-H "Content-Type: application/json" \
|
| 73 |
+
-d '{
|
| 74 |
+
"display_name": "John Smith"
|
| 75 |
+
}'
|
| 76 |
+
```
|
| 77 |
+
|
| 78 |
+
### Delete User Profile
|
| 79 |
+
```bash
|
| 80 |
+
curl -X DELETE "http://localhost:8000/api/profile" \
|
| 81 |
+
-H "Authorization: Bearer YOUR_FIREBASE_ID_TOKEN"
|
| 82 |
+
```
|
| 83 |
+
|
| 84 |
+
## Troubleshooting
|
| 85 |
+
|
| 86 |
+
### Torchaudio Backend Error
|
| 87 |
+
If you encounter the error:
|
| 88 |
+
```
|
| 89 |
+
RuntimeError: Couldn't find appropriate backend to handle uri ... and format None.
|
| 90 |
+
```
|
| 91 |
+
|
| 92 |
+
This was fixed by:
|
| 93 |
+
1. Adding `soundfile` to requirements.txt
|
| 94 |
+
2. Ensuring proper audio backend dependencies are installed
|
| 95 |
+
3. Adding better error handling and logging
|
| 96 |
+
|
| 97 |
+
### Dependencies
|
| 98 |
+
- `fastapi` - Web framework
|
| 99 |
+
- `uvicorn` - ASGI server
|
| 100 |
+
- `pydantic` - Data validation
|
| 101 |
+
- `ffmpeg-python` - Audio processing
|
| 102 |
+
- `python-multipart` - File upload handling
|
| 103 |
+
- `demucs` - AI audio separation
|
| 104 |
+
- `torchaudio` - Audio processing backend
|
| 105 |
+
- `soundfile` - Audio file I/O
|
| 106 |
+
- `yt-dlp` - YouTube downloader
|
| 107 |
+
- `firebase-admin` - Firebase authentication
|
| 108 |
+
- `supabase` - Supabase database client
|
| 109 |
+
- `slowapi` - Rate limiting
|
| 110 |
+
- `python-jose[cryptography]` - JWT token handling
|
| 111 |
+
- `python-dotenv` - Environment variable management
|
| 112 |
+
|
| 113 |
+
## Error Handling
|
| 114 |
+
|
| 115 |
+
The application now includes comprehensive error handling:
|
| 116 |
+
- Subprocess error capture and logging
|
| 117 |
+
- File existence checks
|
| 118 |
+
- Detailed error messages
|
| 119 |
+
- Proper HTTP status codes
|
| 120 |
+
|
| 121 |
+
## Logging
|
| 122 |
+
|
| 123 |
+
The application uses structured logging to help debug issues:
|
| 124 |
+
- Download progress logging
|
| 125 |
+
- Processing step logging
|
| 126 |
+
- Error logging with stack traces
|
| 127 |
+
|
| 128 |
+
## Security Features
|
| 129 |
+
|
| 130 |
+
The profile management system includes comprehensive security measures:
|
| 131 |
+
|
| 132 |
+
### Authentication & Authorization
|
| 133 |
+
- **Firebase ID Token Validation**: All profile endpoints require valid Firebase ID tokens
|
| 134 |
+
- **User Isolation**: Users can only access and modify their own profiles
|
| 135 |
+
- **Token Audience Validation**: Ensures tokens are issued for the correct Firebase project
|
| 136 |
+
|
| 137 |
+
### Rate Limiting
|
| 138 |
+
- **GET /api/profile**: 30 requests per minute
|
| 139 |
+
- **POST /api/profile**: 10 requests per minute
|
| 140 |
+
- **PUT /api/profile**: 20 requests per minute
|
| 141 |
+
- **DELETE /api/profile**: 5 requests per minute
|
| 142 |
+
|
| 143 |
+
### Input Validation
|
| 144 |
+
- **Display Name**: Maximum 100 characters, cannot be empty
|
| 145 |
+
- **Profile Picture URL**: Maximum 500 characters
|
| 146 |
+
- **Email Validation**: Automatically populated from Firebase user data
|
| 147 |
+
- **Data Sanitization**: All input is validated and sanitized
|
| 148 |
+
|
| 149 |
+
### Error Handling
|
| 150 |
+
- **Secure Error Messages**: No sensitive information leaked in error responses
|
| 151 |
+
- **Comprehensive Logging**: All errors are logged for monitoring
|
| 152 |
+
- **Proper HTTP Status Codes**: Appropriate status codes for different error scenarios
|
| 153 |
+
|
| 154 |
+
### Database Security
|
| 155 |
+
- **Service Role Access**: Uses Supabase service role key for secure database operations
|
| 156 |
+
- **User ID Validation**: All database operations are scoped to the authenticated user
|
| 157 |
+
- **Data Integrity**: Proper validation and constraints on all profile data
|
| 158 |
+
|
| 159 |
+
## Firebase Admin (production) vs Dev Bypass (local testing)
|
| 160 |
+
|
| 161 |
+
The profile endpoints require `firebase-admin` to verify Firebase ID tokens. There are two recommended ways to run and test locally:
|
| 162 |
+
|
| 163 |
+
1) Production-like (recommended): configure `firebase-admin` with a service account
|
| 164 |
+
|
| 165 |
+
- Download a service account JSON from the Firebase Console (Project Settings -> Service accounts -> Generate new private key).
|
| 166 |
+
- In PowerShell, set the environment variable and start the server (current terminal session):
|
| 167 |
+
|
| 168 |
+
```powershell
|
| 169 |
+
$env:GOOGLE_APPLICATION_CREDENTIALS = 'C:\path\to\service-account.json'
|
| 170 |
+
uvicorn main:app --reload
|
| 171 |
+
```
|
| 172 |
+
|
| 173 |
+
- Or set it permanently (Windows) and restart your shell / service:
|
| 174 |
+
|
| 175 |
+
```powershell
|
| 176 |
+
setx GOOGLE_APPLICATION_CREDENTIALS "C:\path\to\service-account.json"
|
| 177 |
+
```
|
| 178 |
+
|
| 179 |
+
- Once `firebase-admin` can initialize, the backend will verify real Firebase ID tokens sent by the frontend.
|
| 180 |
+
|
| 181 |
+
2) Dev bypass (only for local development): enable `DEV_ALLOW_PROFILE_NO_AUTH`
|
| 182 |
+
|
| 183 |
+
- This bypass exists to let you iterate on frontend/profile UI quickly without configuring a service account. It MUST NOT be used in production.
|
| 184 |
+
|
| 185 |
+
- Enable the bypass and start the server (current terminal session):
|
| 186 |
+
|
| 187 |
+
```powershell
|
| 188 |
+
$env:DEV_ALLOW_PROFILE_NO_AUTH = '1'
|
| 189 |
+
uvicorn main:app --reload
|
| 190 |
+
```
|
| 191 |
+
|
| 192 |
+
- The backend will accept `Authorization` headers in the form `Bearer alice:alice@example.com` and use them as the dev user id/email. If the token does not contain a `:`, it will default to a dev user id/email.
|
| 193 |
+
|
| 194 |
+
- Example curl using the dev token:
|
| 195 |
+
|
| 196 |
+
```bash
|
| 197 |
+
curl -X GET "http://localhost:8000/api/profile" \
|
| 198 |
+
-H "Authorization: Bearer alice:alice@example.com"
|
| 199 |
+
```
|
| 200 |
+
|
| 201 |
+
- Frontend dev flow: you can set a Vite env variable in your frontend dev environment to use the dev token automatically:
|
| 202 |
+
|
| 203 |
+
- In `tune-layers-explorer-main/.env.local` (create if missing):
|
| 204 |
+
```env
|
| 205 |
+
VITE_API_BASE_URL=http://localhost:8000
|
| 206 |
+
VITE_DEV_PROFILE_TOKEN=alice:alice@example.com
|
| 207 |
+
```
|
| 208 |
+
|
| 209 |
+
- Restart the frontend dev server. The frontend hook will use `VITE_DEV_PROFILE_TOKEN` when no Firebase user is present.
|
| 210 |
+
|
| 211 |
+
Security note: The `DEV_ALLOW_PROFILE_NO_AUTH` bypass is intentionally gated and logs a warning when used. Do not set this in any non-local environment.
|
__pycache__/main.cpython-312.pyc
ADDED
|
Binary file (44.1 kB). View file
|
|
|
__pycache__/main.cpython-313.pyc
ADDED
|
Binary file (35.5 kB). View file
|
|
|
__pycache__/main.cpython-314.pyc
ADDED
|
Binary file (34.1 kB). View file
|
|
|
build.sh
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# Install dependencies
|
| 3 |
+
|
| 4 |
+
# 1. Update pip
|
| 5 |
+
pip install --upgrade pip
|
| 6 |
+
|
| 7 |
+
# 2. Install base requirements
|
| 8 |
+
pip install -r requirements.txt
|
| 9 |
+
|
| 10 |
+
# 3. Install demucs dependencies separately to manage version conflicts
|
| 11 |
+
echo "Installing demucs dependencies..."
|
| 12 |
+
pip install dora-search einops "julius>=0.2.3" openunmix tqdm pyyaml "lameenc>=1.2"
|
| 13 |
+
|
| 14 |
+
echo "Build complete (Pure Python)!"
|
install.sh
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# Local installation script
|
| 3 |
+
|
| 4 |
+
# 1. Update pip
|
| 5 |
+
pip install --upgrade pip
|
| 6 |
+
|
| 7 |
+
# 2. Install base requirements
|
| 8 |
+
pip install -r requirements-base.txt
|
| 9 |
+
|
| 10 |
+
# 3. Install demucs dependencies
|
| 11 |
+
echo "Installing demucs dependencies..."
|
| 12 |
+
pip install dora-search einops "julius>=0.2.3" openunmix tqdm pyyaml "lameenc>=1.2"
|
| 13 |
+
|
| 14 |
+
# 4. Install yt-dlp
|
| 15 |
+
pip install -U yt-dlp
|
| 16 |
+
|
| 17 |
+
echo "Installation complete (Pure Python)!"
|
main.py
ADDED
|
@@ -0,0 +1,474 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import tempfile
|
| 3 |
+
import shutil
|
| 4 |
+
import subprocess
|
| 5 |
+
import logging
|
| 6 |
+
import zipfile
|
| 7 |
+
import re
|
| 8 |
+
import json
|
| 9 |
+
import hashlib
|
| 10 |
+
import io
|
| 11 |
+
from fastapi import FastAPI, UploadFile, File, HTTPException, BackgroundTasks, Response, Request, Depends, Header
|
| 12 |
+
from datetime import datetime
|
| 13 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 14 |
+
from fastapi.responses import FileResponse
|
| 15 |
+
from pydantic import BaseModel
|
| 16 |
+
|
| 17 |
+
# Regex for basic YouTube URL validation
|
| 18 |
+
YT_PATTERN = r'(https?://)?(www\.)?(youtube\.com|youtu\.be)/.+'
|
| 19 |
+
|
| 20 |
+
# Logging setup
|
| 21 |
+
logging.basicConfig(level=logging.INFO)
|
| 22 |
+
logger = logging.getLogger(__name__)
|
| 23 |
+
|
| 24 |
+
# --- YouTube Cookie & PO Token Setup ---
|
| 25 |
+
|
| 26 |
+
# Read the cookie data from the environment variable (Netscape format preferred)
|
| 27 |
+
cookies_content = os.environ.get('YTDLP_COOKIES_CONTENT')
|
| 28 |
+
cookies_file_path = None
|
| 29 |
+
|
| 30 |
+
if cookies_content:
|
| 31 |
+
try:
|
| 32 |
+
# Create a temporary file for yt-dlp to read
|
| 33 |
+
with tempfile.NamedTemporaryFile(mode='w', delete=False, encoding='utf-8') as tmp_file:
|
| 34 |
+
tmp_file.write(cookies_content)
|
| 35 |
+
cookies_file_path = tmp_file.name
|
| 36 |
+
os.environ['YTDLP_COOKIES_FILE'] = cookies_file_path
|
| 37 |
+
logger.info(f"YTDLP_COOKIES_FILE set to temporary path: {cookies_file_path}")
|
| 38 |
+
except Exception as e:
|
| 39 |
+
logger.error(f"Failed to set up yt-dlp cookies: {e}")
|
| 40 |
+
else:
|
| 41 |
+
logger.warning("YTDLP_COOKIES_CONTENT not set. Downloads may fail on restricted videos.")
|
| 42 |
+
|
| 43 |
+
# PO Token support for advanced bot detection bypass
|
| 44 |
+
PO_TOKEN = os.environ.get('YTDLP_PO_TOKEN')
|
| 45 |
+
if PO_TOKEN:
|
| 46 |
+
logger.info("YTDLP_PO_TOKEN detected and will be used.")
|
| 47 |
+
|
| 48 |
+
# ----------------------------------------
|
| 49 |
+
|
| 50 |
+
# FastAPI app
|
| 51 |
+
app = FastAPI()
|
| 52 |
+
|
| 53 |
+
# Configure CORS
|
| 54 |
+
default_origins = [
|
| 55 |
+
"http://localhost:5173",
|
| 56 |
+
"http://localhost:8080",
|
| 57 |
+
"http://localhost:3000",
|
| 58 |
+
"http://localhost:8000",
|
| 59 |
+
"https://aimusicapp-a2b65.web.app",
|
| 60 |
+
"https://aimusicapp-a2b65.firebaseapp.com",
|
| 61 |
+
]
|
| 62 |
+
allowed_origins_env = os.environ.get('ALLOWED_ORIGINS')
|
| 63 |
+
allowed_origins = [o.strip() for o in allowed_origins_env.split(',') if o.strip()] if allowed_origins_env else default_origins
|
| 64 |
+
|
| 65 |
+
app.add_middleware(
|
| 66 |
+
CORSMiddleware,
|
| 67 |
+
allow_origins=allowed_origins,
|
| 68 |
+
allow_credentials=True,
|
| 69 |
+
allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],
|
| 70 |
+
allow_headers=["Authorization", "Content-Type", "X-Requested-With"],
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
@app.options("/youtube")
|
| 74 |
+
@app.options("/upload")
|
| 75 |
+
def options_handler(request: Request):
|
| 76 |
+
origin = request.headers.get("origin")
|
| 77 |
+
return Response(status_code=200, headers={
|
| 78 |
+
"Access-Control-Allow-Origin": origin or "*",
|
| 79 |
+
"Access-Control-Allow-Methods": "POST, OPTIONS",
|
| 80 |
+
"Access-Control-Allow-Headers": "Content-Type, Authorization",
|
| 81 |
+
})
|
| 82 |
+
|
| 83 |
+
class YouTubeInput(BaseModel):
|
| 84 |
+
youtube_url: str
|
| 85 |
+
|
| 86 |
+
@app.get("/")
|
| 87 |
+
def health_check():
|
| 88 |
+
return {"status": "healthy", "message": "AI Music App Backend is running (Pure Python)"}
|
| 89 |
+
|
| 90 |
+
# --- Utility Functions ---
|
| 91 |
+
|
| 92 |
+
def get_video_id_from_url(url: str) -> str:
|
| 93 |
+
m = re.search(r'(?:v=|youtu\.be/)([A-Za-z0-9_-]{6,})', url)
|
| 94 |
+
return m.group(1) if m else None
|
| 95 |
+
|
| 96 |
+
def find_ffmpeg() -> str:
|
| 97 |
+
common_paths = ["/opt/homebrew/bin/ffmpeg", "/usr/local/bin/ffmpeg", "/usr/bin/ffmpeg"]
|
| 98 |
+
for path in common_paths:
|
| 99 |
+
if os.path.exists(path) and os.access(path, os.X_OK):
|
| 100 |
+
return path
|
| 101 |
+
return shutil.which("ffmpeg") or "ffmpeg"
|
| 102 |
+
|
| 103 |
+
FFMPEG_PATH = find_ffmpeg()
|
| 104 |
+
FFMPEG_DIR = os.path.dirname(FFMPEG_PATH) if FFMPEG_PATH != "ffmpeg" else None
|
| 105 |
+
logger.info(f"Using ffmpeg at: {FFMPEG_PATH}")
|
| 106 |
+
|
| 107 |
+
def find_demucs() -> list:
|
| 108 |
+
import sys
|
| 109 |
+
path = shutil.which("demucs")
|
| 110 |
+
if path: return [path]
|
| 111 |
+
try:
|
| 112 |
+
import demucs
|
| 113 |
+
return [sys.executable, "-m", "demucs"]
|
| 114 |
+
except ImportError:
|
| 115 |
+
return ["demucs"]
|
| 116 |
+
|
| 117 |
+
DEMUCS_CMD = find_demucs()
|
| 118 |
+
CACHE_DIR = os.path.join(tempfile.gettempdir(), "aimusic_cache")
|
| 119 |
+
os.makedirs(CACHE_DIR, exist_ok=True)
|
| 120 |
+
|
| 121 |
+
# --- Firebase Admin Setup ---
|
| 122 |
+
firebase_admin = None
|
| 123 |
+
firebase_auth = None
|
| 124 |
+
FIREBASE_INITIALIZED = False
|
| 125 |
+
|
| 126 |
+
try:
|
| 127 |
+
import firebase_admin
|
| 128 |
+
from firebase_admin import credentials, auth as firebase_auth
|
| 129 |
+
if not firebase_admin._apps:
|
| 130 |
+
cred_json = os.environ.get('FIREBASE_CREDENTIALS')
|
| 131 |
+
if cred_json:
|
| 132 |
+
cred = credentials.Certificate(json.loads(cred_json))
|
| 133 |
+
firebase_admin.initialize_app(cred)
|
| 134 |
+
FIREBASE_INITIALIZED = True
|
| 135 |
+
logger.info("Firebase Admin initialized via environment variable")
|
| 136 |
+
else:
|
| 137 |
+
# Try to find a JSON file in the project folder
|
| 138 |
+
for f in os.listdir(os.path.dirname(os.path.abspath(__file__))):
|
| 139 |
+
if f.endswith('.json') and 'firebase' in f.lower() and 'admin' in f.lower():
|
| 140 |
+
firebase_admin.initialize_app(credentials.Certificate(f))
|
| 141 |
+
FIREBASE_INITIALIZED = True
|
| 142 |
+
logger.info(f"Firebase Admin initialized via file: {f}")
|
| 143 |
+
break
|
| 144 |
+
except Exception as e:
|
| 145 |
+
logger.warning(f"Firebase Admin setup skipped: {e}")
|
| 146 |
+
|
| 147 |
+
PROFILES_FILE = os.path.join(CACHE_DIR, "profiles.json")
|
| 148 |
+
|
| 149 |
+
class ProfileIn(BaseModel):
|
| 150 |
+
display_name: str | None = None
|
| 151 |
+
profile_picture: str | None = None
|
| 152 |
+
|
| 153 |
+
class ProfileOut(BaseModel):
|
| 154 |
+
user_id: str
|
| 155 |
+
display_name: str | None = None
|
| 156 |
+
email: str | None = None
|
| 157 |
+
profile_picture: str | None = None
|
| 158 |
+
created_at: str | None = None
|
| 159 |
+
updated_at: str | None = None
|
| 160 |
+
|
| 161 |
+
def load_profiles() -> dict:
|
| 162 |
+
try:
|
| 163 |
+
if os.path.exists(PROFILES_FILE):
|
| 164 |
+
with open(PROFILES_FILE, 'r', encoding='utf-8') as fh:
|
| 165 |
+
return json.loads(fh.read())
|
| 166 |
+
except Exception:
|
| 167 |
+
logger.exception('Failed to load profiles file')
|
| 168 |
+
return {}
|
| 169 |
+
|
| 170 |
+
def save_profiles(data: dict) -> None:
|
| 171 |
+
try:
|
| 172 |
+
with open(PROFILES_FILE, 'w', encoding='utf-8') as fh:
|
| 173 |
+
fh.write(json.dumps(data, ensure_ascii=False, indent=2))
|
| 174 |
+
except Exception:
|
| 175 |
+
logger.exception('Failed to save profiles file')
|
| 176 |
+
|
| 177 |
+
def verify_firebase_token(authorization: str | None):
|
| 178 |
+
# Development bypass
|
| 179 |
+
dev_bypass = os.environ.get('DEV_ALLOW_PROFILE_NO_AUTH', '').lower() in ('1', 'true', 'yes')
|
| 180 |
+
if dev_bypass:
|
| 181 |
+
uid, email = 'dev-user', 'dev@example.com'
|
| 182 |
+
if authorization and authorization.lower().startswith('bearer '):
|
| 183 |
+
token = authorization.split(' ', 1)[1].strip()
|
| 184 |
+
if ':' in token:
|
| 185 |
+
parts = token.split(':', 1)
|
| 186 |
+
uid = parts[0] or uid
|
| 187 |
+
if len(parts) > 1: email = parts[1] or email
|
| 188 |
+
return {'user_id': uid, 'email': email}
|
| 189 |
+
|
| 190 |
+
if not authorization or not authorization.lower().startswith('bearer '):
|
| 191 |
+
raise HTTPException(status_code=401, detail='Missing or invalid Authorization header')
|
| 192 |
+
|
| 193 |
+
token = authorization.split(' ', 1)[1].strip()
|
| 194 |
+
if FIREBASE_INITIALIZED and firebase_auth:
|
| 195 |
+
try:
|
| 196 |
+
decoded = firebase_auth.verify_id_token(token)
|
| 197 |
+
return {'user_id': decoded.get('uid'), 'email': decoded.get('email')}
|
| 198 |
+
except Exception:
|
| 199 |
+
raise HTTPException(status_code=401, detail='Firebase token verification failed')
|
| 200 |
+
raise HTTPException(status_code=401, detail='Firebase Admin not initialized')
|
| 201 |
+
|
| 202 |
+
def get_current_user(authorization: str | None = Header(None)):
|
| 203 |
+
return verify_firebase_token(authorization)
|
| 204 |
+
|
| 205 |
+
@app.get("/api/profile", response_model=ProfileOut)
|
| 206 |
+
def get_profile(user=Depends(get_current_user)):
|
| 207 |
+
profiles = load_profiles()
|
| 208 |
+
p = profiles.get(user['user_id'], {})
|
| 209 |
+
return {
|
| 210 |
+
"user_id": user['user_id'],
|
| 211 |
+
"email": user['email'],
|
| 212 |
+
"display_name": p.get("display_name"),
|
| 213 |
+
"profile_picture": p.get("profile_picture"),
|
| 214 |
+
"created_at": p.get("created_at"),
|
| 215 |
+
"updated_at": p.get("updated_at")
|
| 216 |
+
}
|
| 217 |
+
|
| 218 |
+
@app.post("/api/profile", response_model=ProfileOut)
|
| 219 |
+
def update_profile(data: ProfileIn, user=Depends(get_current_user)):
|
| 220 |
+
profiles = load_profiles()
|
| 221 |
+
u_id = user['user_id']
|
| 222 |
+
now = datetime.utcnow().isoformat()
|
| 223 |
+
|
| 224 |
+
if u_id not in profiles:
|
| 225 |
+
profiles[u_id] = {"created_at": now}
|
| 226 |
+
|
| 227 |
+
p = profiles[u_id]
|
| 228 |
+
if data.display_name is not None: p["display_name"] = data.display_name
|
| 229 |
+
if data.profile_picture is not None: p["profile_picture"] = data.profile_picture
|
| 230 |
+
p["updated_at"] = now
|
| 231 |
+
|
| 232 |
+
save_profiles(profiles)
|
| 233 |
+
return {**p, "user_id": u_id, "email": user['email']}
|
| 234 |
+
|
| 235 |
+
# --- Core Logic ---
|
| 236 |
+
|
| 237 |
+
def run_demucs_and_extract(input_path: str, tmpdir: str) -> str:
|
| 238 |
+
output_dir = os.path.join(tmpdir, "stems")
|
| 239 |
+
os.makedirs(output_dir, exist_ok=True)
|
| 240 |
+
|
| 241 |
+
cmd = DEMUCS_CMD + ["-o", output_dir, input_path]
|
| 242 |
+
logger.info(f"Running demucs: {' '.join(cmd)}")
|
| 243 |
+
subprocess.run(cmd, check=True, capture_output=True, text=True)
|
| 244 |
+
|
| 245 |
+
mp3_dir = os.path.join(tmpdir, "stems_mp3")
|
| 246 |
+
os.makedirs(mp3_dir, exist_ok=True)
|
| 247 |
+
|
| 248 |
+
# Walk to find all .wav files (handles various models like htdemucs)
|
| 249 |
+
wav_count = 0
|
| 250 |
+
for root, dirs, files in os.walk(output_dir):
|
| 251 |
+
for f in files:
|
| 252 |
+
if f.endswith('.wav'):
|
| 253 |
+
src = os.path.join(root, f)
|
| 254 |
+
dst = os.path.join(mp3_dir, f.replace('.wav', '.mp3'))
|
| 255 |
+
logger.info(f"Converting: {src} -> {dst}")
|
| 256 |
+
subprocess.run([FFMPEG_PATH, "-y", "-i", src, "-codec:a", "libmp3lame", "-qscale:a", "2", dst], check=True)
|
| 257 |
+
wav_count += 1
|
| 258 |
+
|
| 259 |
+
logger.info(f"Demucs processing finished. Found and converted {wav_count} stems.")
|
| 260 |
+
if wav_count == 0:
|
| 261 |
+
raise Exception("Demucs produced no output files. Check if the model is installed and the input is valid.")
|
| 262 |
+
|
| 263 |
+
# Create instrumental mix
|
| 264 |
+
stems = [os.path.join(mp3_dir, f) for f in os.listdir(mp3_dir) if 'vocal' not in f.lower() and f.endswith('.mp3')]
|
| 265 |
+
if stems:
|
| 266 |
+
inst_path = os.path.join(mp3_dir, 'instrumental.mp3')
|
| 267 |
+
n = len(stems)
|
| 268 |
+
labels = "".join(f"[{i}:a]" for i in range(n))
|
| 269 |
+
subprocess.run([FFMPEG_PATH, "-y"] + [i for s in stems for i in ("-i", s)] +
|
| 270 |
+
["-filter_complex", f"{labels}amix=inputs={n}:normalize=0", "-c:a", "libmp3lame", "-qscale:a", "2", inst_path], check=True)
|
| 271 |
+
|
| 272 |
+
logger.info(f"MP3 Directory contents: {os.listdir(mp3_dir)}")
|
| 273 |
+
return mp3_dir
|
| 274 |
+
|
| 275 |
+
@app.post("/youtube")
|
| 276 |
+
def process_youtube_audio(data: YouTubeInput, background_tasks: BackgroundTasks):
|
| 277 |
+
if not re.match(YT_PATTERN, data.youtube_url):
|
| 278 |
+
raise HTTPException(status_code=400, detail="Invalid YouTube URL")
|
| 279 |
+
|
| 280 |
+
vid = get_video_id_from_url(data.youtube_url)
|
| 281 |
+
if vid:
|
| 282 |
+
cache_path = os.path.join(CACHE_DIR, f"{vid}.zip")
|
| 283 |
+
if os.path.exists(cache_path):
|
| 284 |
+
return FileResponse(cache_path, filename="extracted_stems.zip", media_type="application/zip")
|
| 285 |
+
|
| 286 |
+
tmpdir = tempfile.mkdtemp()
|
| 287 |
+
try:
|
| 288 |
+
audio_path = os.path.join(tmpdir, "audio.mp3")
|
| 289 |
+
|
| 290 |
+
# 1. Fetch Title
|
| 291 |
+
title_cmd = [
|
| 292 |
+
"yt-dlp", "--get-title", "--no-warnings",
|
| 293 |
+
"--user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36",
|
| 294 |
+
"--add-header", "Referer: https://www.google.com",
|
| 295 |
+
data.youtube_url
|
| 296 |
+
]
|
| 297 |
+
if os.environ.get('YTDLP_COOKIES_FILE'): title_cmd.extend(["--cookies", os.environ['YTDLP_COOKIES_FILE']])
|
| 298 |
+
if PO_TOKEN: title_cmd.extend(["--extractor-args", f"youtube:po_token={PO_TOKEN}"])
|
| 299 |
+
try:
|
| 300 |
+
res = subprocess.run(title_cmd, capture_output=True, text=True, check=True)
|
| 301 |
+
video_title = res.stdout.strip()
|
| 302 |
+
except subprocess.CalledProcessError as e:
|
| 303 |
+
logger.error(f"yt-dlp title fetch failed: {e.stderr}")
|
| 304 |
+
video_title = "Unknown Title"
|
| 305 |
+
|
| 306 |
+
# 2. Download Audio
|
| 307 |
+
dl_cmd = [
|
| 308 |
+
"yt-dlp", "-x", "--audio-format", "mp3",
|
| 309 |
+
"--force-ipv4", "--no-playlist", "--no-warnings",
|
| 310 |
+
"--user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36",
|
| 311 |
+
"--add-header", "Referer: https://www.google.com",
|
| 312 |
+
"-o", audio_path, data.youtube_url
|
| 313 |
+
]
|
| 314 |
+
if os.environ.get('YTDLP_COOKIES_FILE'): dl_cmd.extend(["--cookies", os.environ['YTDLP_COOKIES_FILE']])
|
| 315 |
+
if PO_TOKEN: dl_cmd.extend(["--extractor-args", f"youtube:po_token={PO_TOKEN}"])
|
| 316 |
+
if FFMPEG_DIR: dl_cmd.extend(["--ffmpeg-location", FFMPEG_DIR])
|
| 317 |
+
|
| 318 |
+
logger.info(f"Downloading: {data.youtube_url}")
|
| 319 |
+
try:
|
| 320 |
+
subprocess.run(dl_cmd, check=True, capture_output=True, text=True)
|
| 321 |
+
except subprocess.CalledProcessError as e:
|
| 322 |
+
logger.error(f"yt-dlp download failed: {e.stderr}")
|
| 323 |
+
if "Incomplete YouTube ID" in e.stderr:
|
| 324 |
+
raise HTTPException(status_code=400, detail="Invalid or truncated YouTube URL ID.")
|
| 325 |
+
raise e
|
| 326 |
+
|
| 327 |
+
# 3. Process with Demucs
|
| 328 |
+
extracted_dir = run_demucs_and_extract(audio_path, tmpdir)
|
| 329 |
+
|
| 330 |
+
logger.info(f"Zipping directory: {extracted_dir}, Contents: {os.listdir(extracted_dir)}")
|
| 331 |
+
final_zip_path = os.path.join(tmpdir, "extracted_stems.zip")
|
| 332 |
+
with zipfile.ZipFile(final_zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
|
| 333 |
+
for root, dirs, files in os.walk(extracted_dir):
|
| 334 |
+
for file in files:
|
| 335 |
+
file_path = os.path.join(root, file)
|
| 336 |
+
arcname = os.path.relpath(file_path, extracted_dir)
|
| 337 |
+
zipf.write(file_path, arcname)
|
| 338 |
+
|
| 339 |
+
zip_size = os.path.getsize(final_zip_path)
|
| 340 |
+
logger.info(f"Created zip file at {final_zip_path}, Size: {zip_size} bytes")
|
| 341 |
+
|
| 342 |
+
if vid:
|
| 343 |
+
cache_path = os.path.join(CACHE_DIR, f"{vid}.zip")
|
| 344 |
+
shutil.copyfile(final_zip_path, cache_path)
|
| 345 |
+
# Serve from cache to avoid race conditions with cleanup
|
| 346 |
+
final_zip_path = cache_path
|
| 347 |
+
|
| 348 |
+
# Sanitize title for HTTP header (prevent latin-1 encoding errors)
|
| 349 |
+
safe_title = video_title.encode('ascii', 'ignore').decode('ascii')
|
| 350 |
+
|
| 351 |
+
background_tasks.add_task(shutil.rmtree, tmpdir, True)
|
| 352 |
+
return FileResponse(final_zip_path, filename="extracted_stems.zip", media_type="application/zip", headers={"X-Video-Title": safe_title})
|
| 353 |
+
|
| 354 |
+
except Exception as e:
|
| 355 |
+
shutil.rmtree(tmpdir, ignore_errors=True)
|
| 356 |
+
logger.error(f"YouTube processing error: {e}")
|
| 357 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 358 |
+
|
| 359 |
+
@app.post("/upload")
|
| 360 |
+
def process_upload(file: UploadFile = File(...), background_tasks: BackgroundTasks = None):
|
| 361 |
+
tmpdir = tempfile.mkdtemp()
|
| 362 |
+
try:
|
| 363 |
+
input_path = os.path.join(tmpdir, file.filename)
|
| 364 |
+
audio_path = os.path.join(tmpdir, "audio.mp3")
|
| 365 |
+
|
| 366 |
+
with open(input_path, "wb") as f: f.write(file.file.read())
|
| 367 |
+
|
| 368 |
+
subprocess.run([FFMPEG_PATH, "-y", "-i", input_path, "-ac", "2", "-ar", "44100", audio_path], check=True)
|
| 369 |
+
extracted_dir = run_demucs_and_extract(audio_path, tmpdir)
|
| 370 |
+
|
| 371 |
+
logger.info(f"Zipping directory: {extracted_dir}, Contents: {os.listdir(extracted_dir)}")
|
| 372 |
+
final_zip_path = os.path.join(tmpdir, "extracted_stems.zip")
|
| 373 |
+
with zipfile.ZipFile(final_zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
|
| 374 |
+
for root, dirs, files in os.walk(extracted_dir):
|
| 375 |
+
for file in files:
|
| 376 |
+
file_path = os.path.join(root, file)
|
| 377 |
+
arcname = os.path.relpath(file_path, extracted_dir)
|
| 378 |
+
zipf.write(file_path, arcname)
|
| 379 |
+
|
| 380 |
+
digest = hashlib.sha256(open(final_zip_path, 'rb').read()).hexdigest()
|
| 381 |
+
cache_path = os.path.join(CACHE_DIR, f"{digest}.zip")
|
| 382 |
+
shutil.copyfile(final_zip_path, cache_path)
|
| 383 |
+
|
| 384 |
+
if background_tasks: background_tasks.add_task(shutil.rmtree, tmpdir, True)
|
| 385 |
+
return FileResponse(cache_path, filename="extracted_stems.zip", media_type="application/zip")
|
| 386 |
+
except Exception as e:
|
| 387 |
+
shutil.rmtree(tmpdir, ignore_errors=True)
|
| 388 |
+
logger.error(f"Upload processing error: {e}")
|
| 389 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 390 |
+
|
| 391 |
+
@app.post("/youtube/extracted")
|
| 392 |
+
def process_youtube_audio_extracted(data: YouTubeInput):
|
| 393 |
+
if not re.match(YT_PATTERN, data.youtube_url):
|
| 394 |
+
raise HTTPException(status_code=400, detail="Invalid YouTube URL")
|
| 395 |
+
|
| 396 |
+
tmpdir = tempfile.mkdtemp()
|
| 397 |
+
try:
|
| 398 |
+
audio_path = os.path.join(tmpdir, "audio.mp3")
|
| 399 |
+
dl_cmd = ["yt-dlp", "-x", "--audio-format", "mp3", "--force-ipv4", "--no-playlist", "-o", audio_path, data.youtube_url]
|
| 400 |
+
if os.environ.get('YTDLP_COOKIES_FILE'): dl_cmd.extend(["--cookies", os.environ['YTDLP_COOKIES_FILE']])
|
| 401 |
+
if PO_TOKEN: dl_cmd.extend(["--extractor-args", f"youtube:po_token={PO_TOKEN}"])
|
| 402 |
+
|
| 403 |
+
try:
|
| 404 |
+
subprocess.run(dl_cmd, check=True, capture_output=True, text=True)
|
| 405 |
+
except subprocess.CalledProcessError as e:
|
| 406 |
+
logger.error(f"yt-dlp extracted download failed: {e.stderr}")
|
| 407 |
+
raise e
|
| 408 |
+
extracted_dir = run_demucs_and_extract(audio_path, tmpdir)
|
| 409 |
+
|
| 410 |
+
files = []
|
| 411 |
+
for f in os.listdir(extracted_dir):
|
| 412 |
+
files.append({"filename": f, "path": os.path.join(extracted_dir, f)})
|
| 413 |
+
|
| 414 |
+
return {"message": "Success", "extracted_files": files, "extracted_directory": extracted_dir}
|
| 415 |
+
except Exception as e:
|
| 416 |
+
shutil.rmtree(tmpdir, ignore_errors=True)
|
| 417 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 418 |
+
|
| 419 |
+
@app.post("/upload/extracted")
|
| 420 |
+
def process_upload_extracted(file: UploadFile = File(...)):
|
| 421 |
+
tmpdir = tempfile.mkdtemp()
|
| 422 |
+
try:
|
| 423 |
+
input_path = os.path.join(tmpdir, file.filename)
|
| 424 |
+
audio_path = os.path.join(tmpdir, "audio.mp3")
|
| 425 |
+
with open(input_path, "wb") as f: f.write(file.file.read())
|
| 426 |
+
subprocess.run([FFMPEG_PATH, "-y", "-i", input_path, "-ac", "2", "-ar", "44100", audio_path], check=True)
|
| 427 |
+
extracted_dir = run_demucs_and_extract(audio_path, tmpdir)
|
| 428 |
+
|
| 429 |
+
files = []
|
| 430 |
+
for f in os.listdir(extracted_dir):
|
| 431 |
+
files.append({"filename": f, "path": os.path.join(extracted_dir, f)})
|
| 432 |
+
|
| 433 |
+
return {"message": "Success", "extracted_files": files, "extracted_directory": extracted_dir}
|
| 434 |
+
except Exception as e:
|
| 435 |
+
shutil.rmtree(tmpdir, ignore_errors=True)
|
| 436 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 437 |
+
|
| 438 |
+
@app.get('/cache/{key}')
|
| 439 |
+
def get_cache(key: str):
|
| 440 |
+
path = os.path.join(CACHE_DIR, f"{key}.zip")
|
| 441 |
+
if not os.path.exists(path): raise HTTPException(status_code=404, detail="Not found")
|
| 442 |
+
return FileResponse(path, filename="extracted_stems.zip", media_type="application/zip")
|
| 443 |
+
|
| 444 |
+
@app.get('/stems/{key}/{filename:path}')
|
| 445 |
+
def get_stem(key: str, filename: str):
|
| 446 |
+
zip_path = os.path.join(CACHE_DIR, f"{key}.zip")
|
| 447 |
+
if not os.path.exists(zip_path):
|
| 448 |
+
raise HTTPException(status_code=404, detail="Cache not found")
|
| 449 |
+
|
| 450 |
+
try:
|
| 451 |
+
with zipfile.ZipFile(zip_path, 'r') as zf:
|
| 452 |
+
# zipfile names usually match the relative path in the archive
|
| 453 |
+
# if we have subdirs in the zip, we might need to search
|
| 454 |
+
target = filename
|
| 455 |
+
if target not in zf.namelist():
|
| 456 |
+
# try to find by basename
|
| 457 |
+
found = None
|
| 458 |
+
for name in zf.namelist():
|
| 459 |
+
if os.path.basename(name) == filename:
|
| 460 |
+
found = name
|
| 461 |
+
break
|
| 462 |
+
if not found:
|
| 463 |
+
raise HTTPException(status_code=404, detail="Stem not found in archive")
|
| 464 |
+
target = found
|
| 465 |
+
|
| 466 |
+
data = zf.read(target)
|
| 467 |
+
return Response(content=data, media_type="audio/mpeg", headers={"Content-Disposition": f"attachment; filename={filename}"})
|
| 468 |
+
except Exception as e:
|
| 469 |
+
logger.error(f"Error extracting stem: {e}")
|
| 470 |
+
raise HTTPException(status_code=500, detail="Failed to extract stem from archive")
|
| 471 |
+
|
| 472 |
+
if __name__ == "__main__":
|
| 473 |
+
import uvicorn
|
| 474 |
+
uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", 8000)))
|
requirements-base.txt
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
fastapi
|
| 2 |
+
uvicorn
|
| 3 |
+
pydantic
|
| 4 |
+
ffmpeg-python
|
| 5 |
+
python-multipart
|
| 6 |
+
soundfile
|
| 7 |
+
yt-dlp
|
| 8 |
+
firebase-admin
|
| 9 |
+
torchcodec
|
| 10 |
+
torch
|
| 11 |
+
torchaudio
|
requirements-demucs.txt
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Demucs and its dependencies (installed separately to avoid version conflicts)
|
| 2 |
+
# Install with: pip install --no-deps git+https://github.com/facebookresearch/demucs.git
|
| 3 |
+
# Then install dependencies manually
|
| 4 |
+
dora-search
|
| 5 |
+
einops
|
| 6 |
+
julius>=0.2.3
|
| 7 |
+
openunmix
|
| 8 |
+
tqdm
|
| 9 |
+
pyyaml
|
| 10 |
+
lameenc>=1.2
|
requirements.txt
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Base dependencies
|
| 2 |
+
fastapi
|
| 3 |
+
uvicorn
|
| 4 |
+
pydantic
|
| 5 |
+
ffmpeg-python
|
| 6 |
+
python-multipart
|
| 7 |
+
soundfile
|
| 8 |
+
yt-dlp
|
| 9 |
+
firebase-admin
|
| 10 |
+
torchcodec
|
| 11 |
+
torch
|
| 12 |
+
torchaudio
|
| 13 |
+
|
| 14 |
+
# NOTE: Demucs is installed separately via install.sh or build script
|
| 15 |
+
# to avoid torchaudio version conflict (demucs requires <2.1, but only 2.6+ available)
|
| 16 |
+
# See install.sh or deployment instructions in README
|