Update app.py
Browse files123451 unmodified line789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687882 unmodified lines91929394959697988 unmodified lines10710810911011111211311411511611711811912012112212312412512612712834 unmodified lines1631641651661671681691701711721731741751761771781791801813 unmodified lines1851861871881891901911921931941951961971981992002012022032042052062 unmodified lines2092102112122132142152162172182192201 unmodified line2222232242252262272282292302312322332342352362372382392402412422432442452462478 unmodified lines256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307import numpy as npfrom PIL import Imageimport ioimport zipfileimport random1 unmodified lineimport warningsimport gradio as grfrom typing import List, Tuple, Dict, Any, Optionalimport time# Ignore specific Pillow warnings for large imageswarnings.filterwarnings("ignore", category=Image.DecompressionBombWarning)# ==============================================================================# AESTHETICS V3 - "Cyberpunk Pro" Theme (Refined for Gradio 4 stable)# ==============================================================================CUSTOM_CSS = """@import url('https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;700&display=swap');/* === Main Theme & Background === */body, .gradio-container {font-family: 'IBM Plex Mono', monospace;background: linear-gradient(135deg, #0f0c29 0%, #302b63 50%, #24243e 100%);color: #e0e0e0;}/* === Main Title Styling === */.main-title {text-align: center;font-size: 3rem !important;font-weight: 700;background: -webkit-linear-gradient(45deg, #ff00ff, #00ffff);-webkit-background-clip: text;-webkit-text-fill-color: transparent;padding-bottom: 10px;}/* === Professional Panel Styling (Glassmorphism) for gr.Group === */.pro-panel {background-color: rgba(20, 20, 40, 0.6) !important;border: 1px solid rgba(255, 255, 255, 0.1) !important;border-radius: 16px !important;box-shadow: 0 8px 32px 0 rgba(0, 0, 0, 0.37) !important;backdrop-filter: blur(10px) !important;-webkit-backdrop-filter: blur(10px) !important;padding: 15px !important;}/* === Interactive Button Styling with Glow Effect === */.gr-button {background: linear-gradient(90deg, #da22ff, #9733ee) !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 10px rgba(218, 34, 255, 0.4);}.gr-button:hover {transform: scale(1.05) !important;box-shadow: 0 0 25px rgba(218, 34, 255, 0.8) !important;}/* === Tab & Gallery Styling === */.tabs > .tab-nav > button.selected {background: #9733ee !important;color: white !important;border-bottom: 2px solid #ff00ff !important;}.gr-gallery > .preview > img {border-radius: 10px !important;transition: transform 0.3s cubic-bezier(0.25, 0.8, 0.25, 1) !important;box-shadow: 0 4px 15px rgba(0,0,0,0.4);}.gr-gallery > .preview > img:hover {transform: scale(1.08) rotate(2deg) !important;z-index: 10;box-shadow: 0 8px 30px rgba(255,0,255,0.5);}"""# ==============================================================================# CORE GLITCH EFFECT FUNCTIONS (Unchanged, already optimized)# ==============================================================================def pixel_sorting(img: Image.Image, intensity: float) -> Image.Image:if intensity == 0: return imgarr = np.array(img)2 unmodified linesrows_to_process = np.where(np.random.random(height) < intensity)[0]for y in rows_to_process:sorted_indices = np.argsort(brightness[y])if random.random() > 0.5: arr[y] = arr[y, sorted_indices]else: arr[y] = arr[y, sorted_indices[::-1]]return Image.fromarray(arr)def rgb_shift(img: Image.Image, intensity: float) -> Image.Image:8 unmodified linesif random.random() < intensity: channels[1] = np.roll(channels[1], shift_y, axis=0)return Image.fromarray(cv2.merge(channels))def datamosh(img: Image.Image, intensity: float) -> Image.Image:if intensity == 0: return imgquality = max(1, min(100, int(15 - intensity * 12)))try: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.05 * intensity)indices = np.random.randint(header_size, len(data) - 1, size=corruption_amount)for idx in indices: data[idx] = random.randint(0, 255)return Image.open(io.BytesIO(data))except Exception:return imgdef tile_glitch(img: Image.Image, intensity: float, tile_size: int) -> Image.Image:if intensity == 0: return imgarr = np.array(img)34 unmodified lines"Scanline Effect": scanline_effect}def create_gif_from_bytes(frames: List[Image.Image], max_size: int = 600) -> Optional[io.BytesIO]:if not frames: return Nonebase_width, base_height = frames[0].sizescale = min(1.0, max_size / max(base_width, base_height))if scale < 1.0:new_size = (int(base_width * scale), int(base_height * scale))frames = [frame.resize(new_size, Image.Resampling.LANCZOS) for frame in frames]gif_bytes = io.BytesIO()frames[0].save(gif_bytes, format='GIF', save_all=True, append_images=frames[1:], duration=300, loop=0, optimize=True)gif_bytes.seek(0)return gif_bytesdef create_zip_from_bytes(steps: List[Tuple[Image.Image, str]]) -> io.BytesIO:zip_bytes = io.BytesIO()with zipfile.ZipFile(zip_bytes, 'w', zipfile.ZIP_DEFLATED) as zipf:for i, (img, title) in enumerate(steps):3 unmodified linesfilename = f"step_{i:02d}_{title.replace(' ', '_')}.png"zipf.writestr(filename, img_bytes.getvalue())zip_bytes.seek(0)return zip_bytesdef run_glitch_pipeline(image: Image.Image,active_effects: List[str],params: Dict[str, Any]) -> Tuple[Image.Image, List[Tuple[Image.Image, str]]]:if image is None:placeholder = Image.new('RGB', (512, 512), color = '#0f0c29')return placeholder, [(placeholder, "Upload an image to start")]if image.mode != 'RGB': image = image.convert('RGB')steps = [(image.copy(), "Original")]current_img = image.copy()for effect_name in active_effects:if effect_name in EFFECT_MAP:func = EFFECT_MAP[effect_name]2 unmodified lineselse:param_key = f"{effect_name.lower().replace(' ', '_')}_intensity"current_img = func(current_img, params[param_key])steps.append((current_img.copy(), effect_name))return current_img, steps# ==============================================================================# GRADIO INTERFACE - V3 (Stable and Refined)# ==============================================================================with gr.Blocks(theme=gr.themes.Default(), css=CUSTOM_CSS) as demo:gr.Markdown("<h1 class='main-title'>G L I T C H / A R T / S T U D I O</h1>")1 unmodified lineshared_steps = gr.State([])with gr.Row():# --- LEFT COLUMN: CONTROLS ---with gr.Column(scale=1):with gr.Group(elem_classes=["pro-panel"]):image_input = gr.Image(type="pil", label="π· UPLOAD IMAGE", height=300)active_effects = gr.CheckboxGroup(choices=list(EFFECT_MAP.keys()),value=list(EFFECT_MAP.keys()),label="ποΈ ACTIVE EFFECTS")with gr.Group(elem_classes=["pro-panel"]):with gr.Accordion("βοΈ FINE-TUNE PARAMETERS", open=True):pixel_sort_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_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="Tile Size")# --- RIGHT COLUMN: OUTPUTS ---with gr.Column(scale=2):with gr.Group(elem_classes=["pro-panel"]):with gr.Tabs() as output_tabs:8 unmodified linesgenerate_button = gr.Button("π GENERATE FINAL ART & DOWNLOADS")# --- Live Preview Logic ---def update_live_preview(image, effects, ps, rgbs, dm, sl, tgi, ts):params = {"pixel_sorting_intensity": ps, "rgb_shift_intensity": rgbs,"datamosh_intensity": dm, "scanline_effect_intensity": sl, # Using the general name"tile_glitch_intensity": tgi, "tile_size": int(ts)}# Final consistency check for scanline param keyparams["scanline_effect_intensity"] = slfinal_image, steps_data = run_glitch_pipeline(image, effects, params)return final_image, steps_data# --- Final Generation Logic ---def generate_final_assets(steps_data):if not steps_data or len(steps_data) <= 1:gr.Warning("No effects applied or no image loaded. Cannot generate assets.")return None, None, [], gr.Tabs(selected="preview_tab")step_images = [img for img, _ in steps_data]# Create files in memorygif_bytes = create_gif_from_bytes(step_images)zip_bytes = create_zip_from_bytes(steps_data)gallery_items = [(img, title) for img, title in steps_data]gr.Info("β Success! Your art is ready in the 'Gallery' and 'Downloads' tabs.")return gif_bytes, zip_bytes, gallery_items, gr.Tabs(selected="gallery_tab")# --- Event Listeners ---controls = [image_input, active_effects, pixel_sort_intensity, rgb_shift_intensity,datamosh_intensity, scanline_intensity, tile_glitch_intensity, tile_size]for control in controls:control.change(fn=update_live_preview,inputs=controls,outputs=[final_output, shared_steps],queue=True)generate_button.click(fn=generate_final_assets,inputs=[shared_steps],outputs=[gif_output, zip_output, gallery_output, output_tabs])123451 unmodified line78910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576772 unmodified lines808182838485868 unmodified lines959697989910034 unmodified lines1351361371381391401411421431441451461471481491501511521531541551561571581591603 unmodified lines1641651661671681691701711721731741751761771781791801811821831841851861871882 unmodified lines1911921931941951961971981992002012021 unmodified line2042052062072082092102112122132142152162172182192202212222238 unmodified lines232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274import numpy as npfrom PIL import Image, ImageFileimport ioimport zipfileimport random1 unmodified lineimport warningsimport gradio as grfrom typing import List, Tuple, Dict, Any, Optional# --- Configuration for Robustness ---# Ignore specific Pillow warnings for large imageswarnings.filterwarnings("ignore", category=Image.DecompressionBombWarning)# Allow loading of truncated/corrupted images from datamosh, a key part of the fix.ImageFile.LOAD_TRUNCATED_IMAGES = True# ==============================================================================# AESTHETICS - "Cyberpunk Pro" Theme (Stable & Refined)# ==============================================================================CUSTOM_CSS = """@import url('https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;700&display=swap');body, .gradio-container { font-family: 'IBM Plex Mono', monospace; background: linear-gradient(135deg, #0f0c29 0%, #302b63 50%, #24243e 100%); color: #e0e0e0; }.main-title { text-align: center; font-size: 3rem !important; font-weight: 700; background: -webkit-linear-gradient(45deg, #ff00ff, #00ffff); -webkit-background-clip: text; -webkit-text-fill-color: transparent; padding-bottom: 10px; }.pro-panel { background: rgba(20, 20, 40, 0.6) !important; border: 1px solid rgba(255, 255, 255, 0.1) !important; border-radius: 16px !important; box-shadow: 0 8px 32px 0 rgba(0, 0, 0, 0.37) !important; backdrop-filter: blur(10px) !important; -webkit-backdrop-filter: blur(10px) !important; padding: 15px !important; }.gr-button { background: linear-gradient(90deg, #da22ff, #9733ee) !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 10px rgba(218, 34, 255, 0.4); }.gr-button:hover { transform: scale(1.05) !important; box-shadow: 0 0 25px rgba(218, 34, 255, 0.8) !important; }.tabs > .tab-nav > button.selected { background: #9733ee !important; color: white !important; border-bottom: 2px solid #ff00ff !important; }.gr-gallery > .preview > img { border-radius: 10px !important; transition: transform 0.3s ease-in-out !important; }.gr-gallery > .preview > img:hover { transform: scale(1.05) !important; }"""# ==============================================================================# CORE GLITCH EFFECT FUNCTIONS (DATAMOSH IS NOW BULLETPROOF)# ==============================================================================def datamosh(img: Image.Image, intensity: float) -> Image.Image:"""Simulates digital artifacts by corrupting JPEG data.*** This function is now hardened against errors. ***If corruption creates an unreadable image, it returns the original."""if intensity == 0: return imgtry: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 = 623 # A safe offset for JPEG headersif 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)# Try to open the corrupted data. If it fails, the 'except' block will catch it.new_img = Image.open(io.BytesIO(data))# A crucial step: verify the image is usable by trying to load it.new_img.load()# If we reached here, the image is valid. Convert back to RGB if needed.if new_img.mode != 'RGB':new_img = new_img.convert('RGB')return new_imgexcept (OSError, Image.DecompressionBombError, ValueError, TypeError) as e:# If ANY error occurs during datamoshing, log it for debugging and# return the original image to prevent the app from crashing.print(f"Datamosh failed gracefully: {e}. Returning original image.")return img# --- Other effect functions (already stable) ---def pixel_sorting(img: Image.Image, intensity: float) -> Image.Image:if intensity == 0: return imgarr = np.array(img)2 unmodified linesrows_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)def rgb_shift(img: Image.Image, intensity: float) -> Image.Image:8 unmodified linesif random.random() < intensity: channels[1] = np.roll(channels[1], shift_y, axis=0)return Image.fromarray(cv2.merge(channels))def tile_glitch(img: Image.Image, intensity: float, tile_size: int) -> Image.Image:if intensity == 0: return imgarr = np.array(img)34 unmodified lines"Scanline Effect": scanline_effect}def create_files_in_memory(steps: List[Tuple[Image.Image, str]]) -> Tuple[Optional[io.BytesIO], Optional[io.BytesIO]]:"""Generates GIF and ZIP files entirely in memory."""if not steps: return None, Noneimages = [img for img, _ in steps]# Create GIF in memorygif_bytes = io.BytesIO()max_size = 600base_width, base_height = images[0].sizescale = min(1.0, max_size / max(base_width, base_height))if scale < 1.0:new_size = (int(base_width * scale), int(base_height * scale))resized_images = [img.resize(new_size, Image.Resampling.LANCZOS) for img in images]else:resized_images = imagesresized_images[0].save(gif_bytes, format='GIF', save_all=True, append_images=resized_images[1:], duration=300, loop=0, optimize=True)gif_bytes.seek(0)# Create ZIP in memoryzip_bytes = io.BytesIO()with zipfile.ZipFile(zip_bytes, 'w', zipfile.ZIP_DEFLATED) as zipf:for i, (img, title) in enumerate(steps):3 unmodified linesfilename = f"step_{i:02d}_{title.replace(' ', '_')}.png"zipf.writestr(filename, img_bytes.getvalue())zip_bytes.seek(0)return gif_bytes, zip_bytesdef run_glitch_pipeline(image: Image.Image,active_effects: List[str],params: Dict[str, Any]) -> Tuple[Image.Image, List[Tuple[Image.Image, str]]]:"""Applies the selected effects and returns the process steps."""if image is None:placeholder = Image.new('RGB', (512, 512), color='#0f0c29')return placeholder, [(placeholder, "Upload an image to start")]if image.mode != 'RGB':image = image.convert('RGB')steps = [(image.copy(), "Original")]current_img = imagefor effect_name in active_effects:if effect_name in EFFECT_MAP:func = EFFECT_MAP[effect_name]2 unmodified lineselse:param_key = f"{effect_name.lower().replace(' ', '_')}_intensity"current_img = func(current_img, params[param_key])steps.append((current_img, effect_name)) # No .copy() needed here, effects return new objectsreturn current_img, steps# ==============================================================================# GRADIO INTERFACE - V4 (Production Ready)# ==============================================================================with gr.Blocks(theme=gr.themes.Default(), css=CUSTOM_CSS) as demo:gr.Markdown("<h1 class='main-title'>G L I T C H / A R T / S T U D I O</h1>")1 unmodified lineshared_steps = gr.State([])with gr.Row():with gr.Column(scale=1):with gr.Group(elem_classes=["pro-panel"]):image_input = gr.Image(type="pil", label="π· UPLOAD IMAGE", height=300)active_effects = gr.CheckboxGroup(choices=list(EFFECT_MAP.keys()), value=list(EFFECT_MAP.keys()), label="ποΈ ACTIVE EFFECTS")with gr.Group(elem_classes=["pro-panel"]):with gr.Accordion("βοΈ FINE-TUNE PARAMETERS", open=True):# Naming convention: The variable name MUST match the key in the params dictionary.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="Tile Size")with gr.Column(scale=2):with gr.Group(elem_classes=["pro-panel"]):with gr.Tabs() as output_tabs:8 unmodified linesgenerate_button = gr.Button("π GENERATE FINAL ART & DOWNLOADS")# --- Backend Functions for Gradio ---def live_preview_controller(img, fx, ps, rgbs, dm, sl, tgi, ts):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, fx, params)return final_image, steps_datadef final_assets_controller(steps_data):if not steps_data or len(steps_data) <= 1:gr.Warning("No effects applied or no image loaded. Cannot generate assets.")return None, None, [], gr.Tabs(selected="preview_tab")gif_file, zip_file = create_files_in_memory(steps_data)gallery_items = [(img, title) for img, title in steps_data]gr.Info("β Success! Your art is ready in the 'Gallery' and 'Downloads' tabs.")return gif_file, zip_file, gallery_items, gr.Tabs(selected="gallery_tab")# --- Event Listeners ---controls = [image_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],queue=True)generate_button.click(fn=final_assets_controller,inputs=[shared_steps],outputs=[gif_output, zip_output, gallery_output, output_tabs])
app.py+96-129