Chrunos commited on
Commit
af3f642
·
verified ·
1 Parent(s): 390c953

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +81 -79
app.py CHANGED
@@ -37,85 +37,6 @@ BASE_URL = "https://chrunos-depot.hf.space"
37
 
38
  # Deezer ARL token (required for deezspot downloads)
39
  ARL_TOKEN = os.getenv('ARL')
40
- dl = DeeLogin(arl=ARL_TOKEN)
41
-
42
- # Spotify credentials from environment variables
43
- SPOTIFY_USERNAME = os.getenv("SPOTIFY_USERNAME")
44
- SPOTIFY_CREDENTIALS = os.getenv("SPOTIFY_CREDENTIALS")
45
-
46
- if not SPOTIFY_USERNAME or not SPOTIFY_CREDENTIALS:
47
- raise RuntimeError("Spotify credentials not found in environment variables")
48
-
49
- # Create a temporary credentials.json file
50
- CREDENTIALS_PATH = "/tmp/credentials.json"
51
- with open(CREDENTIALS_PATH, "w") as f:
52
- json.dump({
53
- "username": SPOTIFY_USERNAME,
54
- "credentials": SPOTIFY_CREDENTIALS,
55
- "type": "AUTHENTICATION_STORED_SPOTIFY_CREDENTIALS"
56
- }, f)
57
-
58
- # Initialize Spotify client
59
- spo = SpoLogin(credentials_path=CREDENTIALS_PATH)
60
-
61
-
62
- # 定义请求体模型
63
- class DownloadRequest(BaseModel):
64
- url: str
65
- quality: str
66
-
67
-
68
- def cleanup_dir(dir_path: Path):
69
- """Background task to clean up directory"""
70
- try:
71
- shutil.rmtree(dir_path)
72
- logger.info(f"Cleaned up directory: {dir_path}")
73
- except Exception as e:
74
- logger.error(f"Error cleaning up {dir_path}: {e}")
75
-
76
-
77
- # Download a Spotify track and return a download URL
78
- @app.post("/spot-track/{track_id}")
79
- async def download_spotify_track(
80
- track_id: str,
81
- background_tasks: BackgroundTasks
82
- ):
83
- try:
84
- downloads_dir = Path("downloads")
85
- # Create unique directory for this download
86
- download_id = uuid.uuid4().hex
87
- download_dir = downloads_dir / download_id
88
- download_dir.mkdir(parents=True, exist_ok=True)
89
-
90
- # Download to unique directory
91
- logger.info(f"Downloading to {download_dir}")
92
- spo.download_track(
93
- link_track=f"https://open.spotify.com/track/{track_id}",
94
- output_dir=str(download_dir),
95
- quality_download="VERY_HIGH",
96
- recursive_quality=False,
97
- recursive_download=False,
98
- not_interface=False,
99
- method_save=1
100
- )
101
-
102
- # Find downloaded file
103
- filepath = next(download_dir.glob(f"**/*.ogg"), None)
104
- if not filepath:
105
- raise HTTPException(status_code=500, detail="File not found after download")
106
-
107
- # Schedule cleanup after response is sent
108
- #background_tasks.add_task(cleanup_dir, download_dir)
109
-
110
- # Return path with unique directory
111
- relative_path = quote(str(filepath.relative_to(downloads_dir)))
112
- return {"download_url": f"{BASE_URL}/downloads/{relative_path}"}
113
-
114
- except Exception as e:
115
- logger.error(f"Error downloading track: {e}")
116
- raise HTTPException(status_code=500, detail=str(e))
117
-
118
-
119
 
120
  @app.get("/")
121
  def read_root():
@@ -147,6 +68,7 @@ def get_track(track_id: str):
147
  @app.post("/download/track")
148
  def download_track(request: DownloadRequest):
149
  try:
 
150
  url = request.url
151
  quality = request.quality
152
 
@@ -229,3 +151,83 @@ def search_tracks(query: str, limit: Optional[int] = 10):
229
  except Exception as e:
