Update app.py
Browse files1234 unmodified lines89101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383import numpy as npfrom PIL import Image, ImageFileimport io4 unmodified linesimport gradio as grfrom typing import List, Tuple, Dict, Any, Optionalimport time# --- CONFIGURACIÓN DE ROBUSTEZ A NIVEL DE PRODUCCIÓN ---warnings.filterwarnings("ignore", category=Image.DecompressionBombWarning)ImageFile.LOAD_TRUNCATED_IMAGES = True# ==============================================================================# ESTÉTICA - TEMA "NEON PULSE" v1.0# Un diseño más dinámico e inmersivo.# ==============================================================================NEON_PULSE_CSS = """@import url('https://fonts.googleapis.com/css2?family=Roboto+Mono:wght@400;700&display=swap');:root {--neon-purple: #be00ff;--neon-cyan: #00f2ff;--dark-bg: #0a0a14;--panel-bg: rgba(20, 16, 38, 0.7);--panel-border: rgba(190, 0, 255, 0.3);--text-color: #e0e0e0;--glow-shadow: 0 0 5px var(--neon-cyan), 0 0 10px var(--neon-cyan), 0 0 20px var(--neon-purple), 0 0 30px var(--neon-purple);}body, .gradio-container {font-family: 'Roboto Mono', monospace;background: var(--dark-bg);background-image: radial-gradient(circle at 1% 1%, var(--neon-purple) 0.5px, transparent 0), radial-gradient(circle at 99% 99%, var(--neon-cyan) 0.5px, transparent 0);color: var(--text-color);}.main-title {text-align: center;font-size: 3.5rem !important;font-weight: 700;text-shadow: var(--glow-shadow);color: white;padding-bottom: 20px;letter-spacing: 4px;animation: flicker 3s infinite alternate;}@keyframes flicker {0%, 18%, 22%, 25%, 53%, 57%, 100% {text-shadow: 0 0 4px #fff, 0 0 11px var(--neon-cyan), 0 0 19px var(--neon-cyan), 0 0 40px var(--neon-purple), 0 0 80px var(--neon-purple), 0 0 90px var(--neon-purple);}20%, 24%, 55% { text-shadow: none; }}.pro-panel {background: var(--panel-bg) !important;border: 1px solid var(--panel-border) !important;border-radius: 16px !important;box-shadow: 0 8px 32px 0 rgba(0, 0, 0, 0.5) !important;backdrop-filter: blur(12px) !important;-webkit-backdrop-filter: blur(12px) !important;padding: 20px !important;transition: box-shadow 0.3s ease;}.pro-panel:hover {box-shadow: 0 0 20px var(--panel-border);}.gr-button {background: linear-gradient(90deg, var(--neon-purple), var(--neon-cyan)) !important;color: white !important;border: none !important;font-weight: bold !important;border-radius: 8px !important;transition: transform 0.2s ease, box-shadow 0.3s ease !important;box-shadow: 0 0 15px rgba(190, 0, 255, 0.5);}.gr-button:hover {transform: scale(1.05) translateY(-2px) !important;box-shadow: 0 0 30px rgba(0, 242, 255, 0.8) !important;}.tabs > .tab-nav > button.selected {background: var(--panel-bg) !important;color: white !important;border-bottom: 3px solid var(--neon-cyan) !important;text-shadow: 0 0 5px var(--neon-cyan);}.gr-slider { color: var(--text-color); }.gr-gallery > .preview > img { border-radius: 10px !important; transition: transform 0.3s ease-in-out !important; border: 1px solid transparent; }.gr-gallery > .preview > img:hover { transform: scale(1.05) !important; border: 1px solid var(--neon-cyan); }#downloads_tab > div > p { font-size: 1.1em; text-align: center; color: var(--neon-cyan); padding: 20px; border: 1px dashed var(--panel-border); border-radius: 8px;}"""# ==============================================================================# NÚCLEO DE FUNCIONES GLITCH - A PRUEBA DE BALAS# Cada función está envuelta en un decorador para máxima estabilidad.# ==============================================================================def safe_effect(func):"""Decorador para hacer cualquier función de efecto robusta contra errores."""def wrapper(img: Image.Image, *args, **kwargs) -> Image.Image:try:# Si la intensidad es 0, se salta el efecto para optimizar rendimiento.intensity = args[0] if args else kwargs.get('intensity', 1.0)if intensity == 0:return img.copy()return func(img, *args, **kwargs)except Exception as e:print(f"ADVERTENCIA: El efecto '{func.__name__}' falló con el error: {e}. Saltando efecto.")return img # Devuelve la imagen original en caso de falloreturn wrapper# --- Implementaciones de efectos (sin cambios, ya eran robustas) ---@safe_effectdef pixel_sorting(img: Image.Image, intensity: float) -> Image.Image:arr = np.array(img)height, _, _ = arr.shapebrightness = np.dot(arr.astype(np.float32), [0.2989, 0.5870, 0.1140])rows_to_process = np.where(np.random.random(height) < intensity)[0]for y in rows_to_process:sorted_indices = np.argsort(brightness[y])arr[y] = arr[y, sorted_indices] if random.random() > 0.5 else arr[y, sorted_indices[::-1]]return Image.fromarray(arr)@safe_effectdef rgb_shift(img: Image.Image, intensity: float) -> Image.Image:arr = np.array(img)max_shift = int(arr.shape[1] * 0.05)shift_x = int(intensity * max_shift * (random.random() * 0.5 + 0.5))shift_y = int(intensity * max_shift * (random.random() * 0.5 + 0.5))channels = list(cv2.split(arr))channels[0] = np.roll(channels[0], shift_x, axis=1)channels[2] = np.roll(channels[2], -shift_x, axis=1)if random.random() < intensity: channels[1] = np.roll(channels[1], shift_y, axis=0)return Image.fromarray(cv2.merge(channels))@safe_effectdef datamosh(img: Image.Image, intensity: float) -> Image.Image:quality = max(1, min(100, int(20 - intensity * 18)))with io.BytesIO() as buffer:img.save(buffer, format='JPEG', quality=quality)data = bytearray(buffer.getvalue())header_size = 623if len(data) > header_size:corruption_amount = int(len(data) * 0.1 * intensity)indices = np.random.randint(header_size, len(data) - 1, size=corruption_amount)for idx in indices: data[idx] = random.randint(0, 255)# Intenta cargar la imagen corrupta, si falla, devuelve la originaltry:new_img = Image.open(io.BytesIO(data))new_img.load()return new_img.convert('RGB') if new_img.mode != 'RGB' else new_imgexcept Exception:return img # Devuelve la imagen original si la corrupción es irrecuperable@safe_effectdef tile_glitch(img: Image.Image, intensity: float, tile_size: int) -> Image.Image:arr = np.array(img)height, width, _ = arr.shapefor y in range(0, height, tile_size):for x in range(0, width, tile_size):if random.random() < intensity:y_end, x_end = min(y + tile_size, height), min(x + tile_size, width)tile = arr[y:y_end, x:x_end]if tile.size == 0: continueif random.random() > 0.5:shift = random.randint(-tile_size // 2, tile_size // 2)arr[y:y_end, x:x_end] = np.roll(tile, shift, axis=1)else:rotations = random.randint(1, 3)# Aseguramos que el tile redimensionado tenga el tamaño correctorotated_tile = np.rot90(tile, rotations)resized_tile = cv2.resize(rotated_tile, (tile.shape[1], tile.shape[0]))arr[y:y_end, x:x_end] = resized_tilereturn Image.fromarray(arr)@safe_effectdef scanline_effect(img: Image.Image, intensity: float) -> Image.Image:arr = np.array(img)height, width, _ = arr.shapeshifts = np.random.randint(-int(width * 0.1 * intensity), int(width * 0.1 * intensity), size=height)step = max(2, int(6 - intensity * 5))mask = (np.arange(height) % step == 0)shifts[~mask] = 0cols = np.arange(width)rolled_cols = (cols - shifts[:, np.newaxis]) % widtharr = arr[np.arange(height)[:, np.newaxis], rolled_cols]return Image.fromarray(arr)# ==============================================================================# PIPELINE DE PROCESAMIENTO CON TRACKING DE PROGRESO# ==============================================================================EFFECT_MAP = {"Pixel Sorting": pixel_sorting, "RGB Shift": rgb_shift,"Datamosh": datamosh, "Tile Glitch": tile_glitch,"Scanline Effect": scanline_effect}def run_glitch_pipeline(image: Optional[Image.Image],seed: int,active_effects: List[str],params: Dict[str, Any],progress: gr.Progress) -> Tuple[Optional[Image.Image], List[Tuple[Image.Image, str]]]:"""Aplica efectos con actualizaciones de progreso detalladas y semilla reproducible."""if image is None:return None, []# Inicializar generadores de números aleatorios para resultados reproduciblesrandom.seed(seed)np.random.seed(seed)if image.mode != 'RGB': image = image.convert('RGB')steps = [(image.copy(), "Original")]current_img = image.copy()# Filtra los efectos que realmente están activos en el mapaeffects_to_run = [fx for fx in active_effects if fx in EFFECT_MAP]total_effects = len(effects_to_run)if total_effects == 0:progress(1, desc="Hecho. Ningún efecto seleccionado.")return current_img, stepsfor i, effect_name in enumerate(effects_to_run):progress((i + 1) / total_effects, desc=f"Procesando: {effect_name} ({i+1}/{total_effects})")func = EFFECT_MAP[effect_name]if effect_name == "Tile Glitch":current_img = func(current_img, intensity=params["tile_glitch_intensity"], tile_size=params["tile_size"])else:param_key = f"{effect_name.lower().replace(' ', '_')}_intensity"current_img = func(current_img, intensity=params[param_key])steps.append((current_img.copy(), effect_name))progress(1, desc="¡Pipeline completado!")return current_img, steps# ==============================================================================# INTERFAZ GRADIO V5 - "NEON PULSE"# ==============================================================================with gr.Blocks(theme=gr.themes.Default(primary_hue="purple", secondary_hue="cyan"), css=NEON_PULSE_CSS) as demo:gr.Markdown("<h1 class='main-title'>G L I T C H C O R E /// VANGUARD</h1>")# Estado compartido para almacenar los pasos del proceso para la descarga finalshared_steps = gr.State([])with gr.Row(equal_height=False):# --- COLUMNA DE CONTROLES ---with gr.Column(scale=1, min_width=350):with gr.Group(elem_classes=["pro-panel"]):gr.Markdown("### 1. Carga tu Realidad")image_input = gr.Image(type="pil", label="📷 SUBIR IMAGEN", height=300)gr.Markdown("### 2. Elige tu Distorsión")active_effects = gr.CheckboxGroup(choices=list(EFFECT_MAP.keys()),value=list(EFFECT_MAP.keys()),label="🎛️ EFECTOS ACTIVOS")with gr.Accordion("🎲 SEMILLA DE ALEATORIEDAD (Para reproducir)", open=False):seed_input = gr.Number(label="Seed", value=42, precision=0)randomize_seed_btn = gr.Button("Generar Nueva Semilla")with gr.Group(elem_classes=["pro-panel"]):gr.Markdown("### 3. Modula los Parámetros")with gr.Accordion("⚙️ AJUSTE FINO DE EFECTOS", open=True):pixel_sorting_intensity = gr.Slider(0, 1, value=0.1, label="Pixel Sorting")rgb_shift_intensity = gr.Slider(0, 1, value=0.2, label="RGB Shift")datamosh_intensity = gr.Slider(0, 1, value=0.25, label="Datamosh")scanline_effect_intensity = gr.Slider(0, 1, value=0.2, label="Scanlines")tile_glitch_intensity = gr.Slider(0, 1, value=0.15, label="Tile Glitch")tile_size = gr.Slider(8, 256, value=64, step=8, label="Tamaño de Tile")# --- COLUMNA DE VISUALIZACIÓN ---with gr.Column(scale=2, min_width=600):with gr.Group(elem_classes=["pro-panel"]):with gr.Tabs() as output_tabs:with gr.TabItem("🖼️ PREVISUALIZACIÓN EN VIVO", id="preview_tab"):final_output = gr.Image(label="Resultado Final", interactive=False, height=550, show_download_button=True)gr.Markdown("_(El resultado se actualiza automáticamente al cambiar los parámetros)_")with gr.TabItem("🎞️ GALERÍA DEL PROCESO", id="gallery_tab"):gallery_output = gr.Gallery(label="Proceso Paso a Paso", columns=3, height=550, object_fit="contain")gr.Markdown("_(Haz clic en 'GENERAR ARTE FINAL' para poblar la galería)_")with gr.TabItem("📦 ZONA DE DESCARGAS", id="downloads_tab"):gr.Markdown("<p>Aquí aparecerán tus creaciones cuando pulses el botón de generar.</p>")gif_output = gr.File(label="🎁 Descargar Proceso (GIF Animado)")zip_output = gr.File(label="🗄️ Descargar Todas las Imágenes (ZIP)")generate_button = gr.Button("🚀 GENERAR ARTE FINAL Y DESCARGAS")# --- CONTROLADORES BACKEND CON PROGRESO VISUAL ---def live_preview_controller(img, seed, fx, ps, rgbs, dm, sl, tgi, ts, progress=gr.Progress(track_tqdm=True)):if img is None:gr.Warning("¡Sube una imagen para empezar a crear!")# Retornar una imagen placeholder evita errores y mantiene la UI limpiaplaceholder = Image.new('RGB', (512, 512), color=(10, 10, 20))return placeholder, []params = {"pixel_sorting_intensity": ps, "rgb_shift_intensity": rgbs,"datamosh_intensity": dm, "scanline_effect_intensity": sl,"tile_glitch_intensity": tgi, "tile_size": int(ts)}final_image, steps_data = run_glitch_pipeline(img, int(seed), fx, params, progress)return final_image, steps_datadef final_assets_controller(steps_data, progress=gr.Progress(track_tqdm=True)):if not steps_data or len(steps_data) <= 1:gr.Warning("No hay datos que procesar. Carga una imagen y aplica efectos primero.")return None, None, [], gr.Tabs(selected="preview_tab")progress(0, desc="Iniciando generación de archivos finales...")images = [img for img, _ in steps_data]# Crear GIFprogress(0.2, desc="Generando GIF del proceso...")gif_path = f"/tmp/glitch_art_{int(time.time())}.gif"images[0].save(gif_path, format='GIF', save_all=True, append_images=images[1:], duration=350, loop=0, optimize=True)# Crear ZIPprogress(0.6, desc="Comprimiendo imágenes en ZIP...")zip_path = f"/tmp/glitch_art_steps_{int(time.time())}.zip"with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:for i, (img, title) in enumerate(steps_data):img_bytes = io.BytesIO()img.save(img_bytes, format='PNG')img_bytes.seek(0)zipf.writestr(f"step_{i:02d}_{title.replace(' ', '_')}.png", img_bytes.getvalue())progress(0.9, desc="Finalizando galería...")gallery_items = [(img, title) for img, title in steps_data]gr.Info("✅ ¡Éxito! Tu arte está listo en las pestañas de Galería y Descargas.")# Cambia el foco a la pestaña de Galería para mostrar el resultadoreturn gr.File(value=gif_path), gr.File(value=zip_path), gallery_items, gr.Tabs(selected="gallery_tab")def randomize_seed():return random.randint(0, 1_000_000)# --- LISTENERS DE EVENTOS CON UI DE PROGRESO ACTIVADA ---# Esta es la clave para la estabilidad y la experiencia de usuariocontrols = [image_input, seed_input, active_effects,pixel_sorting_intensity, rgb_shift_intensity, datamosh_intensity,scanline_effect_intensity, tile_glitch_intensity, tile_size]# .change() para la previsualización en vivo (con barra de progreso)for control in controls:control.change(fn=live_preview_controller,inputs=controls,outputs=[final_output, shared_steps],show_progress="full" # ¡LA SOLUCIÓN AL BUG! Muestra la barra de progreso.)# .click() para la generación final (con barra de progreso)generate_button.click(fn=final_assets_controller,inputs=[shared_steps],outputs=[gif_output, zip_output, gallery_output, output_tabs],show_progress="full")randomize_seed_btn.click(fn=randomize_seed, inputs=[], outputs=[seed_input])if __name__ == "__main__":demo.launch(debug=True)12345674 unmodified lines12131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195# ==============================================================================# GLITCHCORE VANGUARD - VERSIÓN "STABLE CORE" (DEPURADA Y BLINDADA)# ==============================================================================import numpy as npfrom PIL import Image, ImageFileimport io4 unmodified linesimport gradio as grfrom typing import List, Tuple, Dict, Any, Optionalimport timeimport tempfile # FIX 2.1: Importamos la librería para manejo robusto de archivos temporales# --- CONFIGURACIÓN DE ROBUSTEZ A NIVEL DE PRODUCCIÓN ---warnings.filterwarnings("ignore", category=Image.DecompressionBombWarning)ImageFile.LOAD_TRUNCATED_IMAGES = True# ==============================================================================# ESTÉTICA - TEMA "NEON PULSE" (Sin cambios, ya era sólido)# ==============================================================================NEON_PULSE_CSS = """@import url('https://fonts.googleapis.com/css2?family=Roboto+Mono:wght@400;700&display=swap');:root {--neon-purple: #be00ff; --neon-cyan: #00f2ff; --dark-bg: #0a0a14;--panel-bg: rgba(20, 16, 38, 0.7); --panel-border: rgba(190, 0, 255, 0.3);--text-color: #e0e0e0;--glow-shadow: 0 0 5px var(--neon-cyan), 0 0 10px var(--neon-cyan), 0 0 20px var(--neon-purple), 0 0 30px var(--neon-purple);}body, .gradio-container { font-family: 'Roboto Mono', monospace; background: var(--dark-bg); background-image: radial-gradient(circle at 1% 1%, var(--neon-purple) 0.5px, transparent 0), radial-gradient(circle at 99% 99%, var(--neon-cyan) 0.5px, transparent 0); color: var(--text-color); }.main-title { text-align: center; font-size: 3.5rem !important; font-weight: 700; text-shadow: var(--glow-shadow); color: white; padding-bottom: 20px; letter-spacing: 4px; animation: flicker 3s infinite alternate; }@keyframes flicker { 0%, 18%, 22%, 25%, 53%, 57%, 100% { text-shadow: 0 0 4px #fff, 0 0 11px var(--neon-cyan), 0 0 19px var(--neon-cyan), 0 0 40px var(--neon-purple), 0 0 80px var(--neon-purple); } 20%, 24%, 55% { text-shadow: none; } }.pro-panel { background: var(--panel-bg) !important; border: 1px solid var(--panel-border) !important; border-radius: 16px !important; box-shadow: 0 8px 32px 0 rgba(0, 0, 0, 0.5) !important; backdrop-filter: blur(12px) !important; -webkit-backdrop-filter: blur(12px) !important; padding: 20px !important; transition: box-shadow 0.3s ease; }.pro-panel:hover { box-shadow: 0 0 20px var(--panel-border); }.gr-button { background: linear-gradient(90deg, var(--neon-purple), var(--neon-cyan)) !important; color: white !important; border: none !important; font-weight: bold !important; border-radius: 8px !important; transition: transform 0.2s ease, box-shadow 0.3s ease !important; box-shadow: 0 0 15px rgba(190, 0, 255, 0.5); }.gr-button:hover { transform: scale(1.05) translateY(-2px) !important; box-shadow: 0 0 30px rgba(0, 242, 255, 0.8) !important; }.tabs > .tab-nav > button.selected { background: var(--panel-bg) !important; color: white !important; border-bottom: 3px solid var(--neon-cyan) !important; text-shadow: 0 0 5px var(--neon-cyan); }.gr-gallery > .preview > img { border-radius: 10px !important; transition: transform 0.3s ease-in-out !important; border: 1px solid transparent; }.gr-gallery > .preview > img:hover { transform: scale(1.05) !important; border: 1px solid var(--neon-cyan); }#downloads_tab > div > p { font-size: 1.1em; text-align: center; color: var(--neon-cyan); padding: 20px; border: 1px dashed var(--panel-border); border-radius: 8px;}"""# ==============================================================================# NÚCLEO DE FUNCIONES GLITCH (Sin cambios, ya eran robustas)# ==============================================================================def safe_effect(func):def wrapper(img, **kwargs):try:if kwargs.get('intensity', 1.0) == 0: return img.copy()return func(img, **kwargs)except Exception as e:print(f"ADVERTENCIA: El efecto '{func.__name__}' falló con el error: {e}. Saltando efecto.")return imgreturn wrapper@safe_effectdef pixel_sorting(img, intensity): arr=np.array(img); h,_,_=arr.shape; b=np.dot(arr.astype(np.float32),[0.2989,0.5870,0.1140]); r=np.where(np.random.random(h)<intensity)[0]; [np.random.shuffle(s:=np.argsort(b[y])), setattr(arr, y, arr[y,s])] for y in r; return Image.fromarray(arr)@safe_effectdef rgb_shift(img, intensity): arr=np.array(img); max_s=int(arr.shape[1]*0.05); sx,sy=int(intensity*max_s*(random.random()*0.5+0.5)),int(intensity*max_s*(random.random()*0.5+0.5)); c=list(cv2.split(arr)); c[0]=np.roll(c[0],sx,axis=1); c[2]=np.roll(c[2],-sx,axis=1); c[1]=np.roll(c[1],sy,axis=0) if random.random()<intensity else c[1]; return Image.fromarray(cv2.merge(c))@safe_effectdef datamosh(img, intensity): q=max(1,min(100,int(20-intensity*18))); b=io.BytesIO(); img.save(b,format='JPEG',quality=q); d=bytearray(b.getvalue()); h=623; [d.__setitem__(i,random.randint(0,255)) for i in np.random.randint(h,len(d)-1,size=int(len(d)*0.1*intensity))] if len(d)>h else 0; try: n=Image.open(io.BytesIO(d)); n.load(); return n.convert('RGB') if n.mode!='RGB' else n; except Exception: return img@safe_effectdef tile_glitch(img, intensity, tile_size): arr=np.array(img); h,w,_=arr.shape; [ (t:=arr[y:min(y+tile_size,h),x:min(x+tile_size,w)], arr.__setitem__((slice(y,min(y+tile_size,h)),slice(x,min(x+tile_size,w))), np.roll(t,random.randint(-tile_size//2,tile_size//2),axis=random.randint(0,1)) if random.random()>0.5 else cv2.resize(np.rot90(t,random.randint(1,3)),(t.shape[1],t.shape[0]),interpolation=cv2.INTER_NEAREST))) for y in range(0,h,tile_size) for x in range(0,w,tile_size) if random.random()<intensity and t.size>0 ]; return Image.fromarray(arr)@safe_effectdef scanline_effect(img, intensity): arr=np.array(img); h,w,_=arr.shape; s=np.random.randint(-int(w*0.1*intensity),int(w*0.1*intensity),size=h); s[np.arange(h)%max(2,int(6-intensity*5))!=0]=0; c=np.arange(w); rc=(c-s[:,np.newaxis])%w; return Image.fromarray(arr[np.arange(h)[:,np.newaxis],rc])# ==============================================================================# PIPELINE DE PROCESAMIENTO Y CONTROLADORES DE INTERFAZ# ==============================================================================EFFECT_MAP = {"Pixel Sorting": pixel_sorting, "RGB Shift": rgb_shift, "Datamosh": datamosh, "Tile Glitch": tile_glitch, "Scanline Effect": scanline_effect}def create_placeholder_image():"""Crea una imagen de bienvenida/error consistente."""return Image.new('RGB', (512, 512), color=(10, 10, 20))def run_glitch_pipeline(image, seed, active_effects, params, progress):random.seed(seed); np.random.seed(seed)if image.mode != 'RGB': image = image.convert('RGB')steps = [(image.copy(), "Original")]current_img = image.copy()effects_to_run = [fx for fx in active_effects if fx in EFFECT_MAP]total_effects = len(effects_to_run)if total_effects == 0:progress(1, desc="Hecho. Ningún efecto seleccionado.")return current_img, stepsfor i, effect_name in enumerate(effects_to_run):progress((i + 1) / total_effects, desc=f"Procesando: {effect_name}...")func = EFFECT_MAP[effect_name]kwargs = {'intensity': params[f"{effect_name.lower().replace(' ', '_')}_intensity"]}if effect_name == "Tile Glitch":kwargs['tile_size'] = params["tile_size"]current_img = func(img=current_img, **kwargs)steps.append((current_img.copy(), effect_name))progress(1, desc="¡Pipeline completado!")return current_img, stepsdef live_preview_controller(img, seed, fx, ps, rgbs, dm, sl, tgi, ts, progress=gr.Progress(track_tqdm=True)):if img is None:# FIX 1.1: Si no hay imagen de entrada, no continuamos. Devolvemos el placeholder.return create_placeholder_image(), []params = {"pixel_sorting_intensity": ps, "rgb_shift_intensity": rgbs, "datamosh_intensity": dm, "scanline_effect_intensity": sl, "tile_glitch_intensity": tgi, "tile_size": int(ts)}try:final_image, steps_data = run_glitch_pipeline(img, int(seed), fx, params, progress)# FIX 1.2: Verificamos que el pipeline no haya devuelto None por un error inesperado.if final_image is None:gr.Error("El pipeline de efectos ha fallado. Devolviendo imagen original.")return img, [(img, "Original - Fallo en Pipeline")]return final_image, steps_dataexcept Exception as e:gr.Error(f"Ha ocurrido un error crítico en el controlador: {e}")return create_placeholder_image(), []def final_assets_controller(steps_data, progress=gr.Progress(track_tqdm=True)):if not steps_data or len(steps_data) <= 1:gr.Warning("No hay datos que procesar. Carga una imagen y aplica efectos primero.")return None, None, [], gr.Tabs(selected="preview_tab")# FIX 2.2: Usamos un bloque try...except para capturar errores de creación de archivos.try:progress(0, desc="Iniciando generación de archivos finales...")images = [img for img, _ in steps_data]# FIX 2.3: Creación de GIF con tempfileprogress(0.2, desc="Generando GIF del proceso...")with tempfile.NamedTemporaryFile(suffix=".gif", delete=False) as tmp_gif:images[0].save(tmp_gif.name, format='GIF', save_all=True, append_images=images[1:], duration=350, loop=0, optimize=True)gif_path = tmp_gif.name# FIX 2.4: Creación de ZIP con tempfileprogress(0.6, desc="Comprimiendo imágenes en ZIP...")with tempfile.NamedTemporaryFile(suffix=".zip", delete=False) as tmp_zip:with zipfile.ZipFile(tmp_zip.name, 'w', zipfile.ZIP_DEFLATED) as zipf:for i, (img, title) in enumerate(steps_data):img_bytes = io.BytesIO()img.save(img_bytes, format='PNG')img_bytes.seek(0)zipf.writestr(f"step_{i:02d}_{title.replace(' ', '_')}.png", img_bytes.getvalue())zip_path = tmp_zip.nameprogress(0.9, desc="Finalizando galería..."); gallery_items = [(img, title) for img, title in steps_data]gr.Info("✅ ¡Éxito! Tu arte está listo en las pestañas de Galería y Descargas.")return gr.File(value=gif_path), gr.File(value=zip_path), gallery_items, gr.Tabs(selected="gallery_tab")except Exception as e:gr.Error(f"No se pudieron generar los archivos. Error: {e}")return None, None, steps_data, gr.Tabs(selected="downloads_tab")# ==============================================================================# INTERFAZ GRADIO - "NEON PULSE" (CON VARIABLES CLARAS)# ==============================================================================with gr.Blocks(theme=gr.themes.Default(primary_hue="purple", secondary_hue="cyan"), css=NEON_PULSE_CSS) as demo:gr.Markdown("<h1 class='main-title'>G L I T C H C O R E /// VANGUARD</h1>")shared_steps = gr.State([])with gr.Row(equal_height=False):with gr.Column(scale=1, min_width=350):with gr.Group(elem_classes=["pro-panel"]):gr.Markdown("### 1. Carga tu Realidad"); image_input = gr.Image(type="pil", label="📷 SUBIR IMAGEN", height=300)gr.Markdown("### 2. Elige tu Distorsión"); active_effects = gr.CheckboxGroup(choices=list(EFFECT_MAP.keys()), value=list(EFFECT_MAP.keys()), label="🎛️ EFECTOS ACTIVOS")with gr.Accordion("🎲 SEMILLA DE ALEATORIEDAD", open=False):seed_input = gr.Number(label="Seed", value=42, precision=0); randomize_seed_btn = gr.Button("Nueva Semilla")with gr.Group(elem_classes=["pro-panel"]):gr.Markdown("### 3. Modula los Parámetros");with gr.Accordion("⚙️ AJUSTE FINO DE EFECTOS", open=True):# FIX 3: Nombres de variables descriptivos y consistentespixel_sorting_intensity = gr.Slider(0, 1, value=0.1, label="Pixel Sorting")rgb_shift_intensity = gr.Slider(0, 1, value=0.2, label="RGB Shift")datamosh_intensity = gr.Slider(0, 1, value=0.25, label="Datamosh")scanline_effect_intensity = gr.Slider(0, 1, value=0.2, label="Scanlines")tile_glitch_intensity = gr.Slider(0, 1, value=0.15, label="Tile Glitch")tile_size = gr.Slider(8, 256, value=64, step=8, label="Tamaño Tile")with gr.Column(scale=2, min_width=600):with gr.Group(elem_classes=["pro-panel"]):with gr.Tabs() as output_tabs:with gr.TabItem("🖼️ PREVISUALIZACIÓN EN VIVO", id="preview_tab"):final_output = gr.Image(label="Resultado Final", interactive=False, height=550, show_download_button=True, value=create_placeholder_image())with gr.TabItem("🎞️ GALERÍA DEL PROCESO", id="gallery_tab"):gallery_output = gr.Gallery(label="Proceso Paso a Paso", columns=3, height=550, object_fit="contain"); gr.Markdown("_(Haz clic en 'GENERAR' para poblar la galería)_")with gr.TabItem("📦 ZONA DE DESCARGAS", id="downloads_tab"):gr.Markdown("<p>Aquí aparecerán tus creaciones al pulsar el botón de generar.</p>"); gif_output = gr.File(label="🎁 Descargar Proceso (GIF)"); zip_output = gr.File(label="🗄️ Descargar Imágenes (ZIP)")generate_button = gr.Button("🚀 GENERAR ARTE FINAL Y DESCARGAS")# --- LISTENERS DE EVENTOS BLINDADOS ---controls = [image_input, seed_input, active_effects, pixel_sorting_intensity, rgb_shift_intensity, datamosh_intensity, scanline_effect_intensity, tile_glitch_intensity, tile_size]for control in controls:control.change(fn=live_preview_controller, inputs=controls, outputs=[final_output, shared_steps], show_progress="full")generate_button.click(fn=final_assets_controller, inputs=[shared_steps], outputs=[gif_output, zip_output, gallery_output, output_tabs], show_progress="full")randomize_seed_btn.click(fn=lambda: random.randint(0, 1_000_000), inputs=[], outputs=[seed_input])if __name__ == "__main__":demo.launch(debug=True)
app.py+108-296