from flask import Flask, request, render_template_string, send_from_directory
import requests, os, re, glob, uuid
from mutagen.easyid3 import EasyID3
app = Flask(__name__)
DOWNLOAD_FOLDER = "downloads"
os.makedirs(DOWNLOAD_FOLDER, exist_ok=True)
MAX_FILES = 20
TEMPLATE = """
Udio Library
Udio Music Library
{% for song in songs %}
-
{{ song.title }}
{% endfor %}
Drag & Drop MP3 files here to upload
"""
def normalize_udio_input(input_text):
"""Accept song page URL, embed URL, or iframe snippet, return embed URL"""
match = re.search(r'src=["\'](https://www\.udio\.com/embed/[^"\']+)["\']', input_text)
if match:
return match.group(1)
if input_text.startswith("https://www.udio.com/embed/"):
return input_text.split()[0]
song_match = re.search(r'https://www\.udio\.com/songs/([A-Za-z0-9]+)', input_text)
if song_match:
song_id = song_match.group(1)
return f"https://www.udio.com/embed/{song_id}"
return None
def get_mp3_from_embed(embed_url):
messages = []
mp3_url = ""
messages.append(f"Fetching embed page: {embed_url}")
try:
r = requests.get(embed_url)
html = r.text
mp3_match = re.search(r'https://storage\.googleapis\.com/.*?\.mp3', html)
if mp3_match:
mp3_url = mp3_match.group(0)
messages.append(f"Found MP3 URL: {mp3_url}")
else:
messages.append("MP3 URL not found in embed page.")
except Exception as e:
messages.append(f"Error fetching embed page: {e}")
return messages, mp3_url
def download_mp3(mp3_url):
ext = ".mp3"
unique_name = f"{uuid.uuid4()}{ext}"
local_path = os.path.join(DOWNLOAD_FOLDER, unique_name)
try:
r = requests.get(mp3_url)
with open(local_path, "wb") as f:
f.write(r.content)
except Exception:
return None
return f"/downloads/{unique_name}"
def list_songs():
songs = []
for f in sorted(os.listdir(DOWNLOAD_FOLDER)):
if f.lower().endswith(".mp3"):
path = os.path.join(DOWNLOAD_FOLDER, f)
title = f
try:
audio = EasyID3(path)
if 'title' in audio:
title = audio['title'][0]
except:
pass
songs.append({"title": title, "url": f"/downloads/{f}"})
return songs
def cleanup_old_files():
files = sorted(glob.glob(os.path.join(DOWNLOAD_FOLDER, "*.mp3")), key=os.path.getmtime)
while len(files) > MAX_FILES:
os.remove(files[0])
files.pop(0)
@app.route("/", methods=["GET", "POST"])
def index():
messages = []
if request.method == "POST":
user_input = request.form.get("embed_url")
if user_input:
embed_url = normalize_udio_input(user_input)
if embed_url:
msg, mp3_url = get_mp3_from_embed(embed_url)
messages.extend(msg)
if mp3_url:
download_mp3(mp3_url)
messages.append("Downloaded new MP3.")
cleanup_old_files()
else:
messages.append("Could not extract embed URL from input.")
songs = list_songs()
return render_template_string(TEMPLATE, messages=messages, songs=songs)
@app.route("/uploads/")
def serve_file(filename):
return send_from_directory(DOWNLOAD_FOLDER, filename)
@app.route("/upload", methods=["POST"])
def upload_file():
file = request.files.get("file")
if file and file.filename.endswith(".mp3"):
ext = ".mp3"
unique_name = f"{uuid.uuid4()}{ext}"
file.save(os.path.join(DOWNLOAD_FOLDER, unique_name))
cleanup_old_files()
return "", 204
@app.route("/downloads/")
def serve_download(filename):
return send_from_directory(DOWNLOAD_FOLDER, filename)
if __name__ == "__main__":
app.run(debug=True)