Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584import gradio as grimport soundfile as sfimport numpy as npimport osfrom scipy.signal import lfilter, resample_polyfrom pedalboard import (Pedalboard,Compressor,Limiter,Gain,HighShelfFilter,LowShelfFilter,PeakFilter,Reverb)# ===================================================# 6HD SPATIAL & ENTROPY MODULES# ===================================================def spatial_6hd(audio):"""Restores the 6HD Spatial Fieldwith high-definition stereo width."""mid = (audio[:, 0] + audio[:, 1]) * 0.5side = (audio[:, 0] - audio[:, 1]) * 0.5width_motion = np.random.normal(1.15,0.01,len(side))width_motion = np.convolve(width_motion,np.ones(8000) / 8000,mode='same')side *= width_motionleft = mid + sideright = mid - sidereturn np.clip(np.column_stack((left, right)),-1.0,1.0)def inject_6hd_entropy(audio, sr):"""Injects organic human entropy while preservinghigh-end clarity and avoiding metallic artifacts."""n_samples = len(audio)# ---------------------------------------------------# TEMPORAL MICRO-JITTER# ---------------------------------------------------t_jitter = np.cumsum(np.random.normal(0,0.0000008,n_samples))indices = np.clip(np.arange(n_samples) + t_jitter * sr,0,n_samples - 1).astype(np.intp)audio = audio[indices]# ---------------------------------------------------# ORGANIC SPECTRAL DRIFT# ---------------------------------------------------s_drift = np.random.normal(1.0,0.0004,len(audio))b, a = [1.0], [1.0, -0.9998]s_drift = lfilter(b, a, s_drift)audio[:, 0] *= (1.0 + 0.0004 * s_drift)audio[:, 1] *= (1.0 - 0.0004 * s_drift)return np.clip(audio, -1.0, 1.0)# ===================================================# 6HD CORE COMPONENTS# ===================================================def normalize(audio):peak = np.max(np.abs(audio))return audio / peak if peak > 0 else audiodef analog_6hd(audio):"""Soft analog saturation."""return np.tanh(audio * 1.012)def transient_evolution(audio):"""Adds subtle punch and transient life."""transient = np.diff(audio,axis=0,prepend=audio[:1])audio += transient * 0.025return np.clip(audio, -1.0, 1.0)# ===================================================# COMMERCIAL CLARITY LAYER# ===================================================def commercial_clarity_layer(audio):"""Adds commercial streaming polishwithout damaging the original mix."""# ---------------------------------------------------# AIR LAYER# ---------------------------------------------------air = np.mean(audio,axis=1,keepdims=True) * 0.012audio[:, 0] += air[:, 0]audio[:, 1] += air[:, 0]# ---------------------------------------------------# MICRO STEREO ENHANCEMENT# ---------------------------------------------------stereo_phase = (np.sin(np.linspace(0,np.pi * 2,len(audio))) * 0.002)audio[:, 0] *= (1.0 + stereo_phase)audio[:, 1] *= (1.0 - stereo_phase)return np.clip(audio, -1.0, 1.0)# ===================================================# STREAMING SAFE FINALIZATION# ===================================================def streaming_safe_finalize(audio):"""Prevents harsh codec distortionafter AAC / Spotify transcoding."""# ---------------------------------------------------# TRUE PEAK STYLE SAFETY# ---------------------------------------------------audio = np.tanh(audio * 0.995)# ---------------------------------------------------# LIGHT DITHERING# ---------------------------------------------------dither = np.random.normal(0,1e-5,audio.shape)audio += ditherreturn np.clip(audio, -1.0, 1.0)# ===================================================# 6HD COMMERCIAL DELIVERY ENGINE# ===================================================def commercial_streaming_finalize(audio, sr):"""Commercial-grade streaming preparation layer.Optimized for:SpotifyApple MusicTidalFLACAACALAC"""# ---------------------------------------------------# ULTRA-HIGH RESOLUTION OVERSAMPLING# ---------------------------------------------------oversampled = resample_poly(audio,2,1,axis=0)# ---------------------------------------------------# MICRO AIR EXCITER# ---------------------------------------------------air = np.diff(oversampled,axis=0,prepend=oversampled[:1]) * 0.0035oversampled += air# ---------------------------------------------------# STREAMING TRANSIENT PRESERVER# ---------------------------------------------------transient = np.diff(oversampled,axis=0,prepend=oversampled[:1])oversampled += transient * 0.008# ---------------------------------------------------# TRUE PEAK PROTECTION# ---------------------------------------------------oversampled = np.tanh(oversampled * 0.985)# ---------------------------------------------------# DOWN SAMPLE BACK# ---------------------------------------------------finalized = resample_poly(oversampled,1,2,axis=0)# ---------------------------------------------------# ANALOG HUMAN NOISE FLOOR# ---------------------------------------------------analog_noise = np.random.normal(0,0.000003,finalized.shape)finalized += analog_noise# ---------------------------------------------------# FINAL CLIP PROTECTION# ---------------------------------------------------finalized = np.clip(finalized,-1.0,1.0)return finalized# ===================================================# MASTER 6HD ENGINE# ===================================================def adaptive_6hd_master(audio_path,style,lufs_target,auto_glass):if not audio_path:return Noneaudio, sr = sf.read(audio_path)# ---------------------------------------------------# MONO TO STEREO FIX# ---------------------------------------------------if len(audio.shape) == 1:audio = np.column_stack([audio,audio])elif audio.shape[1] == 2:if np.max(np.abs(audio[:, 1])) == 0:audio[:, 1] = audio[:, 0]audio = audio.astype(np.float32)# ===================================================# CORE PROCESSING# ===================================================audio = normalize(audio)audio = spatial_6hd(audio)audio = transient_evolution(audio)audio = inject_6hd_entropy(audio, sr)audio = analog_6hd(audio)audio = commercial_clarity_layer(audio)# ===================================================# PRESET MAP# ===================================================eq_gains = {"Universal": {"low": 1.2,"mid": 0.5,"high": 2.0,"gain": 4.0},"Cinematic": {"low": 1.8,"mid": 0.2,"high": 1.5,"gain": 3.5},"Spatial": {"low": 1.0,"mid": 0.8,"high": 2.5,"gain": 4.2},"Slam": {"low": 2.2,"mid": 0.4,"high": 1.0,"gain": 4.8},"Stumper": {"low": 1.5,"mid": 0.6,"high": 1.8,"gain": 4.0},"Clarity HD": {"low": 0.8,"mid": 0.3,"high": 3.0,"gain": 3.8}}cfg = eq_gains.get(style,eq_gains["Universal"])# ===================================================# STREAMING TARGETS# ===================================================lufs_shift = float(-14.0 - lufs_target)final_gain = cfg["gain"] + lufs_shiftlimiter_ceiling = -1.0 if auto_glass else -0.8# ===================================================# MASTERING BOARD# ===================================================board = Pedalboard([LowShelfFilter(cutoff_frequency_hz=90,gain_db=cfg["low"]),PeakFilter(cutoff_frequency_hz=2500,gain_db=cfg["mid"],q=0.7),HighShelfFilter(cutoff_frequency_hz=14000,gain_db=cfg["high"]),Compressor(threshold_db=-16,ratio=1.5,attack_ms=50,release_ms=250),Reverb(room_size=0.08,damping=0.9,wet_level=0.015,width=1.0),Gain(gain_db=final_gain),Limiter(threshold_db=limiter_ceiling)])# ===================================================# APPLY BOARD# ===================================================processed = board(audio, sr)# ===================================================# FINAL COMMERCIAL DELIVERY STAGES# ===================================================processed = streaming_safe_finalize(processed)processed = commercial_streaming_finalize(processed,sr)processed = normalize(processed)# ===================================================# OUTPUT FILE# ===================================================base_name = "".join([c for c in os.path.splitext(os.path.basename(audio_path))[0]if c.isalnum() or c in ('_', '-')])if not base_name:base_name = "UCDM_Track"output_path = f"{base_name}_Master6HD.wav"# ===================================================# EXPORT# ===================================================sf.write(output_path,processed,sr,subtype='PCM_24')return output_path# ===================================================# GRADIO UI# ===================================================with gr.Blocks(theme=gr.themes.Soft()) as app:gr.Markdown("# HumanNaturalMaster: Ultra-6HD Commercial Engine")with gr.Row():input_audio = gr.Audio(label="Upload UCDM Track",type="filepath")with gr.Row():style = gr.Radio(["Universal","Cinematic","Spatial","Slam","Stumper","Clarity HD"],value="Universal",label="Master Style Profile")with gr.Row():lufs_target = gr.Slider(minimum=-20,maximum=-6,value=-14,step=1,label="Loudness Target (LUFS)")auto_glass = gr.Checkbox(value=True,label="Auto-Glass (Apple/Spotify Streaming Optimization)")process_btn = gr.Button("GENERATE 6HD HUMAN MASTER",variant="primary")output_audio = gr.Audio(label="6HD Commercial Output",type="filepath")process_btn.click(fn=adaptive_6hd_master,inputs=[input_audio,style,lufs_target,auto_glass],outputs=output_audio)# ===================================================# LAUNCH# ===================================================if __name__ == "__main__":app.launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277import gradio as grimport osimport jsonimport shutilfrom datetime import datetime# ============================================================ ## CONFIG# ============================================================ #APP_TITLE = "Benny Agosto Music Store"CATALOG_FILE = "catalog.json"USER_DB_FILE = "users.json"TRACKS_FOLDER = "tracks"VAULT_FOLDER = "vault"IMAGES_FOLDER = "images"for f in [TRACKS_FOLDER, VAULT_FOLDER, IMAGES_FOLDER]:os.makedirs(f, exist_ok=True)# ============================================================ ## DEFAULT DATA# ============================================================ #DEFAULT_CATALOG = {"admin_username": "admin","admin_password": "change-this-password","album_title": "Divine Retribution (Reference Edition)","artist": "Benny Agosto","album_price": "$12.99","cover_art": "","stripe_payment_link": "https://buy.stripe.com/aFaaEW2Hd9z317fcb73ZK01","download_access_code": "BAM2026","full_album_zip": "vault/full.zip",# FIXED VIDEO (YOUR LINK)"featured_video_url": "https://www.youtube.com/embed/yDCZgLzxcx8","tracks": [{"id": "t1","title": "TΓΊ Cuerpo Protegido Rompiendo Cadenas","price": "$1.29","file": "tracks/track1.mp3"}]}# ============================================================ ## FILE SYSTEM# ============================================================ #def load_catalog():if not os.path.exists(CATALOG_FILE):save_catalog(DEFAULT_CATALOG.copy())return DEFAULT_CATALOG.copy()with open(CATALOG_FILE, "r", encoding="utf-8") as f:data = json.load(f)for k, v in DEFAULT_CATALOG.items():data.setdefault(k, v)return datadef save_catalog(c):with open(CATALOG_FILE, "w", encoding="utf-8") as f:json.dump(c, f, indent=4, ensure_ascii=False)def load_users():if not os.path.exists(USER_DB_FILE):save_users({})return {}with open(USER_DB_FILE, "r", encoding="utf-8") as f:return json.load(f)def save_users(u):with open(USER_DB_FILE, "w", encoding="utf-8") as f:json.dump(u, f, indent=4, ensure_ascii=False)# ============================================================ ## HELPERS# ============================================================ #def yt_embed(url):if not url:return ""if "watch?v=" in url:url = url.replace("watch?v=", "embed/")if "youtu.be/" in url:url = url.replace("youtu.be/", "www.youtube.com/embed/")return url.split("&")[0]def get_choices():c = load_catalog()return [f"πΏ Γlbum Completo β {c['album_price']}"] + [f"π΅ {t['title']} β {t['price']}" for t in c["tracks"]]# ============================================================ ## STORE VIEW (SAFE β NO gr.update inside logic)# ============================================================ #def load_store():c = load_catalog()cover = c.get("cover_art", "")cover_ok = cover and os.path.exists(cover)cover_html = f"<img src='/file={cover}' style='max-width:300px;border-radius:12px'>" if cover_ok else ""video_html = f"""<iframe width="100%" height="320"src="{yt_embed(c['featured_video_url'])}"frameborder="0" allowfullscreen></iframe>"""info = f"""### πΏ {c['album_title']}**Artista:** {c['artist']}**Precio:** {c['album_price']}"""return cover_html, info, get_choices(), video_html# ============================================================ ## USERS# ============================================================ #def register(u, p):if not u or not p:return "β οΈ incomplete"users = load_users()if u in users:return "β exists"users[u] = {"password": p, "history": []}save_users(users)return "β created"def login(u, p):users = load_users()if u not in users:return "β not found", "", ""if users[u]["password"] != p:return "β wrong password", "", ""hist = users[u]["history"]txt = "\n".join(hist) if hist else "No purchases"return f"β {u}", txt, u# ============================================================ ## ADMIN# ============================================================ #def admin_login(u, p):c = load_catalog()if u == c["admin_username"] and p == c["admin_password"]:return ("β admin ok",True,c["album_title"],c["artist"],c["album_price"],c["stripe_payment_link"],c["download_access_code"],c["featured_video_url"],[t["title"] for t in c["tracks"]])return ("β denied", False, "", "", "", "", "", "", [])def save_settings(title, artist, price, stripe, code, video):c = load_catalog()if title: c["album_title"] = titleif artist: c["artist"] = artistif price: c["album_price"] = priceif stripe: c["stripe_payment_link"] = stripeif code: c["download_access_code"] = codeif video: c["featured_video_url"] = videosave_catalog(c)return "β saved", *load_store()# ============================================================ ## UI# ============================================================ #with gr.Blocks(title=APP_TITLE) as app:gr.Markdown("# π΅ Benny Agosto Music Store")# STOREcover = gr.HTML()info = gr.Markdown()dropdown = gr.Dropdown()video = gr.HTML()app.load(load_store, outputs=[cover, info, dropdown, video])# LOGINwith gr.Tab("Login"):u = gr.Textbox(label="User")p = gr.Textbox(label="Pass", type="password")btn = gr.Button("Login")status = gr.Textbox()profile = gr.Markdown()state = gr.Textbox()btn.click(login, [u, p], [status, profile, state])# REGISTERwith gr.Tab("Register"):ru = gr.Textbox()rp = gr.Textbox(type="password")rb = gr.Button("Create")rs = gr.Textbox()rb.click(register, [ru, rp], rs)# ADMINwith gr.Tab("Admin"):au = gr.Textbox()ap = gr.Textbox(type="password")ab = gr.Button("Login")msg = gr.Textbox()panel = gr.Column(visible=False)with panel:t = gr.Textbox()a = gr.Textbox()pr = gr.Textbox()st = gr.Textbox()cd = gr.Textbox()vd = gr.Textbox()ab.click(admin_login,[au, ap],[msg, panel, t, a, pr, st, cd, vd, dropdown])save_btn = gr.Button("Save")save_msg = gr.Textbox()save_btn.click(save_settings,[t, a, pr, st, cd, vd],[save_msg, cover, info, dropdown, video])# ============================================================ ## LAUNCH (HF SAFE)# ============================================================ #if __name__ == "__main__":app.launch()
app.py+207-514