230
  logger.error(f"Error searching tracks: {e}")
231
  raise HTTPException(status_code=500, detail=str(e))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
 
38
  # Deezer ARL token (required for deezspot downloads)
39
  ARL_TOKEN = os.getenv('ARL')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
 
41
  @app.get("/")
42
  def read_root():
 
68
  @app.post("/download/track")
69
  def download_track(request: DownloadRequest):
70
  try:
71
+ dl = DeeLogin(arl=ARL_TOKEN)
72
  url = request.url
73
  quality = request.quality
74
 
 
151
  except Exception as e:
152
  logger.error(f"Error searching tracks: {e}")
153
  raise HTTPException(status_code=500, detail=str(e))
154
+
155
+ # Spotify credentials from environment variables
156
+ '''SPOTIFY_USERNAME = os.getenv("SPOTIFY_USERNAME")
157
+ SPOTIFY_CREDENTIALS = os.getenv("SPOTIFY_CREDENTIALS")
158
+
159
+ if not SPOTIFY_USERNAME or not SPOTIFY_CREDENTIALS:
160
+ raise RuntimeError("Spotify credentials not found in environment variables")
161
+
162
+ # Create a temporary credentials.json file
163
+ CREDENTIALS_PATH = "/tmp/credentials.json"
164
+ with open(CREDENTIALS_PATH, "w") as f:
165
+ json.dump({
166
+ "username": SPOTIFY_USERNAME,
167
+ "credentials": SPOTIFY_CREDENTIALS,
168
+ "type": "AUTHENTICATION_STORED_SPOTIFY_CREDENTIALS"
169
+ }, f)
170
+
171
+ # Initialize Spotify client
172
+ spo = SpoLogin(credentials_path=CREDENTIALS_PATH)
173
+
174
+
175
+ # 定义请求体模型
176
+ class DownloadRequest(BaseModel):
177
+ url: str
178
+ quality: str
179
+
180
+
181
+ def cleanup_dir(dir_path: Path):
182
+ """Background task to clean up directory"""
183
+ try:
184
+ shutil.rmtree(dir_path)
185
+ logger.info(f"Cleaned up directory: {dir_path}")
186
+ except Exception as e:
187
+ logger.error(f"Error cleaning up {dir_path}: {e}")
188
+
189
+
190
+ # Download a Spotify track and return a download URL
191
+ @app.post("/spot-track/{track_id}")
192
+ async def download_spotify_track(
193
+ track_id: str,
194
+ background_tasks: BackgroundTasks
195
+ ):
196
+ try:
197
+ downloads_dir = Path("downloads")
198
+ # Create unique directory for this download
199
+ download_id = uuid.uuid4().hex
200
+ download_dir = downloads_dir / download_id
201
+ download_dir.mkdir(parents=True, exist_ok=True)
202
+
203
+ # Download to unique directory
204
+ logger.info(f"Downloading to {download_dir}")
205
+ spo.download_track(
206
+ link_track=f"https://open.spotify.com/track/{track_id}",
207
+ output_dir=str(download_dir),
208
+ quality_download="VERY_HIGH",
209
+ recursive_quality=False,
210
+ recursive_download=False,
211
+ not_interface=False,
212
+ method_save=1
213
+ )
214
+
215
+ # Find downloaded file
216
+ filepath = next(download_dir.glob(f"**/*.ogg"), None)
217
+ if not filepath:
218
+ raise HTTPException(status_code=500, detail="File not found after download")
219
+
220
+ # Schedule cleanup after response is sent
221
+ #background_tasks.add_task(cleanup_dir, download_dir)
222
+
223
+ # Return path with unique directory
224
+ relative_path = quote(str(filepath.relative_to(downloads_dir)))
225
+ return {"download_url": f"{BASE_URL}/downloads/{relative_path}"}
226
+
227
+ except Exception as e:
228
+ logger.error(f"Error downloading track: {e}")
229
+ raise HTTPException(status_code=500, detail=str(e))
230
+ '''
231
+
232
+
233
+