triflix commited on
Commit
1810278
·
verified ·
1 Parent(s): 8856024

Create main.py

Browse files
Files changed (1) hide show
  1. main.py +44 -0
main.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.
10
+ """
11
+ ydl_opts = {
12
+ 'format': 'bestaudio[ext=m4a]/best',
13
+ 'quiet': True,
14
+ 'skip_download': True,
15
+ }
16
+
17
+ try:
18
+ with yt_dlp.YoutubeDL(ydl_opts) as ydl:
19
+ info = ydl.extract_info(video_url, download=False)
20
+
21
+ # Try to find an m4a format URL
22
+ for fmt in info.get('formats', []):
23
+ if fmt.get('ext') == 'm4a' and fmt.get('url'):
24
+ return fmt.get('url')
25
+
26
+ # Fallback to best audio URL if m4a is not found
27
+ return info.get('url') if info.get('url') else None
28
+
29
+ except Exception as e:
30
+ raise HTTPException(status_code=500, detail=f"Failed to extract audio: {str(e)}")
31
+
32
+
33
+ @app.get("/{video_id}")
34
+ def get_audio_url(video_id: str):
35
+ """
36
+ FastAPI endpoint to return the m4a audio stream URL in JSON format.
37
+ """
38
+ youtube_url = f"https://www.youtube.com/watch?v={video_id}"
39
+ m4a_url = get_m4a_url(youtube_url)
40
+
41
+ if not m4a_url:
42
+ raise HTTPException(status_code=404, detail="m4a audio stream not found")
43
+
44
+ return JSONResponse(content={"m4a_url": m4a_url})