Update app.py
Browse files1223451 unmodified line7891010111213141516171618192021202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879802223242526272829303132843334353637383940414243444546474849505152535455565758596061626364656667686970717273747576772 unmodified lines8081829495838485868 unmodified lines959697110111112113114115116117118119120121122123124125989910034 unmodified lines1351361371661671681381391401411421431441451461471481491501721731741511521531541551761771781561571581591603 unmodified lines1641651661671881681691701711721731741751761961771781791991801811821832022031841851861871882 unmodified lines1911921932121941951961971982171992002012021 unmodified line2042052062252072082092292302312322332342102112122132372142152162402172182192202442212222238 unmodified lines232233234259260235236237238263239240241266267268269242243244272273245246247248249278279280281282283250251252253287254255256257291292258259260261262263297264265266267268269270304271272273274import numpy as npfrom PIL import Imagefrom PIL import Image, ImageFileimport ioimport zipfileimport random1 unmodified lineimport warningsimport gradio as grfrom typing import List, Tuple, Dict, Any, Optionalimport time
# --- 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 V3 - "Cyberpunk Pro" Theme (Refined for Gradio 4 stable)# AESTHETICS - "Cyberpunk Pro" Theme (Stable & Refined)# ==============================================================================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);}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 (Unchanged, already optimized)# 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 img try: 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 headers if 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_img
except (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 img arr = np.array(img)2 unmodified lines rows_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]] 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 lines if 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 img quality = 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 = 623 if 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 img
def tile_glitch(img: Image.Image, intensity: float, tile_size: int) -> Image.Image: if intensity == 0: return img arr = 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 None base_width, base_height = frames[0].sizedef 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, None images = [img for img, _ in steps] # Create GIF in memory gif_bytes = io.BytesIO() max_size = 600 base_width, base_height = images[0].size scale = 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) resized_images = [img.resize(new_size, Image.Resampling.LANCZOS) for img in images] else: resized_images = images resized_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) return gif_bytes
def create_zip_from_bytes(steps: List[Tuple[Image.Image, str]]) -> io.BytesIO: # Create ZIP in memory zip_bytes = io.BytesIO() with zipfile.ZipFile(zip_bytes, 'w', zipfile.ZIP_DEFLATED) as zipf: for i, (img, title) in enumerate(steps):3 unmodified lines filename = f"step_{i:02d}_{title.replace(' ', '_')}.png" zipf.writestr(filename, img_bytes.getvalue()) zip_bytes.seek(0) return zip_bytes return gif_bytes, zip_bytes
def 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') placeholder = Image.new('RGB', (512, 512), color='#0f0c29') return placeholder, [(placeholder, "Upload an image to start")] if image.mode != 'RGB': image = image.convert('RGB') if image.mode != 'RGB': image = image.convert('RGB') steps = [(image.copy(), "Original")] current_img = image.copy()
current_img = image for effect_name in active_effects: if effect_name in EFFECT_MAP: func = EFFECT_MAP[effect_name]2 unmodified lines else: param_key = f"{effect_name.lower().replace(' ', '_')}_intensity" current_img = func(current_img, params[param_key]) steps.append((current_img.copy(), effect_name)) steps.append((current_img, effect_name)) # No .copy() needed here, effects return new objects return current_img, steps
# ==============================================================================# GRADIO INTERFACE - V3 (Stable and Refined)# 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 line shared_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" ) 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_sort_intensity = gr.Slider(0, 1, value=0.1, label="Pixel Sorting") 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_intensity = gr.Slider(0, 1, value=0.2, label="Scanlines") 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") # --- RIGHT COLUMN: OUTPUTS --- with gr.Column(scale=2): with gr.Group(elem_classes=["pro-panel"]): with gr.Tabs() as output_tabs:8 unmodified lines
generate_button = gr.Button("π GENERATE FINAL ART & DOWNLOADS")
# --- Live Preview Logic --- def update_live_preview(image, effects, ps, rgbs, dm, sl, tgi, ts): # --- 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, # Using the general name "datamosh_intensity": dm, "scanline_effect_intensity": sl, "tile_glitch_intensity": tgi, "tile_size": int(ts) } # Final consistency check for scanline param key params["scanline_effect_intensity"] = sl
final_image, steps_data = run_glitch_pipeline(image, effects, params) final_image, steps_data = run_glitch_pipeline(img, fx, params) return final_image, steps_data
# --- Final Generation Logic --- def generate_final_assets(steps_data): def 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")
step_images = [img for img, _ in steps_data] # Create files in memory gif_bytes = create_gif_from_bytes(step_images) zip_bytes = create_zip_from_bytes(steps_data) 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_bytes, zip_bytes, gallery_items, gr.Tabs(selected="gallery_tab") return gif_file, zip_file, 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 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=update_live_preview, fn=live_preview_controller, inputs=controls, outputs=[final_output, shared_steps], queue=True ) generate_button.click( fn=generate_final_assets, fn=final_assets_controller, inputs=[shared_steps], outputs=[gif_output, zip_output, gallery_output, output_tabs] )app.py+96-129