PYTR / app.py
sudo-soldier's picture
Update app.py
bfbd8e1 verified
raw
history blame
3.79 kB
import gradio as gr
import yt_dlp
import os
from pydub import AudioSegment
from redis import Redis
import re
import requests
redis = Redis(
host="amused-walleye-31373.upstash.io",
port=31373,
password="67212443600c45ffa962e19ea9202605",
ssl=True,
db=0
)
worker_base_url = "https://server.jessejesse.workers.dev"
os.makedirs("downloads", exist_ok=True)
def sanitize_filename(filename):
"""Sanitize the filename by removing or replacing special characters."""
return re.sub(r'[^a-zA-Z0-9_-]', '_', filename)
def save_ringtone_to_worker(song_name, file_path):
"""Upload the ringtone to Cloudflare Worker storage (R2 or KV) and save its URL in Redis."""
try:
sanitized_song_name = sanitize_filename(song_name)
with open(file_path, 'rb') as file:
file_data = file.read()
response = requests.put(
f"{worker_base_url}/{sanitized_song_name}",
data=file_data,
headers={"Content-Type": "audio/mpeg"}
)
if response.status_code == 200:
file_url = f"{worker_base_url}/{sanitized_song_name}"
redis.set(sanitized_song_name, file_url)
print(f"Saved {sanitized_song_name} URL to Redis: {file_url}")
return file_url
else:
print(f"Failed to upload file. Status code: {response.status_code}")
return None
except Exception as e:
print(f"Error uploading to Worker storage: {e}")
return None
def process_youtube_url(url, uploaded_file):
try:
filename = None
song_name = None
if url:
ydl_opts = {
'format': 'bestaudio/best',
'outtmpl': 'downloads/%(id)s.%(ext)s',
'cookiefile': 'cookies.txt' #cookies
}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info(url, download=True)
filename = os.path.join('downloads', f"{info['id']}.webm")
song_name = info['title']
elif uploaded_file:
filename = uploaded_file.name
song_name = os.path.splitext(uploaded_file.name)[0]
if not filename or not os.path.exists(filename):
return None, None
mp3_filename = f"downloads/{song_name}.mp3"
if not os.path.exists(mp3_filename):
audio = AudioSegment.from_file(filename)
audio.export(mp3_filename, format="mp3")
ringtone_filename_m4r = f"downloads/{song_name}.m4r"
if not os.path.exists(ringtone_filename_m4r):
ringtone_audio = AudioSegment.from_file(mp3_filename)[:20000] # 20 seconds
ringtone_audio.export(ringtone_filename_m4r, format="mp4")
mp3_url = save_ringtone_to_worker(f"{song_name}.mp3", mp3_filename)
m4r_url = save_ringtone_to_worker(f"{song_name}.m4r", ringtone_filename_m4r)
return mp3_url, m4r_url
except Exception as e:
print(f"Error: {e}")
return None, None
# Gradio UI
with gr.Blocks() as interface:
gr.HTML("""
<h1>Python YouTube Ringtones</h1>
<p>Insert a URL to create ringtones or Upload an MP3 to convert.</p>
""")
with gr.Row():
youtube_url = gr.Textbox(label="Enter YouTube URL", placeholder="Paste the URL here...")
mp3_upload = gr.File(label="Upload MP3 (Optional)")
with gr.Row():
mp3_download = gr.File(label="Download Android Ringtone")
iphone_ringtone = gr.File(label="Download iPhone Ringtone")
process_button = gr.Button("Create Ringtones")
process_button.click(process_youtube_url, inputs=[youtube_url, mp3_upload], outputs=[mp3_download, iphone_ringtone])
interface.launch(share=True)