Spaces:
Running
Running
File size: 2,313 Bytes
253a78c fc7b4a9 253a78c fc7b4a9 87d96e9 fc7b4a9 253a78c 87d96e9 253a78c |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
import io
import tempfile
import os
import yaml
import yt_dlp
from fastapi import HTTPException
from pathlib import Path
from yt_dlp.utils import DownloadError
def load_server_config():
"""
Load server configs from YAML file.
"""
# Define path first
config_path = Path(__file__).parent.parent / "config" / "server_config.yml"
if not config_path.exists():
raise FileNotFoundError(f"Configuration file not found: {config_path}")
with open(config_path, "r") as file:
return yaml.safe_load(file)
def load_model_config():
"""
Load model configs from YAML file.
"""
config_path = Path(__file__).parent.parent / "config" / "model_config.yml"
if not config_path.exists():
raise FileNotFoundError(f"Configuration file not found : {config_path}")
with open(config_path, "r") as file:
return yaml.safe_load(file)
def download_youtube_audio(youtube_url: str) -> bytes:
"""
Download audio from YouTube URL and return as bytes.
"""
try:
# Create a temporary directory for download
with tempfile.TemporaryDirectory() as temp_dir:
output_path = os.path.join(temp_dir, "audio.mp3")
# yt-dlp options for best audio quality
ydl_opts = {
"format": "bestaudio/best",
"postprocessors": [
{
"key": "FFmpegExtractAudio",
"preferredcodec": "mp3",
"preferredquality": "192",
}
],
"outtmpl": output_path.replace(".mp3", ""),
"quiet": True,
"no_warnings": True,
}
# Download the audio
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
ydl.download([youtube_url])
# Read the downloaded file
with open(output_path, "rb") as file:
audio_content = file.read()
return audio_content
except DownloadError as e:
raise HTTPException(
status_code=400, detail=f"Failed to download YouTube video: {str(e)}"
)
except Exception as e:
raise HTTPException(
status_code=500, detail=f"Error processing YouTube URL {str(e)}"
)
|