Update app.py
Browse files1234513 unmodified lines19202122232425262728293031323334353637383940414243445 unmodified lines5051525354556 unmodified lines62636465666768697071727374757612 unmodified lines899091929394959697989910012 unmodified lines1131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721 unmodified line174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205# ==============================================================================# GLITCHCORE VANGUARD - VERSIÓN "CLEAN SLATE" (INDENTATION FIX)# ==============================================================================import numpy as np13 unmodified linesImageFile.LOAD_TRUNCATED_IMAGES = True# ==============================================================================# ESTÉTICA - TEMA "NEON PULSE" (Sin cambios)# ==============================================================================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;}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; 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; }.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; }"""# ==============================================================================# NÚCLEO DE FUNCIONES GLITCH (Sin cambios)# ==============================================================================def safe_effect(func):def wrapper(img, **kwargs):5 unmodified linesreturn imgreturn wrapper@safe_effectdef pixel_sorting(img: Image.Image, intensity: float, **kwargs) -> Image.Image:arr = np.array(img); height, _, _ = arr.shape; brightness = np.dot(arr.astype(np.float32), [0.2989, 0.5870, 0.1140]); rows_to_process = np.where(np.random.random(height) < intensity)[0]6 unmodified linesif 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, **kwargs) -> Image.Image:quality = max(1, min(100, int(20 - intensity * 18))); buffer = io.BytesIO(); img.save(buffer, format='JPEG', quality=quality); data = bytearray(buffer.getvalue()); header_size = 623if len(data) > header_size:indices = np.random.randint(header_size, len(data) - 1, size=int(len(data) * 0.1 * intensity))for idx in indices: data[idx] = random.randint(0, 255)try: 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@safe_effectdef tile_glitch(img: Image.Image, intensity: float, tile_size: int, **kwargs) -> Image.Image:arr = np.array(img); height, width, _ = arr.shape12 unmodified linesreturn Image.fromarray(arr[np.arange(height)[:, np.newaxis], (np.arange(width) - shifts[:, np.newaxis]) % width])# ==============================================================================# LÓGICA DE PROCESAMIENTO Y CONTROLADORES (Sin cambios)# ==============================================================================EFFECT_MAP = {"Pixel Sorting": pixel_sorting, "RGB Shift": rgb_shift, "Datamosh": datamosh, "Tile Glitch": tile_glitch, "Scanline Effect": scanline_effect}def create_placeholder_image(size=(512, 512)):return Image.new('RGB', size, color=(10, 10, 20))def process_image(original_image, seed, active_effects, params, progress):if original_image is None: return None, []12 unmodified linesdef preview_controller(original_image, seed, fx, ps, rgbs, dm, sl, tgi, ts, progress=gr.Progress(track_tqdm=True)):if original_image is None:gr.Warning("Sube una imagen primero para poder previsualizar.")return gr.update(value=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)}processed_image, steps_data = process_image(original_image, int(seed), fx, params, progress)if processed_image is None:gr.Error("El procesamiento falló. Mostrando placeholder.")return gr.update(value=create_placeholder_image()), []gr.Info("Previsualización actualizada.")return gr.update(value=processed_image), steps_data# *** CORRECCIÓN CRÍTICA: INDENTATION FIX ***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 arte procesado para generar. Usa 'Previsualizar' primero.")return gr.update(), gr.update(), gr.update(), gr.update()try:progress(0, desc="Iniciando..."); images = [img for img, _ in steps_data]progress(0.2, desc="Generando GIF...");with tempfile.NamedTemporaryFile(suffix=".gif", delete=False) as tmp:gif_path = tmp.nameimages[0].save(gif_path, format='GIF', save_all=True, append_images=images[1:], duration=350, loop=0)progress(0.6, desc="Generando ZIP...");with tempfile.NamedTemporaryFile(suffix=".zip", delete=False) as tmp:zip_path = tmp.name# La línea siguiente es la que tenía la indentación incorrecta. Ahora está corregida.with zipfile.ZipFile(zip_path, 'w') as zf:for i, (img, title) in enumerate(steps_data):b = io.BytesIO()img.save(b, 'PNG')b.seek(0) # Importante: rebobinar el buffer antes de leerlozf.writestr(f"step_{i:02d}_{title.replace(' ', '_')}.png", b.getvalue())progress(1, desc="¡Hecho!"); gr.Info("✅ ¡Éxito! Tu arte está listo.")return gr.update(value=gif_path, visible=True), gr.update(value=zip_path, visible=True), gr.update(value=steps_data), gr.update(selected="gallery_tab")except Exception as e:gr.Error(f"No se pudieron generar los archivos. Error: {e}")return gr.update(), gr.update(), gr.update(), gr.update(selected="downloads_tab")# ==============================================================================# INTERFAZ GRADIO (Sin cambios)# ==============================================================================with gr.Blocks(theme=gr.themes.Default(primary_hue="purple"), css=NEON_PULSE_CSS) as demo:gr.Markdown("<h1 class='main-title'>G L I T C H C O R E /// VANGUARD</h1>")original_image_state = gr.State(None)processed_steps_state = gr.State([])with gr.Row():with gr.Column(scale=1, min_width=350):with gr.Group(elem_classes=["pro-panel"]):1 unmodified linegr.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")pixel_s_i = gr.Slider(0,1,value=0.1,label="Pixel Sorting"); rgb_s_i = gr.Slider(0,1,value=0.2,label="RGB Shift")datamosh_i = gr.Slider(0,1,value=0.25,label="Datamosh"); scanline_i = gr.Slider(0,1,value=0.2,label="Scanlines")tile_g_i = gr.Slider(0,1,value=0.15,label="Tile Glitch"); tile_s = gr.Slider(8,256,value=64,step=8,label="Tamaño Tile")with gr.Row():preview_button = gr.Button("🎨 Previsualizar Cambios")generate_button = gr.Button("🚀 Generar Arte Final")with gr.Column(scale=2, min_width=600):with gr.Tabs() as output_tabs:with gr.TabItem("🖼️ LIENZO DIGITAL", id="preview_tab"):final_output = gr.Image(label="Resultado", height=600, value=create_placeholder_image())with gr.TabItem("🎞️ GALERÍA DEL PROCESO", id="gallery_tab"):gallery_output = gr.Gallery(label="Pasos", columns=3, height=600, object_fit="contain")with gr.TabItem("📦 ZONA DE DESCARGAS", id="downloads_tab"):gif_output = gr.File(label="🎁 Descargar Proceso (GIF)", visible=False)zip_output = gr.File(label="🗄️ Descargar Imágenes (ZIP)", visible=False)def store_image(img):if img is None: return gr.update(value=create_placeholder_image()), Nonereturn gr.update(value=img), imgimage_input.upload(fn=store_image, inputs=[image_input], outputs=[final_output, original_image_state])all_inputs = [original_image_state, seed_input, active_effects, pixel_s_i, rgb_s_i, datamosh_i, scanline_i, tile_g_i, tile_s]preview_button.click(fn=preview_controller, inputs=all_inputs, outputs=[final_output, processed_steps_state], show_progress="full")1234513 unmodified lines19202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788895 unmodified lines95969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401416 unmodified lines14814915015115215312 unmodified lines16616716816917017117217317417517617717817918018118212 unmodified lines1951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312321 unmodified line234235236237238239240241242243244245246247248249250251252253254255# ==============================================================================# GLITCHCORE VANGUARD - VERSIÓN "BULLETPROOF" (FINAL Y COMPLETA)# ==============================================================================import numpy as np13 unmodified linesImageFile.LOAD_TRUNCATED_IMAGES = True# ==============================================================================# ESTÉTICA - TEMA "NEON PULSE" (COMPLETO)# ==============================================================================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;}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;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;}.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;}"""# ==============================================================================# NÚCLEO DE FUNCIONES GLITCH - REFORZADO Y CORREGIDO# ==============================================================================def safe_effect(func):def wrapper(img, **kwargs):5 unmodified linesreturn imgreturn wrapperdef find_sos_marker(jpeg_data):"""Encuentra la posición del marcador Start of Scan (0xFFDA) en datos JPEG."""sos_marker = b'\xff\xda'try:return jpeg_data.find(sos_marker, 2)except Exception:return -1 # Devuelve -1 si no se encuentra, para manejar el error@safe_effectdef datamosh(img: Image.Image, intensity: float, **kwargs) -> Image.Image:buffer = io.BytesIO()# Preservar metadatos EXIF si existen, para un datamoshing más consistenteexif = img.info.get('exif', b'')img.save(buffer, format='JPEG', quality=95, exif=exif)data = buffer.getvalue()header_end_pos = find_sos_marker(data)if header_end_pos == -1:print("ADVERTENCIA: No se encontró el marcador SOS en el JPEG. Saltando datamosh.")return imgcorruption_start_point = header_end_pos + 12 # Un offset seguro después del marcador SOSif len(data) > corruption_start_point:byte_data = bytearray(data)corruption_amount = int((len(byte_data) - corruption_start_point) * 0.4 * intensity)if corruption_amount > 0:indices = np.random.randint(corruption_start_point, len(byte_data) - 1, size=corruption_amount)for idx in indices:byte_data[idx] = random.randint(0, 255)try:new_img = Image.open(io.BytesIO(byte_data))new_img.load()return new_img.convert('RGB') if new_img.mode != 'RGB' else new_imgexcept Exception as e:print(f"ADVERTENCIA: La corrupción de datamosh creó una imagen inválida ({e}). Devolviendo la anterior.")return imgreturn img@safe_effectdef pixel_sorting(img: Image.Image, intensity: float, **kwargs) -> Image.Image:arr = np.array(img); height, _, _ = arr.shape; brightness = np.dot(arr.astype(np.float32), [0.2989, 0.5870, 0.1140]); rows_to_process = np.where(np.random.random(height) < intensity)[0]6 unmodified linesif random.random() < intensity: channels[1] = np.roll(channels[1], shift_y, axis=0)return Image.fromarray(cv2.merge(channels))@safe_effectdef tile_glitch(img: Image.Image, intensity: float, tile_size: int, **kwargs) -> Image.Image:arr = np.array(img); height, width, _ = arr.shape12 unmodified linesreturn Image.fromarray(arr[np.arange(height)[:, np.newaxis], (np.arange(width) - shifts[:, np.newaxis]) % width])# ==============================================================================# LÓGICA DE PROCESAMIENTO Y CONTROLADORES# ==============================================================================EFFECT_MAP = {"Pixel Sorting": pixel_sorting, "RGB Shift": rgb_shift, "Datamosh": datamosh, "Tile Glitch": tile_glitch, "Scanline Effect": scanline_effect}def resize_image_if_needed(img: Image.Image, max_dimension: int = 1280) -> Image.Image:if img.width > max_dimension or img.height > max_dimension:gr.Info(f"La imagen es muy grande ({img.width}x{img.height}). Redimensionando a {max_dimension}px para mejor rendimiento.")img.thumbnail((max_dimension, max_dimension), Image.Resampling.LANCZOS)return imgdef create_placeholder_image(size=(512, 512)): return Image.new('RGB', size, color=(10, 10, 20))def process_image(original_image, seed, active_effects, params, progress):if original_image is None: return None, []12 unmodified linesdef preview_controller(original_image, seed, fx, ps, rgbs, dm, sl, tgi, ts, progress=gr.Progress(track_tqdm=True)):if original_image is None:gr.Warning("Sube una imagen primero para poder previsualizar."); return gr.update(value=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)}processed_image, steps_data = process_image(original_image, int(seed), fx, params, progress)if processed_image is None:gr.Error("El procesamiento falló."); return gr.update(value=create_placeholder_image()), []gr.Info("Previsualización actualizada."); return gr.update(value=processed_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("Usa 'Previsualizar' primero."); return gr.update(), gr.update(), gr.update(), gr.update()try:progress(0, desc="Iniciando..."); images = [img for img, _ in steps_data]progress(0.2, desc="Generando GIF...");with tempfile.NamedTemporaryFile(suffix=".gif", delete=False) as tmp:gif_path = tmp.name; images[0].save(gif_path, format='GIF', save_all=True, append_images=images[1:], duration=350, loop=0, optimize=True)progress(0.6, desc="Generando ZIP...");with tempfile.NamedTemporaryFile(suffix=".zip", delete=False) as tmp:zip_path = tmp.namewith zipfile.ZipFile(zip_path, 'w') as zf:for i, (img, title) in enumerate(steps_data):b = io.BytesIO(); img.save(b, 'PNG'); b.seek(0); zf.writestr(f"step_{i:02d}_{title.replace(' ', '_')}.png", b.getvalue())progress(1, desc="¡Hecho!"); gr.Info("✅ ¡Éxito! Tu arte está listo.")return gr.update(value=gif_path, visible=True), gr.update(value=zip_path, visible=True), gr.update(value=steps_data), gr.update(selected="gallery_tab")except Exception as e:gr.Error(f"No se pudieron generar los archivos. Error: {e}"); return gr.update(), gr.update(), gr.update(), gr.update(selected="downloads_tab")# ==============================================================================# INTERFAZ GRADIO# ==============================================================================with gr.Blocks(theme=gr.themes.Default(primary_hue="purple"), css=NEON_PULSE_CSS) as demo:gr.Markdown("<h1 class='main-title'>G L I T C H C O R E /// VANGUARD</h1>")original_image_state = gr.State(None); processed_steps_state = gr.State([])with gr.Row():with gr.Column(scale=1, min_width=350):with gr.Group(elem_classes=["pro-panel"]):1 unmodified linegr.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")pixel_s_i=gr.Slider(0,1,value=0.1,label="Pixel Sorting"); rgb_s_i=gr.Slider(0,1,value=0.2,label="RGB Shift"); datamosh_i=gr.Slider(0,1,value=0.25,label="Datamosh"); scanline_i=gr.Slider(0,1,value=0.2,label="Scanlines"); tile_g_i=gr.Slider(0,1,value=0.15,label="Tile Glitch"); tile_s=gr.Slider(8,256,value=64,step=8,label="Tamaño Tile")with gr.Row(): preview_button = gr.Button("🎨 Previsualizar Cambios"); generate_button = gr.Button("🚀 Generar Arte Final")with gr.Column(scale=2, min_width=600):with gr.Tabs() as output_tabs:with gr.TabItem("🖼️ LIENZO DIGITAL", id="preview_tab"): final_output = gr.Image(label="Resultado", height=600, value=create_placeholder_image())with gr.TabItem("🎞️ GALERÍA DEL PROCESO", id="gallery_tab"): gallery_output = gr.Gallery(label="Pasos", columns=3, height=600, object_fit="contain")with gr.TabItem("📦 ZONA DE DESCARGAS", id="downloads_tab"): gif_output = gr.File(label="🎁 Descargar Proceso (GIF)", visible=False); zip_output = gr.File(label="🗄️ Descargar Imágenes (ZIP)", visible=False)def store_and_resize_image(img):if img is None: return gr.update(value=create_placeholder_image()), Noneresized_img = resize_image_if_needed(img)return gr.update(value=resized_img), resized_imgimage_input.upload(fn=store_and_resize_image, inputs=[image_input], outputs=[final_output, original_image_state])all_inputs = [original_image_state, seed_input, active_effects, pixel_s_i, rgb_s_i, datamosh_i, scanline_i, tile_g_i, tile_s]preview_button.click(fn=preview_controller, inputs=all_inputs, outputs=[final_output, processed_steps_state], show_progress="full")
app.py+124-74