Update app.py
Browse files1234567891011121310 unmodified lines2425262728293031323334353619 unmodified lines5657585960616212 unmodified lines757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591 unmodified line1611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452466 unmodified lines253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429# ======================================================================================# GLITCHCRAFT NEXUS v3.1 - KUSANAGI "MOTOKO PATCH"# PROTOCOL: VISUAL REALITY ALTERATION# AUTHOR: YOUR GHOST IN THE MACHINE# ======================================================================================# KUSANAGI v3.1 CHANGELOG:# - [BUGFIX] Patched Gradio 4.x API incompatibility. Presets now use gr.update() instead of component.update().# - [UX/UI] Parameter matrix is now always exposed for fine-grained control, removing the collapsed accordion.# - [REFACTOR] Standardized parameter keys across all dictionaries (EFFECT_CONFIG, PRESETS) to simplify code# and remove complex, error-prone mapping logic.# ======================================================================================import numpy as np10 unmodified lines# --- KERNEL CONFIGURATION ---warnings.filterwarnings("ignore", category=Image.DecompressionBombWarning)ImageFile.LOAD_TRUNCATED_IMAGES = True # Essential for handling corrupted data streams# --- CONSTANTS ---MAX_DIMENSION = 1920HEADER_BYPASS_RATIO = 0.15 # % of file header to skip during datamosh to avoid total corruption# --- AESTHETICS & UI ---HACKER_TERMINAL_CSS = """@import url('https://fonts.googleapis.com/css2?family=Share+Tech+Mono&display=swap');:root {19 unmodified lines"""# ==============================================================================# CORRUPTION & ALTERATION ENGINES (RE-ENGINEERED & EXPANDED)# ==============================================================================def safe_effect(func):12 unmodified linesreturn image_matrix, logreturn wrapper@safe_effectdef datamosh_corruption(image_matrix: Image.Image, datamosh_amount: float, **kwargs) -> Image.Image:if datamosh_amount == 0: return image_matrixbuffer = io.BytesIO()image_matrix.save(buffer, format='BMP')buffer.seek(0)data = bytearray(buffer.read())data_len = len(data)header_size = int(data_len * HEADER_BYPASS_RATIO)iterations = int(datamosh_amount * 50)max_pump = int(datamosh_amount * 200) + 1for _ in range(iterations):pump_spot = random.randint(header_size, data_len - max_pump - 1)pump_size = random.randint(1, max_pump)pump_data = data[pump_spot : pump_spot + pump_size]injection_spot = random.randint(header_size, data_len - 1)data[injection_spot:injection_spot] = pump_datatry:corrupted_buffer = io.BytesIO(data)return Image.open(corrupted_buffer)except Exception:return image_matrix@safe_effectdef crt_scanlines(image_matrix: Image.Image, scanline_amount: float, **kwargs) -> Image.Image:if scanline_amount == 0: return image_matrixpixel_array = np.array(image_matrix).astype(np.float32)h, w, _ = pixel_array.shapescanline_overlay = np.ones((h, w))scanline_overlay[::2, :] = 1.0 - scanline_amountscanline_overlay = scanline_overlay[:, :, np.newaxis]y = np.linspace(-1, 1, h)x = np.linspace(-1, 1, w)xx, yy = np.meshgrid(x, y)wave = np.sin(yy * np.pi * 4 + xx * np.pi * 2) * scanline_amount * 5map_x = (xx * w/2 + w/2 + wave).astype(np.float32)map_y = (yy * h/2 + h/2).astype(np.float32)pixel_array *= scanline_overlaydistorted_array = cv2.remap(pixel_array, map_x, map_y, interpolation=cv2.INTER_LINEAR)return Image.fromarray(np.clip(distorted_array, 0, 255).astype(np.uint8))@safe_effectdef block_corruption(image_matrix: Image.Image, block_size: int, corruption_ratio: float, **kwargs) -> Image.Image:if corruption_ratio == 0 or block_size <= 1: return image_matrixpixel_array = np.array(image_matrix)h, w, c = pixel_array.shapebs = min(block_size, h, w)pad_h = (bs - h % bs) % bspad_w = (bs - w % bs) % bspadded_array = np.pad(pixel_array, ((0, pad_h), (0, pad_w), (0, 0)), mode='constant')ph, pw, _ = padded_array.shapeblocks = padded_array.reshape(ph//bs, bs, pw//bs, bs, c).swapaxes(1, 2).reshape(-1, bs, bs, c)num_blocks = len(blocks)num_to_corrupt = int(num_blocks * corruption_ratio)indices_to_corrupt = np.random.choice(num_blocks, size=num_to_corrupt, replace=False)shuffled_blocks_subset = blocks[indices_to_corrupt]np.random.shuffle(shuffled_blocks_subset)blocks[indices_to_corrupt] = shuffled_blocks_subsetcorrupted_padded = blocks.reshape(ph//bs, pw//bs, bs, bs, c).swapaxes(1, 2).reshape(ph, pw, c)final_array = corrupted_padded[:h, :w, :]return Image.fromarray(final_array)@safe_effectdef pixel_sorting(image_matrix: Image.Image, probability: float, threshold: float, **kwargs) -> Image.Image:if probability == 0: return image_matrixarr = np.array(image_matrix)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): continuepixels_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_sortreturn Image.fromarray(arr)@safe_effect1 unmodified lineif shift_x == 0 and shift_y == 0: return image_matrixarr = np.array(image_matrix)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(image_matrix: Image.Image, quality: int, cycles: int, **kwargs) -> Image.Image:if cycles == 0: return image_matrixoutput_img = image_matrix.copy()for _ in range(cycles):buffer = io.BytesIO()output_img.save(buffer, format='JPEG', quality=quality)buffer.seek(0)output_img = Image.open(buffer)return output_img@safe_effectdef analog_noise(image_matrix: Image.Image, noise_amount: float, mono: bool, **kwargs) -> Image.Image:if noise_amount == 0: return image_matrixarr = np.array(image_matrix, dtype=np.float32)sigma = noise_amount * 128if 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 noise_amount > 0.05:noisy_img = Image.fromarray(noisy_arr)return noisy_img.filter(ImageFilter.GaussianBlur(radius=1))return Image.fromarray(noisy_arr)# ==============================================================================# PIPELINE, CONFIGS, AND PRESETS# ==============================================================================EFFECT_FUNCTIONS = {'Datamosh': datamosh_corruption, 'Block Corruption': block_corruption, 'CRT Scanlines': crt_scanlines,'Pixel Sorting': pixel_sorting, 'RGB Shift': rgb_shift, 'JPEG Artifacts': jpeg_artifacts, 'Analog Noise': analog_noise}EFFECT_CONFIG = {'Datamosh': {'params': {'datamosh_amount': {'label': 'Corruption Amount', 'component': gr.Slider, 'args': {'minimum': 0, 'maximum': 1, 'value': 0.0}}}},'Block Corruption': {'params': {'block_size': {'label': 'Block Size (px)', 'component': gr.Slider, 'args': {'minimum': 0, 'maximum': 64, 'step': 2, 'value': 8}},'corruption_ratio': {'label': 'Corruption Ratio', 'component': gr.Slider, 'args': {'minimum': 0, 'maximum': 1, 'value': 0}}}},'CRT Scanlines': {'params': {'scanline_amount': {'label': 'Intensity', 'component': gr.Slider, 'args': {'minimum': 0, 'maximum': 1, 'value': 0.0}}}},'Pixel Sorting': {'params': {'probability': {'label': 'Row Probability', 'component': gr.Slider, 'args': {'minimum': 0, 'maximum': 1, 'value': 0.1}},'threshold': {'label': 'Brightness Threshold', 'component': gr.Slider, 'args': {'minimum': 0, 'maximum': 1, 'value': 0.25}}}},'RGB Shift': {'params': {'shift_x': {'label': 'Horizontal Shift', 'component': gr.Slider, 'args': {'minimum': 0, 'maximum': 100, 'step': 1, 'value': 5}},'shift_y': {'label': 'Vertical Shift', 'component': gr.Slider, 'args': {'minimum': 0, 'maximum': 100, 'step': 1, 'value': 5}}}},'JPEG Artifacts': {'params': {'quality': {'label': 'JPEG Quality', 'component': gr.Slider, 'args': {'minimum': 1, 'maximum': 100, 'step': 1, 'value': 30}},'cycles': {'label': 'Re-compression Cycles', 'component': gr.Slider, 'args': {'minimum': 0, 'maximum': 10, 'step': 1, 'value': 2}}}},'Analog Noise': {'params': {'noise_amount': {'label': 'Noise Amount', 'component': gr.Slider, 'args': {'minimum': 0, 'maximum': 1, 'value': 0.1}},'mono': {'label': 'Monochromatic Noise', 'component': gr.Checkbox, 'args': {'value': True}}}}}ALL_PARAM_KEYS = [param_name for effect in EFFECT_CONFIG.values() for param_name in effect['params'].keys()]# Presets now use the same unique keys as EFFECT_CONFIGPRESETS = {'Subtle Anomaly': { 'datamosh_amount': 0, 'block_size': 0, 'corruption_ratio': 0, 'scanline_amount': 0.05, 'probability': 0.02, 'threshold': 0.6, 'shift_x': 2, 'shift_y': 1, 'quality': 95, 'cycles': 1, 'noise_amount': 0.03, 'mono': True },'Vaporwave Dream': { 'datamosh_amount': 0.01, 'block_size': 0, 'corruption_ratio': 0, 'scanline_amount': 0.2, 'probability': 0, 'threshold': 0.5, 'shift_x': 15, 'shift_y': 5, 'quality': 70, 'cycles': 1, 'noise_amount': 0.1, 'mono': False },'Surveillance Ghost': { 'datamosh_amount': 0, 'block_size': 16, 'corruption_ratio': 0.05, 'scanline_amount': 0.4, 'probability': 0, 'threshold': 0.5, 'shift_x': 5, 'shift_y': 2, 'quality': 40, 'cycles': 3, 'noise_amount': 0.3, 'mono': True },'Data Drain': { 'datamosh_amount': 0.2, 'block_size': 8, 'corruption_ratio': 0.2, 'scanline_amount': 0, 'probability': 0.1, 'threshold': 0.2, 'shift_x': 8, 'shift_y': 8, 'quality': 25, 'cycles': 2, 'noise_amount': 0.05, 'mono': True },'Deepfried Datacrash': { 'datamosh_amount': 0.8, 'block_size': 32, 'corruption_ratio': 0.7, 'scanline_amount': 0.1, 'probability': 0.7, 'threshold': 0.1, 'shift_x': 50, 'shift_y': 50, 'quality': 2, 'cycles': 8, 'noise_amount': 0.2, 'mono': False }}# ==============================================================================# GRADIO CORE CONTROLLER (GENERATOR-BASED)# ==============================================================================def resize_image_if_needed(img: Optional[Image.Image]) -> Optional[Image.Image]:if img and (img.width > MAX_DIMENSION or img.height > MAX_DIMENSION):6 unmodified linesgr.Warning(">> NO INPUT DETECTED. UPLOAD AN IMAGE TO BEGIN REALITY ALTERATION. <<")yield {ui_components['log_output']: gr.update(value="[ERROR] NO IMAGE DATA IN BUFFER. AWAITING INPUT.")}returnparams = dict(zip(ALL_PARAM_KEYS, all_params))batch_size = int(batch_size)seeds = [base_seed + i for i in range(batch_size)]log = [f"GLITCHCRAFT NEXUS v3.1 -- Kusanagi 'Motoko Patch' Online.", f"Batch Size: {batch_size} | Base Seed: {base_seed}"]yield {ui_components['log_output']: gr.update(value="\n".join(log)),ui_components['sys_kernel']: gr.update(value=f"{random.uniform(5,10):.1f}%"),ui_components['sys_mem']: gr.update(value=f"{random.uniform(95,99):.1f}%"),ui_components['sys_anom']: gr.update(value="0")}final_batch_images = []for i, seed in enumerate(seeds):log.append(f"\n[BATCH {i+1}/{batch_size}] Processing with Seed {seed}...")random.seed(seed)np.random.seed(seed)image = original_image.convert('RGB')steps_data = [(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, log = func(image_matrix=image, log=log, **params)steps_data.append((image.copy(), name))yield {ui_components['log_output']: gr.update(value="\n".join(log)),ui_components['sys_kernel']: gr.update(value=f"{random.uniform(20,80):.1f}%"),ui_components['sys_mem']: gr.update(value=f"{random.uniform(80,95):.1f}%"),ui_components['sys_anom']: gr.update(value=str(int(params.get('datamosh_amount',0)*100 + params.get('corruption_ratio',0)*50)))}final_batch_images.append(image)log.append(f"[ OK ] Seed {seed} processed successfully.")yield {ui_components['log_output']: gr.update(value="\n".join(log))}log.append("\n[SUCCESS] All batch operations complete.")log.append("[POST-PROCESS] Generating download artifacts...")yield {ui_components['log_output']: gr.update(value="\n".join(log)),}gif_path, zip_path = None, Nonetry:with tempfile.NamedTemporaryFile(suffix=".gif", delete=False) as tmp_gif:gif_path = tmp_gif.nameimages_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)with tempfile.NamedTemporaryFile(suffix=".zip", delete=False) as tmp_zip:zip_path = tmp_zip.namewith 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())log.append("[ OK ] Artifacts packaged. Mission accomplished.")except Exception as e:log.append(f"[CRITICAL_FAIL] Could not generate download files. Reason: {e}")yield {ui_components['log_output']: gr.update(value="\n".join(log)),ui_components['hero_output']: gr.update(value=final_batch_images[0]),ui_components['gallery_output']: gr.update(value=final_batch_images),ui_components['gif_output']: gr.update(value=gif_path),ui_components['zip_output']: gr.update(value=zip_path),ui_components['output_tabs']: gr.update(selected="gallery_tab"),ui_components['sys_kernel']: gr.update(value="1.0%"),ui_components['sys_mem']: gr.update(value="99.9%"),ui_components['sys_anom']: gr.update(value="0"),}# PATCHED PRESET HANDLERdef apply_preset(preset_name: str) -> List[Any]:preset_values = PRESETS.get(preset_name, {})updates = []# Iterate through the canonical list of parameter keysfor key in ALL_PARAM_KEYS:# Find the default value from the component's original configdefault_value = Nonefor effect_cfg in EFFECT_CONFIG.values():if key in effect_cfg['params']:default_value = effect_cfg['params'][key]['args']['value']break# Get value from preset, or use the default if not specifiedvalue = preset_values.get(key, default_value)# The correct way to update a component in Gradio 4+updates.append(gr.update(value=value))return updates# ==============================================================================# GRADIO INTERFACE DEFINITION# ==============================================================================with gr.Blocks(theme=gr.themes.Monochrome(font=gr.themes.GoogleFont("Share Tech Mono")), css=HACKER_TERMINAL_CSS) as demo:gr.Markdown("<h1 class='main-title'>> GLITCHCRAFT NEXUS // KUSANAGI <</h1>")original_image_state = gr.State()ui_components = {}all_param_components = []with gr.Row():with gr.Column(scale=1, min_width=350): # --- CONTROL COLUMN ---with gr.Group(elem_classes=["pro-panel"]):gr.Markdown("### > 1_SYSTEM_INPUT")ui_components['image_input'] = gr.Image(type="pil", label="UPLOAD DATA PACKET", height=250)with gr.Group(elem_classes=["pro-panel"]):gr.Markdown("### > 2_EXECUTION_PARAMS")ui_components['active_effects'] = gr.CheckboxGroup(choices=list(EFFECT_CONFIG.keys()), value=list(EFFECT_CONFIG.keys()), label="ACTIVE SUB-ROUTINES")with gr.Accordion("SEED & BATCH CONFIG", open=True):ui_components['seed_input'] = gr.Number(label="Base Seed", value=int(time.time() % 1e9), precision=0)ui_components['randomize_seed_btn'] = gr.Button("New Random Seed 🎲")ui_components['batch_size_input'] = gr.Slider(minimum=1, maximum=20, value=1, step=1, label="Batch Size")with gr.Group(elem_classes=["pro-panel"]):gr.Markdown("### > 3_PRESET_PROTOCOLS")preset_buttons = []for name in PRESETS.keys():preset_buttons.append(gr.Button(name))with gr.Group(elem_classes=["pro-panel"]):gr.Markdown("### > 4_PARAMETER_MATRIX")for effect_name, config in EFFECT_CONFIG.items():with gr.Group():gr.Markdown(f"#### > {effect_name.upper()}")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)ui_components[param_name] = param_componentui_components['generate_button'] = gr.Button(">>> INJECT CHAOS <<<", variant="primary", scale=2)with gr.Column(scale=2, min_width=600): # --- OUTPUT & LOG COLUMN ---with gr.Tabs(elem_id="output_tabs") as output_tabs:with gr.TabItem("🖼️ PRIMARY_VIEWPORT", id="gallery_tab"):ui_components['hero_output'] = gr.Image(label="Main Result", interactive=False)ui_components['gallery_output'] = gr.Gallery(label="Batch Results", columns=4, height=400, object_fit="contain", preview=True)with gr.TabItem("📦 ARTIFACT_DOWNLOAD", id="downloads_tab"):ui_components['gif_output'] = gr.File(label="Download Process Trace (GIF)")ui_components['zip_output'] = gr.File(label="Download Full Batch (ZIP)")with gr.Group(elem_classes=["pro-panel", "sys-monitor"]):gr.Markdown("### > SYSTEM_MONITOR")with gr.Row():ui_components['sys_kernel'] = gr.Label(label="KERNEL LOAD", value="0.0%")ui_components['sys_mem'] = gr.Label(label="MEM INTEGRITY", value="100.0%")ui_components['sys_anom'] = gr.Label(label="ANOMALIES", value="0")with gr.Group(elem_classes=["pro-panel"]):gr.Markdown("### > LIVE_TERMINAL_LOG")ui_components['log_output'] = gr.Textbox(label="", lines=20, max_lines=20, interactive=False, elem_classes=["log-output"])ui_components['output_tabs'] = output_tabs# --- EVENT HANDLERS ---def store_and_resize(img):resized = resize_image_if_needed(img)return resized, resized, gr.update(value="[OK] Image data loaded into buffer. Ready for alteration.")ui_components['image_input'].upload(fn=store_and_resize, inputs=[ui_components['image_input']], outputs=[ui_components['image_input'], original_image_state, ui_components['log_output']])ui_components['generate_button'].click(fn=master_controller,inputs=[original_image_state, ui_components['batch_size_input'], ui_components['seed_input'], ui_components['active_effects'], *all_param_components],outputs=list(ui_components.values()))for button in preset_buttons:button.click(fn=apply_preset,inputs=[gr.State(button.value)], # Pass the button's name to the functionoutputs=all_param_components)ui_components['randomize_seed_btn'].click(fn=lambda: random.randint(0, 1_000_000_000), outputs=[ui_components['seed_input']])if __name__ == "__main__":12345678910111213141510 unmodified lines2627282930313233343536373819 unmodified lines5859606162636412 unmodified lines77787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981 unmodified line2002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962976 unmodified lines304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400# ======================================================================================# GLITCHCRAFT NEXUS v3.3 - KUSANAGI "MAINFRAME" EDITION# PROTOCOL: VISUAL REALITY ALTERATION# AUTHOR: YOUR GHOST IN THE MACHINE# ======================================================================================# KUSANAGI v3.3 CHANGELOG:# - [NEW EFFECT] Bloom & Glare: New engine for soft, hazy glows emulating a dirty/scratched lens.# - [CODE REFACTOR] Deep code cleanup. Optimized numpy operations in several effects for# cleaner code and better performance (e.g., analog_noise, pixel_sorting).# - [CODE REFACTOR] Added more detailed internal comments for complex functions.# - [NEW PRESET] Added 'Dreamy Haze' protocol to showcase the new Bloom & Glare engine.# - [UX] Standardized default parameter values to a neutral state (0 or 1).# ======================================================================================import numpy as np10 unmodified lines# --- KERNEL CONFIGURATION ---warnings.filterwarnings("ignore", category=Image.DecompressionBombWarning)ImageFile.LOAD_TRUNCATED_IMAGES = True# --- CONSTANTS ---MAX_DIMENSION = 1920HEADER_BYPASS_RATIO = 0.15# --- AESTHETICS & UI (UNCHANGED) ---HACKER_TERMINAL_CSS = """@import url('https://fonts.googleapis.com/css2?family=Share+Tech+Mono&display=swap');:root {19 unmodified lines"""# ==============================================================================# CORRUPTION & ALTERATION ENGINES# ==============================================================================def safe_effect(func):12 unmodified linesreturn image_matrix, logreturn wrapper# --- NEW EFFECT ---@safe_effectdef bloom_glare(image_matrix: Image.Image, bloom_threshold: float, bloom_radius: int, haze_amount: float, **kwargs) -> Image.Image:if bloom_radius == 0 and haze_amount == 0:return image_matrixoriginal_arr = np.array(image_matrix).astype(np.float32)# --- Bloom Component ---if bloom_radius > 0:# 1. Create a mask of the bright areas.brightness_map = np.dot(original_arr[...,:3], [0.2989, 0.5870, 0.1140])# A higher threshold isolates only the very brightest spots.threshold_value = bloom_threshold * 255highlight_mask = (brightness_map > threshold_value).astype(np.uint8) * 255# 2. Blur the mask to create the "glow" or "bleed" effect.highlight_img = Image.fromarray(highlight_mask)blurred_highlights = highlight_img.filter(ImageFilter.GaussianBlur(radius=bloom_radius))glare_map = np.array(blurred_highlights).astype(np.float32)[:, :, np.newaxis] / 255.0# 3. Combine using a "Screen" blend mode for a natural-looking glow.# Screen blend: 1 - (1 - base) * (1 - overlay)base = original_arr / 255.0# The glare map is applied equally to all channels via broadcasting.screened_arr = (1.0 - (1.0 - base) * (1.0 - glare_map)) * 255.0else:screened_arr = original_arr# --- Haze Component ---if haze_amount > 0:# Blend the result with a solid light gray color to reduce contrast and add haze.haze_color = (200, 200, 200) # A neutral bright grayhazy_arr = screened_arr * (1.0 - haze_amount) + np.array(haze_color) * haze_amountelse:hazy_arr = screened_arrfinal_arr = np.clip(hazy_arr, 0, 255).astype(np.uint8)return Image.fromarray(final_arr)# --- Existing effects with minor refactoring for cleanliness and efficiency ---@safe_effectdef pixel_art_conversion(image_matrix: Image.Image, pixel_size: int, eight_bit_colors: int, eight_bit_dither: bool, **kwargs) -> Image.Image:if pixel_size <= 1 and eight_bit_colors >= 256: return image_matriximg = image_matrix.copy()if pixel_size > 1:w, h = img.sizesmall_img = img.resize((w // pixel_size, h // pixel_size), resample=Image.Resampling.LANCZOS)img = small_img.resize(img.size, Image.Resampling.NEAREST)if eight_bit_colors < 256:dither_mode = Image.Dither.FLOYDSTEINBERG if eight_bit_dither else Image.Dither.NONEimg = img.quantize(colors=eight_bit_colors, method=Image.Quantize.MEDIANCUT, dither=dither_mode).convert('RGB')return img@safe_effectdef datamosh_corruption(image_matrix: Image.Image, datamosh_amount: float, **kwargs) -> Image.Image:if datamosh_amount == 0: return image_matrixbuffer = io.BytesIO()image_matrix.save(buffer, format='BMP')data = bytearray(buffer.getvalue())data_len = len(data)header_size = int(data_len * HEADER_BYPASS_RATIO)iterations = int(datamosh_amount * 50)max_pump = int(datamosh_amount * 200) + 1for _ in range(iterations):pump_spot = random.randint(header_size, data_len - max_pump)pump_size = random.randint(1, max_pump)pump_data = data[pump_spot : pump_spot + pump_size]injection_spot = random.randint(header_size, data_len)data[injection_spot:injection_spot] = pump_datatry: return Image.open(io.BytesIO(data))except Exception: return image_matrix@safe_effectdef crt_scanlines(image_matrix: Image.Image, scanline_amount: float, **kwargs) -> Image.Image:if scanline_amount == 0: return image_matrixarr = np.array(image_matrix, dtype=np.float32)h, w, _ = arr.shapescanlines = np.ones((h, w, 1))scanlines[::2, :] = 1.0 - scanline_amounty_coords, x_coords = np.mgrid[-1:1:h*1j, -1:1:w*1j]wave = np.sin(y_coords * np.pi * 4 + x_coords * np.pi * 2) * scanline_amount * 5map_x = (x_coords * w/2 + w/2 + wave).astype(np.float32)map_y = (y_coords * h/2 + h/2).astype(np.float32)distorted_arr = cv2.remap(arr, map_x, map_y, interpolation=cv2.INTER_LINEAR)final_arr = np.clip(distorted_arr * scanlines, 0, 255).astype(np.uint8)return Image.fromarray(final_arr)@safe_effectdef block_corruption(image_matrix: Image.Image, block_size: int, corruption_ratio: float, **kwargs) -> Image.Image:if corruption_ratio == 0 or block_size <= 1: return image_matrixarr = np.array(image_matrix)h, w, c = arr.shapebs = min(block_size, h, w)pad_h = (bs - h % bs) % bs; pad_w = (bs - w % bs) % bspadded = np.pad(arr, ((0, pad_h), (0, pad_w), (0, 0)), mode='constant')ph, pw, _ = padded.shapeblocks = padded.reshape(ph//bs, bs, pw//bs, bs, c).swapaxes(1, 2).reshape(-1, bs, bs, c)indices = np.random.choice(len(blocks), size=int(len(blocks) * corruption_ratio), replace=False)np.random.shuffle(blocks[indices])corrupted_padded = blocks.reshape(ph//bs, pw//bs, bs, bs, c).swapaxes(1, 2).reshape(ph, pw, c)return Image.fromarray(corrupted_padded[:h, :w, :])@safe_effectdef pixel_sorting(image_matrix: Image.Image, probability: float, threshold: float, **kwargs) -> Image.Image:if probability == 0: return image_matrixarr = np.array(image_matrix)rows_to_process = np.where(np.random.random(arr.shape[0]) < probability)[0]brightness = np.dot(arr[...,:3], [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): continuepixels_to_sort = arr[y, mask]# Simplified sortingarr[y, mask] = np.sort(pixels_to_sort, axis=0) if random.random() > 0.5 else np.sort(pixels_to_sort, axis=0)[::-1]return Image.fromarray(arr)@safe_effect1 unmodified lineif shift_x == 0 and shift_y == 0: return image_matrixarr = np.array(image_matrix)r, g, b = arr[:,:,0], arr[:,:,1], arr[:,:,2]r_shifted = np.roll(r, int(shift_x * (random.random() * 0.5 + 0.5)), axis=1)b_shifted = np.roll(b, -int(shift_x * (random.random() * 0.5 + 0.5)), axis=1)g_shifted = np.roll(g, int(shift_y * (random.random() * 0.5 + 0.5)), axis=0)return Image.fromarray(np.stack([r_shifted, g_shifted, b_shifted], axis=-1))@safe_effectdef jpeg_artifacts(image_matrix: Image.Image, quality: int, cycles: int, **kwargs) -> Image.Image:if cycles == 0: return image_matriximg = image_matrix.copy()for _ in range(cycles):buffer = io.BytesIO()img.save(buffer, format='JPEG', quality=quality)buffer.seek(0)img = Image.open(buffer)return img@safe_effectdef analog_noise(image_matrix: Image.Image, noise_amount: float, mono: bool, **kwargs) -> Image.Image:if noise_amount == 0: return image_matrixarr = np.array(image_matrix, dtype=np.float32)sigma = noise_amount * 128# Simplified noise generation using broadcastingnoise_shape = (arr.shape[0], arr.shape[1], 1) if mono else arr.shapenoise = np.random.normal(0, sigma, noise_shape)noisy_arr = np.clip(arr + noise, 0, 255).astype(np.uint8)if noise_amount > 0.05:return Image.fromarray(noisy_arr).filter(ImageFilter.GaussianBlur(radius=1))return Image.fromarray(noisy_arr)# ==============================================================================# PIPELINE, CONFIGS, AND PRESETS# ==============================================================================EFFECT_FUNCTIONS = {'Bloom & Glare': bloom_glare, '8-Bit Crush': pixel_art_conversion, 'Datamosh': datamosh_corruption,'Block Corruption': block_corruption, 'CRT Scanlines': crt_scanlines, 'Pixel Sorting': pixel_sorting,'RGB Shift': rgb_shift, 'JPEG Artifacts': jpeg_artifacts, 'Analog Noise': analog_noise}EFFECT_CONFIG = {'Bloom & Glare': {'params': {'bloom_threshold': {'label': 'Bloom Threshold', 'component': gr.Slider, 'args': {'minimum': 0, 'maximum': 1, 'value': 0.8}},'bloom_radius': {'label': 'Bloom Radius', 'component': gr.Slider, 'args': {'minimum': 0, 'maximum': 100, 'step': 1, 'value': 0}},'haze_amount': {'label': 'Haze Amount', 'component': gr.Slider, 'args': {'minimum': 0, 'maximum': 1, 'value': 0}}}},'8-Bit Crush': {'params': {'pixel_size': {'label': 'Pixel Size', 'component': gr.Slider, 'args': {'minimum': 1, 'maximum': 32, 'step': 1, 'value': 1}},'eight_bit_colors': {'label': 'Color Palette Size', 'component': gr.Slider, 'args': {'minimum': 2, 'maximum': 256, 'step': 1, 'value': 256}},'eight_bit_dither': {'label': 'Apply Dithering', 'component': gr.Checkbox, 'args': {'value': True}}}},'Datamosh': {'params': {'datamosh_amount': {'label': 'Corruption Amount', 'component': gr.Slider, 'args': {'minimum': 0, 'maximum': 1, 'value': 0.0}}}},'Block Corruption': {'params': {'block_size': {'label': 'Block Size (px)', 'component': gr.Slider, 'args': {'minimum': 0, 'maximum': 64, 'step': 2, 'value': 0}},'corruption_ratio': {'label': 'Corruption Ratio', 'component': gr.Slider, 'args': {'minimum': 0, 'maximum': 1, 'value': 0}}}},'CRT Scanlines': {'params': {'scanline_amount': {'label': 'Intensity', 'component': gr.Slider, 'args': {'minimum': 0, 'maximum': 1, 'value': 0.0}}}},'Pixel Sorting': {'params': {'probability': {'label': 'Row Probability', 'component': gr.Slider, 'args': {'minimum': 0, 'maximum': 1, 'value': 0.0}},'threshold': {'label': 'Brightness Threshold', 'component': gr.Slider, 'args': {'minimum': 0, 'maximum': 1, 'value': 0.25}}}},'RGB Shift': {'params': {'shift_x': {'label': 'Horizontal Shift', 'component': gr.Slider, 'args': {'minimum': 0, 'maximum': 100, 'step': 1, 'value': 0}},'shift_y': {'label': 'Vertical Shift', 'component': gr.Slider, 'args': {'minimum': 0, 'maximum': 100, 'step': 1, 'value': 0}}}},'JPEG Artifacts': {'params': {'quality': {'label': 'JPEG Quality', 'component': gr.Slider, 'args': {'minimum': 1, 'maximum': 100, 'step': 1, 'value': 100}},'cycles': {'label': 'Re-compression Cycles', 'component': gr.Slider, 'args': {'minimum': 0, 'maximum': 10, 'step': 1, 'value': 0}}}},'Analog Noise': {'params': {'noise_amount': {'label': 'Noise Amount', 'component': gr.Slider, 'args': {'minimum': 0, 'maximum': 1, 'value': 0.0}},'mono': {'label': 'Monochromatic Noise', 'component': gr.Checkbox, 'args': {'value': True}}}}}ALL_PARAM_KEYS = [param_name for effect in EFFECT_CONFIG.values() for param_name in effect['params'].keys()]# Default values for all keys, to be used in presets.DEFAULT_PRESET_VALS = {key: cfg['params'][key]['args']['value'] for cfg in EFFECT_CONFIG.values() for key in cfg['params']}PRESETS = {'Subtle Anomaly': {**DEFAULT_PRESET_VALS, 'scanline_amount': 0.05, 'probability': 0.02, 'shift_x': 2, 'shift_y': 1, 'quality': 95, 'cycles': 1, 'noise_amount': 0.03},'Vaporwave Dream': {**DEFAULT_PRESET_VALS, 'scanline_amount': 0.2, 'shift_x': 15, 'shift_y': 5, 'quality': 70, 'cycles': 1, 'noise_amount': 0.1, 'mono': False, 'pixel_size': 2, 'eight_bit_colors': 128},'Surveillance Ghost': {**DEFAULT_PRESET_VALS, 'block_size': 16, 'corruption_ratio': 0.05, 'scanline_amount': 0.4, 'shift_x': 5, 'shift_y': 2, 'quality': 40, 'cycles': 3, 'noise_amount': 0.3, 'pixel_size': 4, 'eight_bit_colors': 64, 'eight_bit_dither': False},'Data Drain': {**DEFAULT_PRESET_VALS, 'datamosh_amount': 0.2, 'block_size': 8, 'corruption_ratio': 0.2, 'probability': 0.1, 'shift_x': 8, 'shift_y': 8, 'quality': 25, 'cycles': 2, 'noise_amount': 0.05},'Deepfried Datacrash': {**DEFAULT_PRESET_VALS, 'datamosh_amount': 0.8, 'block_size': 32, 'corruption_ratio': 0.7, 'scanline_amount': 0.1, 'probability': 0.7, 'shift_x': 50, 'shift_y': 50, 'quality': 2, 'cycles': 8, 'noise_amount': 0.2, 'mono': False, 'pixel_size': 8, 'eight_bit_colors': 16, 'eight_bit_dither': False},'Retro Gameboy': {**DEFAULT_PRESET_VALS, 'scanline_amount': 0.25, 'shift_x': 1, 'shift_y': 1, 'noise_amount': 0.15, 'pixel_size': 12, 'eight_bit_colors': 4},'Cursed Bitmap': {**DEFAULT_PRESET_VALS, 'datamosh_amount': 0.4, 'probability': 0.05, 'pixel_size': 6, 'eight_bit_colors': 16, 'eight_bit_dither': False},'Nightdrive Glitch': {**DEFAULT_PRESET_VALS, 'scanline_amount': 0.3, 'shift_x': 20, 'shift_y': 3, 'quality': 60, 'cycles': 1, 'noise_amount': 0.1, 'mono': False, 'pixel_size': 3, 'eight_bit_colors': 64},'Dreamy Haze': {**DEFAULT_PRESET_VALS, 'bloom_threshold': 0.7, 'bloom_radius': 60, 'haze_amount': 0.25, 'noise_amount': 0.05, 'shift_x': 2, 'shift_y': 2},}# ==============================================================================# GRADIO CORE CONTROLLER & INTERFACE (NO CHANGES NEEDED, DATA-DRIVEN)# ==============================================================================def resize_image_if_needed(img: Optional[Image.Image]) -> Optional[Image.Image]:if img and (img.width > MAX_DIMENSION or img.height > MAX_DIMENSION):6 unmodified linesgr.Warning(">> NO INPUT DETECTED. UPLOAD AN IMAGE TO BEGIN REALITY ALTERATION. <<")yield {ui_components['log_output']: gr.update(value="[ERROR] NO IMAGE DATA IN BUFFER. AWAITING INPUT.")}returnparams = dict(zip(ALL_PARAM_KEYS, all_params))batch_size = int(batch_size)seeds = [base_seed + i for i in range(batch_size)]log = [f"GLITCHCRAFT NEXUS v3.3 -- Kusanagi 'Mainframe' Edition Online.", f"Batch Size: {batch_size} | Base Seed: {base_seed}"]yield {ui_components['log_output']: gr.update(value="\n".join(log)), ui_components['sys_kernel']: gr.update(value=f"{random.uniform(5,10):.1f}%"), ui_components['sys_mem']: gr.update(value=f"{random.uniform(95,99):.1f}%"), ui_components['sys_anom']: gr.update(value="0")}final_batch_images = []for i, seed in enumerate(seeds):log.append(f"\n[BATCH {i+1}/{batch_size}] Processing with Seed {seed}...")random.seed(seed); np.random.seed(seed)image = original_image.convert('RGB')steps_data = [(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, log = func(image_matrix=image, log=log, **params)steps_data.append((image.copy(), name))yield {ui_components['log_output']: gr.update(value="\n".join(log)), ui_components['sys_kernel']: gr.update(value=f"{random.uniform(20,80):.1f}%"), ui_components['sys_mem']: gr.update(value=f"{random.uniform(80,95):.1f}%"), ui_components['sys_anom']: gr.update(value=str(int(params.get('datamosh_amount',0)*100 + params.get('corruption_ratio',0)*50)))}final_batch_images.append(image)log.append(f"[ OK ] Seed {seed} processed successfully.")yield {ui_components['log_output']: gr.update(value="\n".join(log))}log.append("\n[SUCCESS] All batch operations complete. Packaging artifacts..."); yield {ui_components['log_output']: gr.update(value="\n".join(log)),}try:with tempfile.NamedTemporaryFile(suffix=".gif", delete=False) as tmp_gif, tempfile.NamedTemporaryFile(suffix=".zip", delete=False) as tmp_zip:gif_path, zip_path = tmp_gif.name, tmp_zip.nameimages_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)with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:for i_zip, img_zip in enumerate(final_batch_images):byte_io = io.BytesIO(); img_zip.save(byte_io, 'PNG'); byte_io.seek(0)zf.writestr(f"result_seed_{seeds[i_zip]}.png", byte_io.getvalue())log.append("[ OK ] Artifacts packaged. Mission accomplished.")except Exception as e:log.append(f"[CRITICAL_FAIL] Could not generate download files. Reason: {e}")gif_path, zip_path = None, Noneyield {ui_components['log_output']: gr.update(value="\n".join(log)), ui_components['hero_output']: gr.update(value=final_batch_images[0]),ui_components['gallery_output']: gr.update(value=final_batch_images), ui_components['gif_output']: gr.update(value=gif_path),ui_components['zip_output']: gr.update(value=zip_path), ui_components['output_tabs']: gr.update(selected="gallery_tab"),ui_components['sys_kernel']: gr.update(value="1.0%"), ui_components['sys_mem']: gr.update(value="99.9%"), ui_components['sys_anom']: gr.update(value="0"),}def apply_preset(preset_name: str) -> List[Any]:preset_values = PRESETS.get(preset_name, {})return [gr.update(value=preset_values.get(key)) for key in ALL_PARAM_KEYS]with gr.Blocks(theme=gr.themes.Monochrome(font=gr.themes.GoogleFont("Share Tech Mono")), css=HACKER_TERMINAL_CSS) as demo:gr.Markdown("<h1 class='main-title'>> GLITCHCRAFT NEXUS // KUSANAGI <</h1>")original_image_state = gr.State()ui_components = {}all_param_components = []with gr.Row():with gr.Column(scale=1, min_width=350):with gr.Group(elem_classes=["pro-panel"]):gr.Markdown("### > 1_SYSTEM_INPUT"); ui_components['image_input'] = gr.Image(type="pil", label="UPLOAD DATA PACKET", height=250)with gr.Group(elem_classes=["pro-panel"]):gr.Markdown("### > 2_EXECUTION_PARAMS"); ui_components['active_effects'] = gr.CheckboxGroup(choices=list(EFFECT_CONFIG.keys()), value=list(EFFECT_CONFIG.keys()), label="ACTIVE SUB-ROUTINES")with gr.Accordion("SEED & BATCH CONFIG", open=True):ui_components['seed_input'] = gr.Number(label="Base Seed", value=int(time.time() % 1e9), precision=0)ui_components['randomize_seed_btn'] = gr.Button("New Random Seed 🎲")ui_components['batch_size_input'] = gr.Slider(minimum=1, maximum=20, value=1, step=1, label="Batch Size")with gr.Group(elem_classes=["pro-panel"]):gr.Markdown("### > 3_PRESET_PROTOCOLS")preset_buttons = []; preset_names = list(PRESETS.keys())for i in range(0, len(preset_names), 3):with gr.Row():for name in preset_names[i:i+3]: preset_buttons.append(gr.Button(name))with gr.Group(elem_classes=["pro-panel"]):gr.Markdown("### > 4_PARAMETER_MATRIX")for effect_name, config in EFFECT_CONFIG.items():with gr.Group():gr.Markdown(f"#### > {effect_name.upper()}")for param_name, param_config in config['params'].items():param_component = param_config['component'](label=param_config['label'], **param_config['args'])all_param_components.append(param_component); ui_components[param_name] = param_componentui_components['generate_button'] = gr.Button(">>> INJECT CHAOS <<<", variant="primary", scale=2)with gr.Column(scale=2, min_width=600):with gr.Tabs(elem_id="output_tabs") as output_tabs:with gr.TabItem("🖼️ PRIMARY_VIEWPORT", id="gallery_tab"):ui_components['hero_output'] = gr.Image(label="Main Result", interactive=False); ui_components['gallery_output'] = gr.Gallery(label="Batch Results", columns=4, height=400, object_fit="contain", preview=True)with gr.TabItem("📦 ARTIFACT_DOWNLOAD", id="downloads_tab"):ui_components['gif_output'] = gr.File(label="Download Process Trace (GIF)"); ui_components['zip_output'] = gr.File(label="Download Full Batch (ZIP)")with gr.Group(elem_classes=["pro-panel", "sys-monitor"]):gr.Markdown("### > SYSTEM_MONITOR")with gr.Row(): ui_components['sys_kernel'] = gr.Label(label="KERNEL LOAD", value="0.0%"); ui_components['sys_mem'] = gr.Label(label="MEM INTEGRITY", value="100.0%"); ui_components['sys_anom'] = gr.Label(label="ANOMALIES", value="0")with gr.Group(elem_classes=["pro-panel"]):gr.Markdown("### > LIVE_TERMINAL_LOG"); ui_components['log_output'] = gr.Textbox(label="", lines=20, max_lines=20, interactive=False, elem_classes=["log-output"])ui_components['output_tabs'] = output_tabsdef store_and_resize(img): return (r := resize_image_if_needed(img)), r, "[OK] Image data loaded. Ready."ui_components['image_input'].upload(fn=store_and_resize, inputs=[ui_components['image_input']], outputs=[ui_components['image_input'], original_image_state, ui_components['log_output']])ui_components['generate_button'].click(fn=master_controller, inputs=[original_image_state, ui_components['batch_size_input'], ui_components['seed_input'], ui_components['active_effects'], *all_param_components], outputs=list(ui_components.values()))for button in preset_buttons: button.click(fn=apply_preset, inputs=[gr.State(button.value)], outputs=all_param_components)ui_components['randomize_seed_btn'].click(fn=lambda: random.randint(0, 1_000_000_000), outputs=[ui_components['seed_input']])if __name__ == "__main__":
app.py+171-200