Chrunos commited on
Commit
a9f35e5
·
verified ·
1 Parent(s): a4ae7b7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +35 -35
app.py CHANGED
@@ -12,6 +12,8 @@ from dotenv import load_dotenv
12
  from pydantic import BaseModel
13
  from urllib.parse import quote
14
  from pathlib import Path
 
 
15
 
16
 
17
  # Set up logging
@@ -33,9 +35,7 @@ DEEZER_API_URL = "https://api.deezer.com"
33
  # Base URL for the server
34
  BASE_URL = "https://tecuts-depot.hf.space"
35
 
36
- # Deezer ARL token (required for deezspot downloads)
37
- ARL_TOKEN = os.getenv('ARL')
38
- dl = DeeLogin(arl=ARL_TOKEN)
39
 
40
  # Spotify credentials from environment variables
41
  SPOTIFY_USERNAME = os.getenv("SPOTIFY_USERNAME")
@@ -63,55 +63,52 @@ class DownloadRequest(BaseModel):
63
  quality: str
64
 
65
 
 
 
 
 
 
 
 
66
 
67
 
68
-
69
- # Download a Spotify track and return a download URL
70
  @app.post("/spot-track/{track_id}")
71
- def download_spotify_track(track_id: str):
 
 
 
72
  try:
73
- # Clear the downloads directory
74
  downloads_dir = Path("downloads")
75
- for item in downloads_dir.iterdir():
76
- if item.is_file():
77
- item.unlink()
78
- elif item.is_dir():
79
- shutil.rmtree(item)
80
-
81
- # Download the track using spotloader
82
- logger.info(f"Downloading Spotify track: {track_id}")
83
  spo.download_track(
84
  link_track=f"https://open.spotify.com/track/{track_id}",
85
- output_dir=str(downloads_dir),
86
  quality_download="VERY_HIGH",
87
  recursive_quality=False,
88
  recursive_download=False,
89
  not_interface=False,
90
  method_save=1
91
  )
92
-
93
- file_extension = "ogg"
94
- # Recursively search for the file in the downloads directory
95
- filepath = None
96
- for root, dirs, files in os.walk(downloads_dir):
97
- for file in files:
98
- if file.endswith(f'.{file_extension}'):
99
- filepath = Path(root) / file
100
- break
101
- if filepath:
102
- break
103
 
 
 
104
  if not filepath:
105
- raise HTTPException(status_code=500, detail=f"{file_extension} file not found after download")
106
-
107
- file_size = filepath.stat().st_size
108
- logger.info(f"Downloaded file size: {file_size} bytes")
109
 
110
- # Return the download URL
 
 
 
111
  relative_path = quote(str(filepath.relative_to(downloads_dir)))
112
- download_url = f"{BASE_URL}/downloads/{relative_path}"
113
- logger.info(f"Download successful: {download_url}")
114
- return {"download_url": download_url}
115
  except Exception as e:
116
  logger.error(f"Error downloading track: {e}")
117
  raise HTTPException(status_code=500, detail=str(e))
@@ -150,6 +147,9 @@ def download_track(request: DownloadRequest):
150
  try:
151
  url = request.url
152
  quality = request.quality
 
 
 
153
 
154
  if quality not in ["MP3_320", "MP3_128", "FLAC"]:
155
  raise HTTPException(status_code=400, detail="Invalid quality specified")
 
12
  from pydantic import BaseModel
13
  from urllib.parse import quote
14
  from pathlib import Path
15
+ import uuid
16
+ from fastapi import BackgroundTasks
17
 
18
 
19
  # Set up logging
 
35
  # Base URL for the server
36
  BASE_URL = "https://tecuts-depot.hf.space"
37
 
38
+
 
 
39
 
40
  # Spotify credentials from environment variables
41
  SPOTIFY_USERNAME = os.getenv("SPOTIFY_USERNAME")
 
63
  quality: str
64
 
65
 
66
+ def cleanup_dir(dir_path: Path):
67
+ """Background task to clean up directory"""
68
+ try:
69
+ shutil.rmtree(dir_path)
70
+ logger.info(f"Cleaned up directory: {dir_path}")
71
+ except Exception as e:
72
+ logger.error(f"Error cleaning up {dir_path}: {e}")
73
 
74
 
75
+ # Download a Spotify track and return a download URL
 
76
  @app.post("/spot-track/{track_id}")
77
+ async def download_spotify_track(
78
+ track_id: str,
79
+ background_tasks: BackgroundTasks
80
+ ):
81
  try:
 
82
  downloads_dir = Path("downloads")
83
+ # Create unique directory for this download
84
+ download_id = uuid.uuid4().hex
85
+ download_dir = downloads_dir / download_id
86
+ download_dir.mkdir(parents=True, exist_ok=True)
87
+
88
+ # Download to unique directory
89
+ logger.info(f"Downloading to {download_dir}")
 
90
  spo.download_track(
91
  link_track=f"https://open.spotify.com/track/{track_id}",
92
+ output_dir=str(download_dir),
93
  quality_download="VERY_HIGH",
94
  recursive_quality=False,
95
  recursive_download=False,
96
  not_interface=False,
97
  method_save=1
98
  )
 
 
 
 
 
 
 
 
 
 
 
99
 
100
+ # Find downloaded file
101
+ filepath = next(download_dir.glob(f"**/*.ogg"), None)
102
  if not filepath:
103
+ raise HTTPException(status_code=500, detail="File not found after download")
 
 
 
104
 
105
+ # Schedule cleanup after response is sent
106
+ background_tasks.add_task(cleanup_dir, download_dir)
107
+
108
+ # Return path with unique directory
109
  relative_path = quote(str(filepath.relative_to(downloads_dir)))
110
+ return {"download_url": f"{BASE_URL}/downloads/{relative_path}"}
111
+
 
112
  except Exception as e:
113
  logger.error(f"Error downloading track: {e}")
114
  raise HTTPException(status_code=500, detail=str(e))
 
147
  try:
148
  url = request.url
149
  quality = request.quality
150
+ # Deezer ARL token (required for deezspot downloads)
151
+ ARL_TOKEN = os.getenv('ARL')
152
+ dl = DeeLogin(arl=ARL_TOKEN)
153
 
154
  if quality not in ["MP3_320", "MP3_128", "FLAC"]:
155
  raise HTTPException(status_code=400, detail="Invalid quality specified")