triflix commited on
Commit
12b9855
·
verified ·
1 Parent(s): 65feaf1

Create main.py

Browse files
Files changed (1) hide show
  1. main.py +50 -0
main.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, HTTPException
2
+ from fastapi.responses import JSONResponse
3
+ import yt_dlp
4
+
5
+ app = FastAPI()
6
+
7
+ def get_m4a_url(video_url: str) -> str:
8
+ """
9
+ Extracts the best m4a audio stream URL from a YouTube video using yt_dlp with cookies.
10
+ """
11
+ ydl_opts = {
12
+ 'format': 'bestaudio[ext=m4a]/best', # Prefer m4a audio
13
+ 'quiet': True, # Suppress console output
14
+ 'skip_download': True, # Don't download, just extract info
15
+ 'cookies': 'cookies.txt', # Use manually exported cookies
16
+ 'user_agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36', # Mimic a browser
17
+ }
18
+
19
+ try:
20
+ with yt_dlp.YoutubeDL(ydl_opts) as ydl:
21
+ info = ydl.extract_info(video_url, download=False)
22
+
23
+ # Try to find an m4a format URL
24
+ for fmt in info.get('formats', []):
25
+ if fmt.get('ext') == 'm4a' and fmt.get('url'):
26
+ return fmt.get('url')
27
+
28
+ # Fallback to best audio URL if m4a is not found
29
+ return info.get('url') if info.get('url') else None
30
+
31
+ except Exception as e:
32
+ raise HTTPException(status_code=500, detail=f"Failed to extract audio: {str(e)}")
33
+
34
+ @app.get("/{video_id}")
35
+ def get_audio_url(video_id: str):
36
+ """
37
+ FastAPI endpoint to return the m4a audio stream URL in JSON format.
38
+ """
39
+ youtube_url = f"https://www.youtube.com/watch?v={video_id}"
40
+ m4a_url = get_m4a_url(youtube_url)
41
+
42
+ if not m4a_url:
43
+ raise HTTPException(status_code=404, detail="m4a audio stream not found")
44
+
45
+ return JSONResponse(content={"m4a_url": m4a_url})
46
+
47
+ if __name__ == "__main__":
48
+ import uvicorn
49
+ # Run on port 7860
50
+ uvicorn.run(app, host="0.0.0.0", port=7860)