Create bckp
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400# ==============================================================================# GLITCHCORE VANGUARD - VERSIÓN "ARCHANGEL 1.1" (FIXED & ENHANCED)# RE-ENGINEERED BY YOUR PERSONAL AI GHOST IN THE MACHINE# ==============================================================================# CHANGELOG "ARCHANGEL 1.1" EDITION:# - [FIX] Patched race condition with temporary files. Reverted from# TemporaryDirectory to NamedTemporaryFile(delete=False) to ensure# files persist long enough for Gradio's post-processing lifecycle.# ==============================================================================
import numpy as npfrom PIL import Image, ImageFile, ImageOpsimport ioimport zipfileimport randomimport cv2import warningsimport gradio as grimport timeimport tempfileimport osfrom typing import List, Tuple, Dict, Any, Optional
# --- CONFIGURACIÓN DE ROBUSTEZ ---warnings.filterwarnings("ignore", category=Image.DecompressionBombWarning)ImageFile.LOAD_TRUNCATED_IMAGES = True
# --- CONSTANTES ---MAX_DIMENSION = 1920
# --- ESTÉTICA ---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; }.preset-button-row { gap: 10px; }.preset-button-row button { flex-grow: 1; }"""
# ==============================================================================# NÚCLEO DE FUNCIONES GLITCH - AMPLIADO Y REFINADO# ==============================================================================
def safe_effect(func): """Decorador para asegurar que un efecto no rompa el pipeline si falla.""" def wrapper(img: Image.Image, **kwargs) -> Image.Image: try: return func(img, **kwargs) except Exception as e: print(f"ERROR en el efecto '{func.__name__}': {e}") import traceback traceback.print_exc() gr.Warning(f"El efecto '{func.__name__}' falló y fue omitido.") return img return wrapper
@safe_effectdef pixel_sorting(img: Image.Image, probability: float, threshold: float, **kwargs) -> Image.Image: if probability == 0: return img arr = np.array(img) rows_to_process = np.where(np.random.random(arr.shape[0]) < probability)[0] brightness = np.dot(arr[...,:3].astype(np.float32), [0.2989, 0.5870, 0.1140]) for y in rows_to_process: row_brightness = brightness[y] mask = row_brightness >= (threshold * 255) if not np.any(mask): continue pixels_to_sort = arr[y, mask] sorted_indices = np.argsort(row_brightness[mask]) if random.random() > 0.5: pixels_to_sort = pixels_to_sort[sorted_indices] else: pixels_to_sort = pixels_to_sort[sorted_indices[::-1]] arr[y, mask] = pixels_to_sort return Image.fromarray(arr)
@safe_effectdef rgb_shift(img: Image.Image, shift_x: int, shift_y: int, **kwargs) -> Image.Image: if shift_x == 0 and shift_y == 0: return img arr = np.array(img) r, g, b = arr[:,:,0], arr[:,:,1], arr[:,:,2] rand_x = (random.random() * 0.5 + 0.5) rand_y = (random.random() * 0.5 + 0.5) r_shifted = np.roll(r, int(shift_x * rand_x), axis=1) b_shifted = np.roll(b, -int(shift_x * rand_x), axis=1) g_shifted = np.roll(g, int(shift_y * rand_y), axis=0) return Image.fromarray(np.stack([r_shifted, g_shifted, b_shifted], axis=-1))
@safe_effectdef jpeg_artifacts(img: Image.Image, quality: int, cycles: int, jpeg_subsampling: str, **kwargs) -> Image.Image: if cycles == 0: return img output_img = img.copy() subsampling_map = {"Estándar (4:2:0)": 0, "Alta Calidad (4:4:4)": -1} subsampling_val = subsampling_map.get(jpeg_subsampling, 0) for _ in range(cycles): buffer = io.BytesIO() output_img.save(buffer, format='JPEG', quality=quality, subsampling=subsampling_val) buffer.seek(0) output_img = Image.open(buffer) return output_img
@safe_effectdef analog_noise(img: Image.Image, amount: float, mono: bool, **kwargs) -> Image.Image: if amount == 0: return img arr = np.array(img, dtype=np.float32) sigma = amount * 128 if mono: noise = np.random.normal(0, sigma, (arr.shape[0], arr.shape[1])) noise = np.stack([noise] * 3, axis=-1) else: noise = np.random.normal(0, sigma, arr.shape) noisy_arr = np.clip(arr + noise, 0, 255).astype(np.uint8) if amount > 0.05: noisy_arr = cv2.GaussianBlur(noisy_arr, (3, 3), 0) return Image.fromarray(noisy_arr) @safe_effectdef color_quantization(img: Image.Image, num_colors: int, dither: bool, **kwargs) -> Image.Image: if num_colors >= 256: return img dither_mode = Image.Dither.FLOYDSTEINBERG if dither else Image.Dither.NONE return img.convert('P', palette=Image.Palette.ADAPTIVE, colors=num_colors, dither=dither_mode).convert('RGB')
@safe_effectdef slit_scan(img: Image.Image, num_slices: int, direction: str, **kwargs) -> Image.Image: if num_slices <= 1: return img arr = np.array(img) h, w, _ = arr.shape output_arr = np.zeros_like(arr) if direction == "Horizontal": slice_width = max(1, w // num_slices) for i in range(num_slices): slice_start_x = i * slice_width slice_end_x = min((i + 1) * slice_width, w) scanline_x = random.randint(slice_start_x, min(slice_end_x, w - 1)) scanline = arr[:, scanline_x:scanline_x + 1, :] output_arr[:, slice_start_x:slice_end_x, :] = scanline else: # Vertical slice_height = max(1, h // num_slices) for i in range(num_slices): slice_start_y = i * slice_height slice_end_y = min((i + 1) * slice_height, h) scanline_y = random.randint(slice_start_y, min(slice_end_y, h - 1)) scanline = arr[scanline_y:scanline_y + 1, :, :] output_arr[slice_start_y:slice_end_y, :, :] = scanline return Image.fromarray(output_arr)
# ==============================================================================# LÓGICA DE PROCESAMIENTO CENTRALIZADA# ==============================================================================
EFFECT_FUNCTIONS = { 'Pixel Sorting': pixel_sorting, 'RGB Shift': rgb_shift, 'JPEG Artifacts': jpeg_artifacts, 'Analog Noise': analog_noise, 'Color Quantization': color_quantization, 'Slit-Scan': slit_scan}
def resize_image_if_needed(img: Optional[Image.Image]) -> Optional[Image.Image]: if img is not None and (img.width > MAX_DIMENSION or img.height > MAX_DIMENSION): gr.Info(f"Imagen grande detectada! Redimensionada a {MAX_DIMENSION}px para un rendimiento óptimo.") img.thumbnail((MAX_DIMENSION, MAX_DIMENSION), Image.Resampling.LANCZOS) return img
def create_placeholder_image(size=(1024, 1024)): return Image.new('RGB', size, color=(10, 10, 20))
def process_image_pipeline(base_image: Image.Image, seed: int, active_effects: List[str], params: Dict[str, Any]) -> Tuple[Image.Image, List[Tuple[Image.Image, str]]]: random.seed(seed) np.random.seed(seed) image = base_image.convert('RGB') if base_image.mode != 'RGB' else base_image.copy() steps = [(image.copy(), "Original")] effects_to_run = [fx for fx in active_effects if fx in EFFECT_FUNCTIONS] for name in effects_to_run: func = EFFECT_FUNCTIONS[name] image = func(img=image, **params) steps.append((image.copy(), name)) return image, steps
# ==============================================================================# CONFIGURACIÓN DE EFECTOS, PARÁMETROS Y PRESETS# ==============================================================================
EFFECT_CONFIG = { 'Pixel Sorting': { 'params': { 'probability': {'label': 'Probabilidad de Fila', 'component': gr.Slider, 'args': {'minimum': 0, 'maximum': 1, 'value': 0.1}}, 'threshold': {'label': 'Umbral de Brillo', 'component': gr.Slider, 'args': {'minimum': 0, 'maximum': 1, 'value': 0.25}}, } }, 'RGB Shift': { 'params': { 'shift_x': {'label': 'Desplazamiento Horizontal', 'component': gr.Slider, 'args': {'minimum': 0, 'maximum': 100, 'step': 1, 'value': 5}}, 'shift_y': {'label': 'Desplazamiento Vertical', 'component': gr.Slider, 'args': {'minimum': 0, 'maximum': 100, 'step': 1, 'value': 5}} } }, 'JPEG Artifacts': { 'params': { 'quality': {'label': 'Calidad JPEG (Baja es más fuerte)', 'component': gr.Slider, 'args': {'minimum': 1, 'maximum': 100, 'step': 1, 'value': 30}}, 'cycles': {'label': 'Ciclos de Re-compresión', 'component': gr.Slider, 'args': {'minimum': 0, 'maximum': 10, 'step': 1, 'value': 2}}, 'jpeg_subsampling': {'label': 'Submuestreo de Croma', 'component': gr.Radio, 'args': {'choices': ['Estándar (4:2:0)', 'Alta Calidad (4:4:4)'], 'value': 'Estándar (4:2:0)'}} } }, 'Analog Noise': { 'params': { 'amount': {'label': 'Cantidad de Ruido', 'component': gr.Slider, 'args': {'minimum': 0, 'maximum': 1, 'value': 0.1}}, 'mono': {'label': 'Ruido Monocromático', 'component': gr.Checkbox, 'args': {'value': True}} } }, 'Color Quantization': { 'params': { 'num_colors': {'label': 'Número de Colores', 'component': gr.Slider, 'args': {'minimum': 2, 'maximum': 256, 'step': 1, 'value': 256}}, 'dither': {'label': 'Aplicar Dithering (Tramado)', 'component': gr.Checkbox, 'args': {'value': True}} } }, 'Slit-Scan': { 'params': { 'num_slices': {'label': 'Número de Lonchas', 'component': gr.Slider, 'args': {'minimum': 0, 'maximum': 128, 'step': 1, 'value': 16}}, 'direction': {'label': 'Dirección del Barrido', 'component': gr.Radio, 'args': {'choices': ['Horizontal', 'Vertical'], 'value': 'Horizontal'}} } }}
ALL_PARAM_KEYS = [param_name for effect in EFFECT_CONFIG.values() for param_name in effect['params'].keys()]
PRESETS = { 'Sutil': { 'probability': 0.05, 'threshold': 0.5, 'shift_x': 3, 'shift_y': 3, 'quality': 80, 'cycles': 1, 'jpeg_subsampling': 'Alta Calidad (4:4:4)', 'amount': 0.05, 'mono': True, 'num_colors': 256, 'dither': True, 'num_slices': 0, 'direction': 'Horizontal', }, 'Ciberpunk': { 'probability': 0.15, 'threshold': 0.2, 'shift_x': 10, 'shift_y': 2, 'quality': 50, 'cycles': 2, 'jpeg_subsampling': 'Estándar (4:2:0)', 'amount': 0.1, 'mono': True, 'num_colors': 64, 'dither': True, 'num_slices': 32, 'direction': 'Horizontal', }, 'Anomalía VHS': { 'probability': 0.0, 'threshold': 0.5, 'shift_x': 25, 'shift_y': 3, 'quality': 35, 'cycles': 4, 'jpeg_subsampling': 'Estándar (4:2:0)', 'amount': 0.25, 'mono': True, 'num_colors': 128, 'dither': True, 'num_slices': 80, 'direction': 'Vertical', }, 'Caos Digital': { 'probability': 0.8, 'threshold': 0.1, 'shift_x': 60, 'shift_y': 60, 'quality': 5, 'cycles': 8, 'jpeg_subsampling': 'Estándar (4:2:0)', 'amount': 0.3, 'mono': False, 'num_colors': 16, 'dither': False, 'num_slices': 64, 'direction': 'Horizontal', }}
# ==============================================================================# CONTROLADORES DE GRADIO# ==============================================================================
def master_controller(original_image, batch_size, base_seed, active_effects, *all_params, progress=gr.Progress(track_tqdm=True)): """El controlador principal que orquesta todo el proceso de generación.""" if original_image is None: gr.Warning("Sube una imagen primero para poder generar arte.") placeholder = create_placeholder_image() # Devuelve un resultado para cada salida para evitar errores de desempaquetado return placeholder, [placeholder], None, None, gr.update(selected="gallery_tab")
params = dict(zip(ALL_PARAM_KEYS, all_params)) batch_size = int(batch_size) seeds = [base_seed + i for i in range(batch_size)] final_batch_images = [] progress(0, desc="[1/3] Inicializando tubería de renderizado...") first_image_result, steps_data = process_image_pipeline(original_image, seeds[0], active_effects, params) if first_image_result is None: gr.Error("El procesamiento de la primera imagen falló. Abortando.") placeholder = create_placeholder_image() return placeholder, [placeholder], None, None, gr.update() final_batch_images.append(first_image_result) for i in range(1, batch_size): progress(i / batch_size, desc=f"[2/3] Inyectando caos en imagen {i+1}/{batch_size}...") image_result, _ = process_image_pipeline(original_image, seeds[i], active_effects, params) if image_result: final_batch_images.append(image_result)
progress(0.9, desc="[3/3] Renderizando anomalías y empaquetando descargas...") gif_path, zip_path = None, None try: # --- INICIO DE LA CORRECCIÓN --- # Creamos archivos temporales con nombre y con delete=False. # Esto los deja en el disco para que Gradio los recoja. # Generar GIF del proceso de la PRIMERA imagen with tempfile.NamedTemporaryFile(suffix=".gif", delete=False) as tmp_gif: gif_path = tmp_gif.name images_for_gif = [step_img for step_img, _ in steps_data] images_for_gif[0].save(gif_path, save_all=True, append_images=images_for_gif[1:], duration=350, loop=0, optimize=True)
# Generar ZIP con TODAS las imágenes finales del lote with tempfile.NamedTemporaryFile(suffix=".zip", delete=False) as tmp_zip: zip_path = tmp_zip.name with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf: for i, img in enumerate(final_batch_images): byte_io = io.BytesIO() img.save(byte_io, 'PNG') byte_io.seek(0) zf.writestr(f"result_seed_{seeds[i]}.png", byte_io.getvalue()) # --- FIN DE LA CORRECCIÓN ---
gr.Info(f"✅ ¡Éxito! Lote de {batch_size} imágenes generado. Semilla base: {base_seed}") except Exception as e: import traceback traceback.print_exc() gr.Error(f"No se pudieron generar los archivos de descarga. Error: {e}") # Devolvemos las rutas de los archivos. Gradio los copiará y servirá. return first_image_result, final_batch_images, gif_path, zip_path, gr.update(selected="gallery_tab")
def apply_preset(preset_name: str) -> List[gr.update]: preset_values = PRESETS.get(preset_name, {}) updates = [] for effect_cfg in EFFECT_CONFIG.values(): for param_name, param_cfg in effect_cfg['params'].items(): value = preset_values.get(param_name, param_cfg['args']['value']) updates.append(gr.update(value=value)) return updates
# ==============================================================================# INTERFAZ GRADIO# ==============================================================================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 /// ARCHANGEL</h1>") original_image_state = gr.State(None) all_param_components = []
with gr.Row(): with gr.Column(scale=1, min_width=400): with gr.Group(elem_classes=["pro-panel"]): gr.Markdown("### 1. Carga y Configuración") image_input = gr.Image(type="pil", label="📷 SUBIR IMAGEN", height=300) active_effects = gr.CheckboxGroup(choices=list(EFFECT_CONFIG.keys()), value=list(EFFECT_CONFIG.keys()), label="🎛️ EFECTOS ACTIVOS") with gr.Accordion("🎲 Semilla y Lotes", open=True): seed_input = gr.Number(label="Semilla Base", value=int(time.time() % 1e9), precision=0) randomize_seed_btn = gr.Button("Nueva Semilla 🎲") batch_size_input = gr.Slider(minimum=1, maximum=20, value=1, step=1, label="Tamaño del Lote") with gr.Group(elem_classes=["pro-panel"]): gr.Markdown("### 2. Presets Rápidos") preset_buttons = [] preset_names = list(PRESETS.keys()) for i in range(0, len(preset_names), 2): with gr.Row(elem_classes=["preset-button-row"]): for name in preset_names[i:i+2]: preset_buttons.append(gr.Button(name)) with gr.Group(elem_classes=["pro-panel"]): gr.Markdown("### 3. Parámetros Detallados") for effect_name, config in EFFECT_CONFIG.items(): with gr.Accordion(effect_name, open=False): for param_name, param_config in config['params'].items(): component = param_config['component'] args = param_config['args'] param_component = component(label=param_config['label'], **args) all_param_components.append(param_component) with gr.Row(): generate_button = gr.Button("🚀 Generar Arte Final")
with gr.Column(scale=2, min_width=600): with gr.Tabs(elem_id="output_tabs") as output_tabs: with gr.TabItem("🖼️ VISOR PRINCIPAL", id="gallery_tab"): gr.Markdown("#### Resultado Principal (Primera imagen del lote)") hero_output = gr.Image(label="Resultado Principal", interactive=False) gr.Markdown("#### Galería del Lote Completo") gallery_output = gr.Gallery(label="Resultados del Lote", columns=4, height=400, object_fit="contain", preview=True) with gr.TabItem("📦 ZONA DE DESCARGAS", id="downloads_tab"): gif_output = gr.File(label="🎁 Descargar Proceso (GIF del primer resultado)") zip_output = gr.File(label="🗄️ Descargar Lote Completo (ZIP)") def store_and_resize(img): resized = resize_image_if_needed(img) return resized, resized image_input.upload(fn=store_and_resize, inputs=[image_input], outputs=[image_input, original_image_state])
generate_button.click( fn=master_controller, inputs=[original_image_state, batch_size_input, seed_input, active_effects, *all_param_components], outputs=[hero_output, gallery_output, gif_output, zip_output, output_tabs] )
for button in preset_buttons: button.click( fn=apply_preset, inputs=[button], outputs=all_param_components ) randomize_seed_btn.click(fn=lambda: random.randint(0, 1_000_000_000), outputs=[seed_input])
if __name__ == "__main__": demo.launch(debug=True, show_error=True)bckpAdded+400