gimhan commited on
Commit
0da53ab
·
verified ·
1 Parent(s): ac05aea

Create main.py

Browse files
Files changed (1) hide show
  1. main.py +65 -0
main.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import uuid
3
+ from fastapi import FastAPI, BackgroundTasks, HTTPException
4
+ from fastapi.responses import FileResponse
5
+ import yt_dlp
6
+
7
+ app = FastAPI()
8
+
9
+ # Cookies ෆයිල් එක තියෙන තැන
10
+ COOKIES_FILE = "cookies.txt"
11
+
12
+ def cleanup_file(path: str):
13
+ """ෆයිල් එක යැව්වට පස්සේ මකලා දානවා (Space එක පිරෙන්නේ නැති වෙන්න)"""
14
+ if os.path.exists(path):
15
+ os.remove(path)
16
+
17
+ @app.get("/")
18
+ def home():
19
+ return {"status": "Alive", "message": "Music Downloader API is Running! 🚀"}
20
+
21
+ @app.get("/download")
22
+ async def download_song(url: str, background_tasks: BackgroundTasks):
23
+ """
24
+ Koyeb එකෙන් URL එක එව්වම සින්දුව බාලා දෙන Function එක
25
+ """
26
+ try:
27
+ # තාවකාලික ෆයිල් නමක් හදාගන්නවා
28
+ file_id = str(uuid.uuid4())
29
+ filename_template = f"{file_id}.%(ext)s"
30
+
31
+ ydl_opts = {
32
+ 'format': 'bestaudio/best',
33
+ 'outtmpl': filename_template,
34
+ 'postprocessors': [{
35
+ 'key': 'FFmpegExtractAudio',
36
+ 'preferredcodec': 'mp3',
37
+ 'preferredquality': '192',
38
+ }],
39
+ 'quiet': True,
40
+ 'no_warnings': True,
41
+ # Cookies ෆයිල් එක අනිවාර්යයෙන්ම ඕනේ
42
+ 'cookiefile': COOKIES_FILE if os.path.exists(COOKIES_FILE) else None,
43
+ # YouTube එකට බොරු කියනවා අපි Browser එකක් කියලා
44
+ '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',
45
+ }
46
+
47
+ with yt_dlp.YoutubeDL(ydl_opts) as ydl:
48
+ ydl.download([url])
49
+
50
+ # ඩවුන්ලෝඩ් වුන MP3 එකේ නම
51
+ mp3_file = f"{file_id}.mp3"
52
+
53
+ if not os.path.exists(mp3_file):
54
+ raise HTTPException(status_code=500, detail="Download failed internally.")
55
+
56
+ # ෆයිල් එක යවනවා (යැව්වට පස්සේ මකන්න කියලා Task එකක් දෙනවා)
57
+ return FileResponse(
58
+ mp3_file,
59
+ media_type="audio/mpeg",
60
+ filename="song.mp3",
61
+ background=background_tasks.add_task(cleanup_file, mp3_file)
62
+ )
63
+
64
+ except Exception as e:
65
+ return {"error": str(e)}