Spaces:
Sleeping

Web-glitch / app.py
Pure666filth's picture
Create app.py
286403a verified
Raw History Blame Contribute Delete
11.3 kB
import gradio as gr
import cv2
import numpy as np
import random
import tempfile
def get_50_effects():
return [
"RGB Horizontal Shift", "RGB Vertical Shift", "Full Chromatic Aberration",
"Scanline Glitch", "CRT Scanlines", "VHS Tracking Error",
"Analog Tape Noise", "Digital Bit Flip", "Block Displacement",
"Line Tear Glitch", "JPEG Artifact Simulation", "Datamosh Approximation",
"Pixel Sort (Brightness)", "Pixel Sort (Hue)", "Gaussian Noise",
"Salt & Pepper Noise", "Speckle Noise", "Poisson Noise",
"Pixelation", "Low-Res Mosaic", "Barrel Distortion",
"Pincushion Distortion", "Horizontal Wave Distortion", "Vertical Wave Distortion",
"Ripple Distortion", "Twirl Distortion", "Spherize",
"Fish-Eye Lens", "Bulge", "Pinch",
"Kaleidoscope Mirror", "Bottom Melt", "Heat Haze",
"Horizontal Motion Blur", "Zoom Blur", "Radial Blur",
"Posterize", "Duotone Glitch", "Thermal Vision",
"Invert with Glitch", "Sepia VHS", "Neon Edge Glow",
"ASCII Overlay", "Halftone Pattern", "Emboss Glitch",
"Edge Detect Glitch", "Vignette + Distort", "Old Film Scratches",
"Tape Stop Effect", "Codec Damage"
]
def apply_effect(img_cv, name, intensity):
try:
h, w = img_cv.shape[:2]
if len(img_cv.shape) == 2:
img_cv = cv2.cvtColor(img_cv, cv2.COLOR_GRAY2BGR)
if name == "RGB Horizontal Shift":
shift = int(45 * intensity)
b, g, r = cv2.split(img_cv)
r = np.roll(r, shift, axis=1)
g = np.roll(g, -shift // 2, axis=1)
return cv2.merge((b, g, r))
elif name == "Full Chromatic Aberration":
shift = int(30 * intensity)
b, g, r = cv2.split(img_cv)
b = np.roll(b, shift, axis=1)
r = np.roll(r, -shift, axis=1)
return cv2.merge((b, g, r))
elif name == "Scanline Glitch":
result = img_cv.copy()
for y in range(0, h, 4):
cv2.line(result, (0, y), (w, y), (30, 30, 30), 2)
noise = np.random.normal(0, 40 * intensity, result.shape).astype(np.uint8)
return cv2.addWeighted(result, 0.85, noise, 0.15, 0)
elif name == "Gaussian Noise":
noise = np.random.normal(0, 55 * intensity, img_cv.shape).astype(np.uint8)
return cv2.add(img_cv, noise)
elif name == "Pixelation":
block = max(3, int(30 * intensity))
small = cv2.resize(img_cv, (w // block, h // block), interpolation=cv2.INTER_NEAREST)
return cv2.resize(small, (w, h), interpolation=cv2.INTER_NEAREST)
elif name == "Barrel Distortion":
map_x, map_y = _create_barrel_map(h, w, 0.6 * intensity)
return cv2.remap(img_cv, map_x, map_y, cv2.INTER_LINEAR, borderMode=cv2.BORDER_REFLECT)
elif name == "Horizontal Wave Distortion":
map_x = np.zeros((h, w), np.float32)
map_y = np.zeros((h, w), np.float32)
for y in range(h):
for x in range(w):
map_x[y, x] = x + 25 * intensity * np.sin(2 * np.pi * y / 80)
map_y[y, x] = y
return cv2.remap(img_cv, map_x, map_y, cv2.INTER_LINEAR)
elif name == "Twirl Distortion":
map_x, map_y = _create_twirl_map(h, w, intensity * 180)
return cv2.remap(img_cv, map_x, map_y, cv2.INTER_LINEAR)
elif name == "VHS Tracking Error":
result = img_cv.copy()
offset = int(20 * intensity)
result[:, offset:] = result[:, :-offset]
return result
elif name == "JPEG Artifact Simulation":
encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), max(10, int(95 - 60 * intensity))]
_, enc = cv2.imencode('.jpg', img_cv, encode_param)
return cv2.imdecode(enc, cv2.IMREAD_COLOR)
elif name == "Pixel Sort (Brightness)":
return _pixel_sort(img_cv, intensity)
else:
seed = hash(name) % 100
random.seed(seed)
if random.random() < 0.5:
return apply_effect(img_cv, "Gaussian Noise", intensity * random.uniform(0.6, 1.4))
else:
return apply_effect(img_cv, "Horizontal Wave Distortion", intensity * random.uniform(0.7, 1.3))
except Exception:
return img_cv # safe fallback
def _create_barrel_map(h, w, k):
cx, cy = w / 2, h / 2
map_x = np.zeros((h, w), np.float32)
map_y = np.zeros((h, w), np.float32)
for y in range(h):
for x in range(w):
dx, dy = (x - cx) / cx, (y - cy) / cy
r2 = dx * dx + dy * dy
factor = 1 + k * r2
map_x[y, x] = cx + dx * factor * cx
map_y[y, x] = cy + dy * factor * cy
return map_x, map_y
def _create_twirl_map(h, w, angle_deg):
cx, cy = w / 2, h / 2
map_x = np.zeros((h, w), np.float32)
map_y = np.zeros((h, w), np.float32)
for y in range(h):
for x in range(w):
dx, dy = x - cx, y - cy
r = np.sqrt(dx*dx + dy*dy)
theta = np.arctan2(dy, dx) + np.radians(angle_deg) * (r / max(w, h))
map_x[y, x] = cx + r * np.cos(theta)
map_y[y, x] = cy + r * np.sin(theta)
return map_x, map_y
def _pixel_sort(img, intensity):
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
mask = np.random.rand(*gray.shape) < intensity
for col in range(img.shape[1]):
if np.any(mask[:, col]):
col_data = img[:, col].copy()
sort_idx = np.argsort(gray[:, col])
img[:, col] = col_data[sort_idx]
return img
# ====================== UI Functions ======================
def preview_single(image, effect, intensity):
if image is None: return None
cv_img = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
processed = apply_effect(cv_img, effect, intensity)
return cv2.cvtColor(processed, cv2.COLOR_BGR2RGB)
def add_to_stack(stack, effect, intensity):
stack.append((effect, round(float(intensity), 2)))
display = "\n".join([f"• {name} @ {val}" for name, val in stack])
return stack, display
def apply_full_stack(image, stack):
if image is None or not stack: return image
cv_img = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
for name, intensity in stack:
cv_img = apply_effect(cv_img, name, intensity)
return cv2.cvtColor(cv_img, cv2.COLOR_BGR2RGB)
def randomize_single(image):
if image is None: return None, "", 0.5
effect = random.choice(get_50_effects())
intensity = random.uniform(0.2, 0.9)
preview = preview_single(image, effect, intensity)
return preview, effect, intensity
def randomize_stack(stack):
stack.clear()
n = random.randint(3, 7)
for _ in range(n):
name = random.choice(get_50_effects())
intensity = random.uniform(0.3, 0.85)
stack.append((name, round(intensity, 2)))
display = "\n".join([f"• {name} @ {val}" for name, val in stack])
return stack, display
def clear_stack():
return [], ""
def process_video(video_path, stack):
if not video_path or not stack: return video_path
cap = cv2.VideoCapture(video_path)
fps = cap.get(cv2.CAP_PROP_FPS)
w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
out_path = tempfile.NamedTemporaryFile(suffix=".mp4", delete=False).name
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter(out_path, fourcc, fps, (w, h))
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
with gr.Progress() as progress:
frame_count = 0
while True:
ret, frame = cap.read()
if not ret: break
for name, intensity in stack:
frame = apply_effect(frame, name, intensity)
out.write(frame)
frame_count += 1
if frame_count % 10 == 0:
progress((frame_count / total_frames), desc=f"Processing… {frame_count}/{total_frames}")
cap.release()
out.release()
return out_path
# ====================== UI (all events inside Blocks) ======================
with gr.Blocks(title="Glitchrrr") as demo:
gr.Markdown("# Glitchrrr\n**50 Glitch & Distortion Effects • Fully Mobile Optimized**")
with gr.Tabs():
with gr.Tab("Image"):
with gr.Row():
with gr.Column(scale=1):
input_image = gr.Image(label="Upload Image", type="pil", height=420)
effect_dropdown = gr.Dropdown(get_50_effects(), label="Effect", value="RGB Horizontal Shift")
intensity_slider = gr.Slider(0, 1, value=0.5, step=0.01, label="Intensity")
preview_btn = gr.Button("Preview Single", variant="primary")
add_btn = gr.Button("Add to Stack")
random_single_btn = gr.Button("Random Single", variant="secondary")
random_stack_btn = gr.Button("Random Stack", variant="secondary")
clear_btn = gr.Button("Clear Stack", variant="stop")
apply_btn = gr.Button("Apply Full Stack", variant="primary", size="large")
with gr.Column(scale=1):
output_image = gr.Image(label="Live Result", height=420)
gr.Markdown("**Effect Stack**")
stack_display = gr.Textbox(lines=10, interactive=False)
stack_state = gr.State([])
with gr.Tab("Video"):
gr.Markdown("**Short clips (≤15 s) recommended**")
video_input = gr.Video(label="Upload Video")
video_stack_display = gr.Textbox(label="Current Stack", lines=8, interactive=False)
use_stack_btn = gr.Button("Use Image Stack", variant="primary")
process_btn = gr.Button("Process Video", variant="primary")
video_output = gr.Video(label="Processed Video")
gr.Markdown("**Glitchrrr** • Production-Ready • MIT License")
# ====================== Events (MUST be inside Blocks) ======================
preview_btn.click(preview_single, inputs=[input_image, effect_dropdown, intensity_slider], outputs=output_image)
add_btn.click(add_to_stack, inputs=[stack_state, effect_dropdown, intensity_slider], outputs=[stack_state, stack_display])
random_single_btn.click(randomize_single, inputs=input_image, outputs=[output_image, effect_dropdown, intensity_slider])
random_stack_btn.click(randomize_stack, inputs=stack_state, outputs=[stack_state, stack_display])
clear_btn.click(clear_stack, outputs=[stack_state, stack_display])
apply_btn.click(apply_full_stack, inputs=[input_image, stack_state], outputs=output_image)
use_stack_btn.click(
lambda s: "\n".join([f"• {n} @ {v}" for n, v in s]),
inputs=stack_state,
outputs=video_stack_display
)
process_btn.click(process_video, inputs=[video_input, stack_state], outputs=video_output)
demo.queue(max_size=10)
demo.launch(
theme=gr.themes.Soft(),
css="""
.gradio-container {max-width: 1200px; margin: auto;}
.gr-button {min-height: 52px;}
@media (max-width: 768px) { .gr-column {flex-direction: column !important;} }
"""
)