kumar-aditya commited on
Commit
495a399
·
verified ·
1 Parent(s): 7754a82

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +22 -36
main.py CHANGED
@@ -1,39 +1,32 @@
1
  from fastapi import FastAPI, HTTPException, BackgroundTasks
2
  from fastapi.responses import FileResponse
 
3
  import yt_dlp
4
- import os
5
- import glob
6
  import uuid
 
7
 
8
  app = FastAPI()
9
-
10
- # Create a temporary directory for downloads
11
  DOWNLOAD_DIR = "/app/downloads"
12
  os.makedirs(DOWNLOAD_DIR, exist_ok=True)
13
 
 
 
 
 
14
  def cleanup_file(path: str):
15
- """Deletes the file after it has been sent."""
16
  if os.path.exists(path):
17
  os.remove(path)
18
 
19
- @app.get("/download-mp3")
20
- async def download_mp3(url: str, background_tasks: BackgroundTasks):
21
- """
22
- Downloads YouTube audio, converts to MP3, and returns the file.
23
- """
24
-
25
- # Generate a unique filename to prevent conflicts between users
26
  unique_id = str(uuid.uuid4())
27
 
 
28
  ydl_opts = {
29
  'format': 'bestaudio/best',
30
  'outtmpl': f'{DOWNLOAD_DIR}/{unique_id}.%(ext)s',
31
  'quiet': True,
32
- 'no_warnings': True,
33
- # COOKIES ARE STILL REQUIRED!
34
- 'cookiefile': 'cookies.txt',
35
-
36
- # POST-PROCESSOR: Convert to MP3
37
  'postprocessors': [{
38
  'key': 'FFmpegExtractAudio',
39
  'preferredcodec': 'mp3',
@@ -42,33 +35,26 @@ async def download_mp3(url: str, background_tasks: BackgroundTasks):
42
  }
43
 
44
  try:
45
- # Run download
46
  with yt_dlp.YoutubeDL(ydl_opts) as ydl:
47
- ydl.download([url])
 
 
 
48
 
49
- # The file will be named {unique_id}.mp3
50
- file_path = f"{DOWNLOAD_DIR}/{unique_id}.mp3"
51
-
52
- if not os.path.exists(file_path):
53
- raise HTTPException(status_code=500, detail="Conversion failed.")
54
 
55
- # Get the actual title for the filename the user sees
56
- info = ydl.extract_info(url, download=False)
57
- display_name = f"{info.get('title', 'audio')}.mp3"
58
 
59
- # Clean filename (remove special chars that break headers)
60
- display_name = "".join(c for c in display_name if c.isalnum() or c in (' ', '.', '-', '_')).strip()
61
-
62
  return FileResponse(
63
  path=file_path,
64
- filename=display_name,
65
  media_type='audio/mpeg',
66
- headers={'Content-Disposition': f'attachment; filename="{display_name}"'},
 
67
  background=background_tasks.add_task(cleanup_file, file_path)
68
  )
69
 
70
  except Exception as e:
71
- # cleanup if something failed
72
- if os.path.exists(f"{DOWNLOAD_DIR}/{unique_id}.mp3"):
73
- os.remove(f"{DOWNLOAD_DIR}/{unique_id}.mp3")
74
- raise HTTPException(status_code=400, detail=str(e))
 
1
  from fastapi import FastAPI, HTTPException, BackgroundTasks
2
  from fastapi.responses import FileResponse
3
+ from pydantic import BaseModel
4
  import yt_dlp
 
 
5
  import uuid
6
+ import os
7
 
8
  app = FastAPI()
 
 
9
  DOWNLOAD_DIR = "/app/downloads"
10
  os.makedirs(DOWNLOAD_DIR, exist_ok=True)
11
 
12
+ # 1. Define the Request Body
13
+ class VideoRequest(BaseModel):
14
+ url: str
15
+
16
  def cleanup_file(path: str):
 
17
  if os.path.exists(path):
18
  os.remove(path)
19
 
20
+ @app.post("/convert")
21
+ async def convert_to_mp3(request: VideoRequest, background_tasks: BackgroundTasks):
 
 
 
 
 
22
  unique_id = str(uuid.uuid4())
23
 
24
+ # Configure yt-dlp for Audio
25
  ydl_opts = {
26
  'format': 'bestaudio/best',
27
  'outtmpl': f'{DOWNLOAD_DIR}/{unique_id}.%(ext)s',
28
  'quiet': True,
29
+ 'cookiefile': 'cookies.txt', # REQUIRED
 
 
 
 
30
  'postprocessors': [{
31
  'key': 'FFmpegExtractAudio',
32
  'preferredcodec': 'mp3',
 
35
  }
36
 
37
  try:
 
38
  with yt_dlp.YoutubeDL(ydl_opts) as ydl:
39
+ # Get Info First (for title)
40
+ info = ydl.extract_info(request.url, download=False)
41
+ clean_title = "".join(c for c in info['title'] if c.isalnum() or c in " -_").strip()
42
+ filename = f"{clean_title}.mp3"
43
 
44
+ # Download & Convert
45
+ ydl.download([request.url])
 
 
 
46
 
47
+ file_path = f"{DOWNLOAD_DIR}/{unique_id}.mp3"
 
 
48
 
49
+ # Return the file as a stream
 
 
50
  return FileResponse(
51
  path=file_path,
52
+ filename=filename,
53
  media_type='audio/mpeg',
54
+ # This header tells Android "Here is the filename"
55
+ headers={'Content-Disposition': f'attachment; filename="{filename}"'},
56
  background=background_tasks.add_task(cleanup_file, file_path)
57
  )
58
 
59
  except Exception as e:
60
+ raise HTTPException(status_code=500, detail=str(e))