Keychain112 commited on
Commit
1a61348
·
verified ·
1 Parent(s): 1ce5c71

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +19 -53
main.py CHANGED
@@ -6,14 +6,18 @@ from fastapi.middleware.cors import CORSMiddleware
6
  from fastapi.responses import FileResponse
7
  from ytmusicapi import YTMusic
8
 
 
 
 
 
 
 
 
9
  app = FastAPI()
10
- ytm = YTMusic()
11
 
12
- # --- THE FIX: CORS MUST BE FIRST ---
13
- # This allows your Netlify website to access this Hugging Face API
14
  app.add_middleware(
15
  CORSMiddleware,
16
- allow_origins=["*"], # Allows all websites (Netlify) to connect
17
  allow_credentials=False,
18
  allow_methods=["*"],
19
  allow_headers=["*"],
@@ -21,25 +25,19 @@ app.add_middleware(
21
 
22
  @app.get("/")
23
  async def root():
24
- return {
25
- "status": "AmberTune Backend Online",
26
- "service": "Hugging Face Spaces",
27
- "version": "v1.0"
28
- }
29
 
30
  @app.get("/search")
31
  async def search(q: str):
 
 
32
  try:
 
33
  raw_results = ytm.search(q, filter="songs")
34
  results = []
35
  for res in raw_results:
36
  artists = ", ".join([a['name'] for a in res.get('artists', [])])
37
-
38
- thumb = ""
39
- if 'thumbnails' in res and len(res['thumbnails']) > 0:
40
- # Get the highest resolution thumbnail
41
- thumb = res['thumbnails'][-1]['url'].split('=')[0] + "=w512-h512"
42
-
43
  results.append({
44
  "id": res['videoId'],
45
  "title": res['title'],
@@ -48,58 +46,26 @@ async def search(q: str):
48
  })
49
  return results
50
  except Exception as e:
51
- print(f"Search Error: {e}")
52
- return []
 
53
 
54
  @app.get("/get_audio")
55
  async def get_audio(id: str):
56
  video_url = f"https://www.youtube.com/watch?v={id}"
 
57
  ydl_opts = {
58
  'format': 'bestaudio/best',
59
  'quiet': True,
60
- 'noplaylist': True,
61
- 'cachedir': False,
62
  }
63
  with yt_dlp.YoutubeDL(ydl_opts) as ydl:
64
  try:
65
  info = ydl.extract_info(video_url, download=False)
66
- # We return the direct URL so the browser player can stream it
67
  return {"url": info['url']}
68
  except Exception as e:
69
- print(f"Extraction failed: {e}")
70
- raise HTTPException(status_code=500, detail="Audio stream unavailable")
71
-
72
- @app.get("/download")
73
- async def download_audio(id: str, title: str):
74
- temp_dir = tempfile.gettempdir()
75
- file_path = os.path.join(temp_dir, f"{id}.mp3")
76
-
77
- ydl_opts = {
78
- 'format': 'bestaudio/best',
79
- 'outtmpl': file_path.replace('.mp3', ''),
80
- 'postprocessors': [{
81
- 'key': 'FFmpegExtractAudio',
82
- 'preferredcodec': 'mp3',
83
- 'preferredquality': '192',
84
- }],
85
- 'quiet': True,
86
- }
87
-
88
- try:
89
- with yt_dlp.YoutubeDL(ydl_opts) as ydl:
90
- ydl.download([f"https://www.youtube.com/watch?v={id}"])
91
-
92
- if os.path.exists(file_path):
93
- return FileResponse(
94
- path=file_path,
95
- filename=f"{title}.mp3",
96
- media_type='audio/mpeg'
97
- )
98
- except Exception as e:
99
- print(f"Download error: {e}")
100
- raise HTTPException(status_code=500, detail="Download failed")
101
 
102
  if __name__ == "__main__":
103
  import uvicorn
104
- # Port 7860 is mandatory for Hugging Face Spaces
105
  uvicorn.run(app, host="0.0.0.0", port=7860)
 
6
  from fastapi.responses import FileResponse
7
  from ytmusicapi import YTMusic
8
 
9
+ # Initialize with a common browser header to avoid 500 errors in datacenters
10
+ try:
11
+ ytm = YTMusic()
12
+ except Exception as e:
13
+ print(f"Init Error: {e}")
14
+ ytm = None
15
+
16
  app = FastAPI()
 
17
 
 
 
18
  app.add_middleware(
19
  CORSMiddleware,
20
+ allow_origins=["*"],
21
  allow_credentials=False,
22
  allow_methods=["*"],
23
  allow_headers=["*"],
 
25
 
26
  @app.get("/")
27
  async def root():
28
+ return {"status": "Online", "mode": "HuggingFace"}
 
 
 
 
29
 
30
  @app.get("/search")
31
  async def search(q: str):
32
+ if not ytm:
33
+ return {"error": "YTMusic not initialized"}
34
  try:
35
+ # We add a try-except here to catch the specific 500 error
36
  raw_results = ytm.search(q, filter="songs")
37
  results = []
38
  for res in raw_results:
39
  artists = ", ".join([a['name'] for a in res.get('artists', [])])
40
+ thumb = res['thumbnails'][-1]['url'] if res.get('thumbnails') else ""
 
 
 
 
 
41
  results.append({
42
  "id": res['videoId'],
43
  "title": res['title'],
 
46
  })
47
  return results
48
  except Exception as e:
49
+ # This will show the real error in your Hugging Face Logs tab
50
+ print(f"Search Crash: {e}")
51
+ return {"error": str(e), "tip": "Check Hugging Face logs"}
52
 
53
  @app.get("/get_audio")
54
  async def get_audio(id: str):
55
  video_url = f"https://www.youtube.com/watch?v={id}"
56
+ # Adding a 'User-Agent' here helps bypass the 'Sign in to confirm you're not a bot' error
57
  ydl_opts = {
58
  'format': 'bestaudio/best',
59
  'quiet': True,
60
+ 'user_agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
 
61
  }
62
  with yt_dlp.YoutubeDL(ydl_opts) as ydl:
63
  try:
64
  info = ydl.extract_info(video_url, download=False)
 
65
  return {"url": info['url']}
66
  except Exception as e:
67
+ raise HTTPException(status_code=500, detail=str(e))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
 
69
  if __name__ == "__main__":
70
  import uvicorn
 
71
  uvicorn.run(app, host="0.0.0.0", port=7860)