Spaces:
Sleeping
Sleeping
Saqib
commited on
Update modules/app.py
Browse files- modules/app.py +19 -9
modules/app.py
CHANGED
|
@@ -1,6 +1,7 @@
|
|
| 1 |
from fastapi import FastAPI, HTTPException, Request, Depends
|
| 2 |
-
from fastapi.
|
| 3 |
from pytube import YouTube
|
|
|
|
| 4 |
import logging
|
| 5 |
import aiohttp
|
| 6 |
import base64
|
|
@@ -32,6 +33,13 @@ def generate_hash(length=12):
|
|
| 32 |
async def read_root():
|
| 33 |
return {"message": "Saqib's API"}
|
| 34 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
@app.get("/get_audio")
|
| 36 |
async def get_audio(url: str):
|
| 37 |
if not url:
|
|
@@ -40,19 +48,21 @@ async def get_audio(url: str):
|
|
| 40 |
try:
|
| 41 |
yt = YouTube(url)
|
| 42 |
video = yt.streams.filter(only_audio=True).first()
|
| 43 |
-
|
| 44 |
-
#
|
| 45 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
|
| 47 |
file_stats = os.stat(out_file)
|
| 48 |
logging.info(f'Size of audio file in Bytes: {file_stats.st_size}')
|
| 49 |
|
| 50 |
if file_stats.st_size <= 30000000:
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
return FileResponse(new_file, media_type="audio/mpeg", filename="audio.mp3")
|
| 56 |
else:
|
| 57 |
os.remove(out_file)
|
| 58 |
raise HTTPException(status_code=413, detail="Audio file is too large. Limited to about 1.5 hours.")
|
|
|
|
| 1 |
from fastapi import FastAPI, HTTPException, Request, Depends
|
| 2 |
+
from fastapi.staticfiles import StaticFiles
|
| 3 |
from pytube import YouTube
|
| 4 |
+
import uuid
|
| 5 |
import logging
|
| 6 |
import aiohttp
|
| 7 |
import base64
|
|
|
|
| 33 |
async def read_root():
|
| 34 |
return {"message": "Saqib's API"}
|
| 35 |
|
| 36 |
+
# Create a directory to store MP3 files if it doesn't exist
|
| 37 |
+
AUDIO_DIR = "audio_files"
|
| 38 |
+
os.makedirs(AUDIO_DIR, exist_ok=True)
|
| 39 |
+
|
| 40 |
+
# Mount the audio directory
|
| 41 |
+
app.mount("/audio", StaticFiles(directory=AUDIO_DIR), name="audio")
|
| 42 |
+
|
| 43 |
@app.get("/get_audio")
|
| 44 |
async def get_audio(url: str):
|
| 45 |
if not url:
|
|
|
|
| 48 |
try:
|
| 49 |
yt = YouTube(url)
|
| 50 |
video = yt.streams.filter(only_audio=True).first()
|
| 51 |
+
|
| 52 |
+
# Generate a unique filename
|
| 53 |
+
unique_filename = f"{uuid.uuid4().hex}.mp3"
|
| 54 |
+
out_file = os.path.join(AUDIO_DIR, unique_filename)
|
| 55 |
+
|
| 56 |
+
# Download the audio
|
| 57 |
+
video.download(output_path=AUDIO_DIR, filename=unique_filename)
|
| 58 |
|
| 59 |
file_stats = os.stat(out_file)
|
| 60 |
logging.info(f'Size of audio file in Bytes: {file_stats.st_size}')
|
| 61 |
|
| 62 |
if file_stats.st_size <= 30000000:
|
| 63 |
+
# Construct the URL for the MP3 file
|
| 64 |
+
mp3_url = f"/audio/{unique_filename}"
|
| 65 |
+
return {"mp3_url": mp3_url}
|
|
|
|
|
|
|
| 66 |
else:
|
| 67 |
os.remove(out_file)
|
| 68 |
raise HTTPException(status_code=413, detail="Audio file is too large. Limited to about 1.5 hours.")
|