Create app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152import numpy as npfrom PIL import Imageimport imageioimport gradio as grimport ioimport zipfilefrom datetime import datetimeimport randomimport cv2
# ======================# ADVANCED GLITCH EFFECTS (CLEANED)# ======================
def pixel_sorting(img: Image.Image, params: dict) -> Image.Image: """Performs chaotic pixel sorting.""" arr = np.array(img) intensity = params.get('pixel_sort_intensity', 0.5) mode = params.get('pixel_sort_mode', 'random') if mode == 'random': mode = random.choice(['horizontal', 'vertical', 'diagonal']) if mode == 'horizontal': for y in range(arr.shape[0]): if random.random() < intensity: brightness = np.mean(arr[y], axis=1) sorted_indices = np.argsort(brightness) arr[y] = arr[y][sorted_indices if random.random() > 0.5 else sorted_indices[::-1]] elif mode == 'vertical': for x in range(arr.shape[1]): if random.random() < intensity: brightness = np.mean(arr[:, x], axis=1) sorted_indices = np.argsort(brightness) arr[:, x] = arr[:, x][sorted_indices if random.random() > 0.5 else sorted_indices[::-1]] elif mode == 'diagonal': for d in range(-arr.shape[0], arr.shape[1]): diag = np.diagonal(arr, offset=d) if len(diag) > 10 and random.random() < intensity: sorted_diag = np.sort(diag) if random.random() > 0.5 else np.sort(diag)[::-1] arr.flat[np.diag_indices_from(arr, d)] = sorted_diag
return Image.fromarray(arr)
def rgb_shift(img: Image.Image, params: dict) -> Image.Image: """Applies extreme RGB channel shifting.""" intensity = params.get('rgb_shift_intensity', 0.5) shift_x = int(intensity * 30 * random.choice([-1, 1])) shift_y = int(intensity * 20 * random.choice([-1, 1])) r, g, b = img.split() r = r.transform(img.size, Image.AFFINE, (1, 0, shift_x, 0, 1, shift_y)) b = b.transform(img.size, Image.AFFINE, (1, 0, -shift_x, 0, 1, -shift_y)) if random.random() < intensity: g_shift_x = int(intensity * 15 * random.choice([-1, 1])) g_shift_y = int(intensity * 10 * random.choice([-1, 1])) g = g.transform(img.size, Image.AFFINE, (1, 0, g_shift_x, 0, 1, g_shift_y)) return Image.merge('RGB', (r, g, b))
def datamosh(img: Image.Image, params: dict) -> Image.Image: """Applies an extreme datamosh effect.""" # Save the image with low quality to create artifacts with io.BytesIO() as buffer: quality = max(1, int(5 + params.get('datamosh_intensity', 0.5) * 10)) img.save(buffer, format='JPEG', quality=quality) buffer.seek(0) moshed = Image.open(buffer) moshed.load() # Ensure the image is fully loaded # Corrupt the bytes of the image to create visual glitches with io.BytesIO() as buffer2: moshed.save(buffer2, format='PNG') buffer2.seek(0) data = bytearray(buffer2.getvalue()) corruption_points = min(1000, int(len(data) * 0.1 * params.get('datamosh_intensity', 0.5))) for _ in range(corruption_points): idx = random.randint(0, len(data) - 1) data[idx] = random.randint(0, 255) try: return Image.open(io.BytesIO(data)) except Exception: return moshed
# ======================# GLITCH PIPELINE SYSTEM# ======================
def create_glitch_art(image: Image.Image, preset_name: str) -> list: """Applies glitch effects based on a preset.""" params = PRESETS[preset_name].copy() steps = [(image.copy(), "Original")] effects = [ pixel_sorting, rgb_shift, datamosh # Additional effects can be added here ] current_img = image.copy() applied_effects = set() for _ in range(8): # Apply up to 8 random effects effect = random.choice(effects) effect_name = effect.__name__ if effect_name in applied_effects: continue try: current_img = effect(current_img, params) steps.append((current_img.copy(), effect_name)) applied_effects.add(effect_name) except Exception as e: print(f"Error applying {effect_name}: {e}") try: final_img = datamosh(current_img, params) steps.append((final_img, "Datamoshing Final")) except Exception: steps.append((current_img, "Final Result")) return steps
# ======================# GRADIO INTERFACE# ======================
with gr.Blocks(title="🔥 GLITCH ART EXTREME") as app: gr.Markdown("# 🔥 **GLITCH ART EXTREME**\n*Transform your images into glitch art with destructive effects*") with gr.Row(): input_img = gr.Image(label="Upload Your Image", type="pil") preset_name = gr.Dropdown(choices=list(PRESETS.keys()), value="Moderate", label="Glitch Preset", interactive=True) generate_btn = gr.Button("💥 GENERATE GLITCH", variant="primary") with gr.Column(): output_img = gr.Image(label="Final Result", interactive=False) gif_output = gr.File(label="Glitch Process (GIF)") gallery = gr.Gallery(label="All Steps", columns=3, object_fit="contain", height="auto") zip_output = gr.File(label="Download All Steps (ZIP)") generate_btn.click( glitch_art_interface, inputs=[input_img, preset_name], outputs=[output_img, gif_output, gallery, zip_output] )
if __name__ == "__main__": app.launch()app.pyAdded+152