| 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=<url>"}) |
| |
| try: |
| |
| headers = {"User-Agent": "Mozilla/5.0"} |
| resp = requests.get( |
| url, |
| stream=True, |
| headers=headers, |
| allow_redirects=True, |
| timeout=30 |
| ) |
| resp.raise_for_status() |
|
|
| |
| data = io.BytesIO() |
| for chunk in resp.iter_content(chunk_size=1024 * 1024): |
| if chunk: |
| data.write(chunk) |
| data.seek(0) |
|
|
| |
| ext = os.path.splitext(url.split("?")[0])[-1].lstrip(".").lower() |
| fmt = ext if ext in ["mp3", "wav", "flac", "ogg", "m4a"] else None |
|
|
| |
| try: |
| sound = AudioSegment.from_file(data, format=fmt) |
| except Exception: |
| data.seek(0) |
| sound = AudioSegment.from_file(data) |
|
|
| |
| sound = effects.normalize(sound) |
|
|
| |
| left, right = sound.split_to_mono() |
| output = AudioSegment.silent(duration=len(sound), frame_rate=sound.frame_rate) |
|
|
| |
| 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 |
|
|
| |
| widened = output.overlay(output.pan(-0.5), gain_during_overlay=-6) |
| widened = widened.overlay(output.pan(0.5), gain_during_overlay=-6) |
|
|
| |
| reverb = widened.overlay(widened - 8, delay=reverb_delay) |
| reverb = reverb.overlay(widened - 14, delay=reverb_delay * 2) |
|
|
| |
| final = effects.normalize(reverb) |
|
|
| |
| 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) |