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

""" def extract_embed_url(input_text): """Extracts the Udio embed URL from iframe or raw URL""" match = re.search(r'src=["\'](https://www\.udio\.com/embed/[^"\']+)["\']', input_text) if match: return match.group(1) elif input_text.startswith("https://www.udio.com/embed/"): return input_text.split()[0] else: return None def get_mp3_from_embed(embed_url): messages = [] mp3_url = "" messages.append(f"Fetching embed page: {embed_url}") 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.") 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) r = requests.get(mp3_url) with open(local_path, "wb") as f: f.write(r.content) 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 = extract_embed_url(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("/downloads/") def serve_file(filename): return send_from_directory(DOWNLOAD_FOLDER, filename) if __name__ == "__main__": app.run(debug=True)