from flask import Flask, request, send_file, jsonify from pydub import AudioSegment, effects import numpy as np import requests import io import os app = Flask(__name__) @app.route("/result") def process_song(): url = request.args.get("song") if not url: return jsonify({"error": "Please provide a song link with ?song="}) try: # --- Download audio --- headers = {"User-Agent": "Mozilla/5.0"} resp = requests.get( url, stream=True, headers=headers, allow_redirects=True, timeout=30 ) resp.raise_for_status() # Buffer to BytesIO data = io.BytesIO() for chunk in resp.iter_content(chunk_size=1024 * 1024): if chunk: data.write(chunk) data.seek(0) # --- Detect format from URL extension --- ext = os.path.splitext(url.split("?")[0])[-1].lstrip(".").lower() fmt = ext if ext in ["mp3", "wav", "flac", "ogg", "m4a"] else None # --- Load with auto-detect --- try: sound = AudioSegment.from_file(data, format=fmt) except Exception: data.seek(0) # retry without forcing format sound = AudioSegment.from_file(data) # --- Normalize --- sound = effects.normalize(sound) # --- Split channels --- left, right = sound.split_to_mono() output = AudioSegment.silent(duration=len(sound), frame_rate=sound.frame_rate) # --- Pan & effect settings --- chunk_ms = 10 pan_period = 6.0 base_depth = 0.7 depth_variation = 0.2 reverb_delay = 80 steps = len(sound) // chunk_ms for i in range(steps): t = (i * chunk_ms) / 1000.0 ratio = (np.sin(2 * np.pi * t / pan_period) + 1) / 2 depth = base_depth + depth_variation * np.sin(2 * np.pi * t / (pan_period * 2)) left_gain = (1 - depth * ratio) * -3 right_gain = (depth * ratio) * -3 left_chunk = left[i * chunk_ms:(i + 1) * chunk_ms] + left_gain right_chunk = right[i * chunk_ms:(i + 1) * chunk_ms] + right_gain stereo_chunk = AudioSegment.from_mono_audiosegments(left_chunk, right_chunk) output += stereo_chunk # --- Stereo widening --- widened = output.overlay(output.pan(-0.5), gain_during_overlay=-6) widened = widened.overlay(output.pan(0.5), gain_during_overlay=-6) # --- Subtle reverb --- reverb = widened.overlay(widened - 8, delay=reverb_delay) reverb = reverb.overlay(widened - 14, delay=reverb_delay * 2) # --- Final mastering --- final = effects.normalize(reverb) # --- Export to memory --- buf = io.BytesIO() final.export(buf, format="mp3") buf.seek(0) return send_file( buf, mimetype="audio/mpeg", as_attachment=True, download_name="panned_heavenly.mp3" ) except Exception as e: return jsonify({"error": str(e)}), 500 if __name__ == "__main__": app.run(host="0.0.0.0", port=7860)