Create app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293import numpy as npfrom PIL import Image, ImageOps, ImageFilterimport imageioimport gradio as grimport ioimport zipfilefrom datetime import datetimeimport randomimport cv2import os
# ======================# EFECTOS GLITCH AVANZADOS# ======================
def pixel_sorting(img, threshold=200, mode='horizontal'): """Ordena p铆xeles basado en valores RGB""" arr = np.array(img) if mode == 'horizontal': for y in range(arr.shape[0]): row = arr[y] brightness = np.mean(row, axis=1) sorted_indices = np.argsort(brightness) arr[y] = row[sorted_indices] elif mode == 'vertical': for x in range(arr.shape[1]): col = arr[:, x] brightness = np.mean(col, axis=1) sorted_indices = np.argsort(brightness) arr[:, x] = col[sorted_indices] return Image.fromarray(arr)
def rgb_shift(img, shift_x=5, shift_y=3): """Desplazamiento de canales RGB""" 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)) return Image.merge('RGB', (r, g, b))
def datamosh(img, intensity=0.8): """Efecto de datamoshing con compresi贸n/descompresi贸n""" with io.BytesIO() as buffer: img.save(buffer, format='JPEG', quality=int(100 - intensity*90)) buffer.seek(0) return Image.open(buffer)
def vhs_glitch(img, noise_intensity=0.7, distortion=0.5): """Efecto VHS con ruido y distorsi贸n""" arr = np.array(img).astype(np.float32) # Ruido est谩tico noise = np.random.normal(0, noise_intensity*80, arr.shape) arr = np.clip(arr + noise, 0, 255) # Distorsi贸n de l铆nea for i in range(arr.shape[0]): if random.random() < distortion/10: shift = int(distortion * 50 * random.choice([-1, 1])) arr[i] = np.roll(arr[i], shift, axis=0) # Desfase de color r, g, b = cv2.split(arr.astype(np.uint8)) r = cv2.resize(r, None, fx=1.01, fy=1.01, interpolation=cv2.INTER_LINEAR) g = cv2.resize(g, None, fx=0.99, fy=0.99, interpolation=cv2.INTER_LINEAR) # Recortar al tama帽o original r = r[:arr.shape[0], :arr.shape[1]] g = g[:arr.shape[0], :arr.shape[1]] return cv2.merge([r, g, b])
def tile_glitch(img, tile_size=32, distortion=0.7): """Glitch de mosaico con desplazamiento aleatorio""" arr = np.array(img) h, w = arr.shape[:2] for y in range(0, h, tile_size): for x in range(0, w, tile_size): if random.random() < distortion/3: # Desplazar algunos bloques shift_y = random.randint(-tile_size//2, tile_size//2) shift_x = random.randint(-tile_size//2, tile_size//2) tile = arr[y:y+tile_size, x:x+tile_size] tile = np.roll(tile, shift_y, axis=0) tile = np.roll(tile, shift_x, axis=1) # Aplicar solo si est谩 dentro de los l铆mites if y+shift_y+tile_size <= h and x+shift_x+tile_size <= w: arr[y:y+tile_size, x:x+tile_size] = tile return Image.fromarray(arr)
def compression_glitch(img, quality=5): """Artefactos extremos de compresi贸n""" with io.BytesIO() as buffer: img.save(buffer, format='JPEG', quality=quality) buffer.seek(0) return Image.open(buffer)
def z_fighting(img, intensity=0.5): """Efecto Z-fighting con duplicaci贸n de capas""" arr1 = np.array(img) arr2 = np.array(img.rotate(0.5)) mask = np.random.random(arr1.shape[:2]) < intensity result = np.where(mask[..., None], arr1, arr2) return Image.fromarray(result)
def sprite_bleed(img, bleed_size=5): """Efecto de derrame de sprites""" arr = np.array(img) h, w = arr.shape[:2] # Crear copias desplazadas bleed_r = np.roll(arr, bleed_size, axis=1) bleed_b = np.roll(arr, -bleed_size, axis=0) # Combinar con la original result = arr.copy() result = np.maximum(result, bleed_r) result = np.maximum(result, bleed_b) return Image.fromarray(result)
def resolution_mismatch(img, scale_factor=0.7): """Desajuste de resoluci贸n con remuestreo""" w, h = img.size scaled = img.resize((int(w*scale_factor), int(h*scale_factor)), Image.NEAREST) return scaled.resize((w, h), Image.NEAREST)
def scanline_corruption(img, line_thickness=1, spacing=3): """L铆neas de escaneo corruptas""" arr = np.array(img) h, w = arr.shape[:2] for y in range(0, h, spacing): if random.random() > 0.3: arr[y:y+line_thickness] = 0 return Image.fromarray(arr)
def palette_corruption(img, bit_depth=3): """Corrupci贸n de paleta reduciendo profundidad de color""" arr = np.array(img) mask = 255 << (8 - bit_depth) return Image.fromarray(arr & mask)
def databending(img, intensity=0.8): """Manipulaci贸n directa de bytes de imagen""" with io.BytesIO() as buffer: img.save(buffer, format='PNG') data = bytearray(buffer.getvalue()) # Corromper secciones aleatorias for _ in range(int(len(data) * intensity / 100)): idx = random.randint(0, len(data)-1) data[idx] = random.randint(0, 255) return Image.open(io.BytesIO(data))
# ======================# SISTEMA DE PROCESAMIENTO# ======================
def create_glitch_art(image, intensity=0.8): """Aplica todos los efectos glitch en cascada""" steps = [] # Paso 0: Imagen original steps.append((image.copy(), "Original")) # Paso 1: Pixel Sorting sorted_img = pixel_sorting(image, mode='horizontal' if random.random() > 0.5 else 'vertical') steps.append((sorted_img, "Pixel Sorting")) # Paso 2: RGB Shift rgb_img = rgb_shift(sorted_img, shift_x=random.randint(3, 15), shift_y=random.randint(1, 7)) steps.append((rgb_img, "RGB Shift")) # Paso 3: Datamoshing mashed_img = datamosh(rgb_img, intensity) steps.append((mashed_img, "Datamoshing")) # Paso 4: VHS Glitch vhs_img = Image.fromarray(vhs_glitch(mashed_img, intensity)) steps.append((vhs_img, "VHS Glitch")) # Paso 5: Tile Glitch tile_img = tile_glitch(vhs_img, tile_size=random.choice([16, 32, 64]), intensity) steps.append((tile_img, "Tile Glitch")) # Paso 6: Z-Fighting z_img = z_fighting(tile_img, intensity) steps.append((z_img, "Z-Fighting")) # Paso 7: Sprite Bleed bleed_img = sprite_bleed(z_img, random.randint(3, 10)) steps.append((bleed_img, "Sprite Bleed")) # Paso 8: Compression Artifacts compressed_img = compression_glitch(bleed_img, quality=max(1, int(100 - intensity*95))) steps.append((compressed_img, "Compression Glitch")) # Paso 9: Resolution Mismatch res_img = resolution_mismatch(compressed_img, random.uniform(0.5, 0.9)) steps.append((res_img, "Resolution Mismatch")) # Paso 10: Scanline Corruption scan_img = scanline_corruption(res_img, random.randint(1, 3), random.randint(2, 6)) steps.append((scan_img, "Scanline Corruption")) # Paso 11: Palette Corruption palette_img = palette_corruption(scan_img, random.randint(1, 4)) steps.append((palette_img, "Palette Corruption")) # Paso 12: Databending final_img = databending(palette_img, intensity*100) steps.append((final_img, "Databending Final")) return steps
# ======================# INTERFAZ GRADIO# ======================
def glitch_art_interface(image, intensity): if image is None: return None, None, None, None # Procesar la imagen con todos los efectos steps = create_glitch_art(image, intensity) step_images = [img for img, title in steps] step_titles = [title for img, title in steps] # Crear GIF gif_bytes = io.BytesIO() frames = [np.array(img) for img, _ in steps] imageio.mimsave(gif_bytes, frames, format='GIF', duration=300) gif_bytes.seek(0) # Crear ZIP zip_bytes = io.BytesIO() with zipfile.ZipFile(zip_bytes, 'w') as zipf: for i, (img, title) in enumerate(steps): img_bytes = io.BytesIO() img.save(img_bytes, format='PNG') img_bytes.seek(0) zipf.writestr(f"step_{i+1}_{title.replace(' ', '_')}.png", img_bytes.read()) zip_bytes.seek(0) # Timestamp para nombres de archivo timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") return ( steps[-1][0], # Imagen final (f"glitch_process_{timestamp}.gif", gif_bytes.read()), # GIF list(zip(step_images, step_titles)), # Galer铆a (f"all_steps_{timestamp}.zip", zip_bytes.read()) # ZIP )
# ======================# CONFIGURACI脫N GRADIO# ======================
with gr.Blocks(title="馃敟 GLITCH ART EXTREME") as app: gr.Markdown(""" # 馃敟 **GLITCH ART EXTREME** *Transforma tus im谩genes en arte glitch con efectos destructivos* """) with gr.Row(): with gr.Column(): input_img = gr.Image(label="Sube tu imagen", type="pil") intensity = gr.Slider(0.1, 1.0, value=0.8, label="Intensidad Glitch") generate_btn = gr.Button("馃挜 GENERAR GLITCH", variant="primary") with gr.Column(): output_img = gr.Image(label="Resultado Final", interactive=False) gif_output = gr.File(label="Proceso Glitch (GIF)") gallery = gr.Gallery(label="Todos los Pasos", columns=3, object_fit="contain", height="auto") zip_output = gr.File(label="Descargar Todos los Pasos (ZIP)") generate_btn.click( glitch_art_interface, inputs=[input_img, intensity], outputs=[output_img, gif_output, gallery, zip_output] )
if __name__ == "__main__": app.launch()app.pyAdded+293