Spaces:
Sleeping

File size: 34,974 Bytes
8800bcc
99435a5
8800bcc
99435a5
 
 
4807d1b
24609dc
6031ed0
232ec1b
11f57da
9b71414
99435a5
9b71414
4807d1b
627e4e0
f616ad8
9b71414
 
627e4e0
f8c3371
8800bcc
9b71414
 
6031ed0
9b71414
 
 
 
6031ed0
9b71414
 
 
 
 
 
 
 
 
 
 
 
 
 
6dddb4c
 
 
627e4e0
6dddb4c
febd6ea
18963a9
9b71414
 
18963a9
9b71414
 
 
 
18963a9
9b71414
f8c3371
 
9b71414
 
18963a9
 
8800bcc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
627e4e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8800bcc
627e4e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b71414
11f57da
 
9b71414
 
627e4e0
9b71414
 
11f57da
 
9b71414
627e4e0
9b71414
 
627e4e0
9b71414
627e4e0
 
9b71414
 
11f57da
 
627e4e0
 
 
 
 
 
 
 
 
 
 
9b71414
 
 
11f57da
627e4e0
 
9b71414
627e4e0
 
 
 
 
 
9b71414
627e4e0
9b71414
cb5d1ca
9b71414
 
 
822a909
627e4e0
822a909
 
 
 
 
627e4e0
822a909
 
 
9b71414
 
 
f8c3371
627e4e0
 
 
f8c3371
822a909
 
9b71414
 
627e4e0
e6d630d
 
627e4e0
e6d630d
627e4e0
 
febd6ea
e6d630d
11f57da
 
9b71414
11f57da
627e4e0
 
822a909
11f57da
627e4e0
822a909
232ec1b
8800bcc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6dddb4c
9b71414
6dddb4c
822a909
8800bcc
 
 
 
 
 
febd6ea
24609dc
822a909
8800bcc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
627e4e0
 
 
 
 
 
 
 
 
 
11f57da
9b71414
627e4e0
9b71414
 
11f57da
9b71414
627e4e0
9b71414
 
 
627e4e0
 
9b71414
 
627e4e0
 
9b71414
 
627e4e0
9b71414
8800bcc
 
 
822a909
 
f8c3371
627e4e0
 
822a909
627e4e0
8800bcc
 
627e4e0
 
 
 
8800bcc
 
 
 
 
822a909
2ed8cdf
f8c3371
8800bcc
f8c3371
9b71414
 
 
 
 
 
 
f8c3371
9b71414
 
 
f8c3371
 
 
8800bcc
627e4e0
9b71414
 
 
627e4e0
9b71414
 
 
 
 
11f57da
9b71414
627e4e0
9b71414
 
 
627e4e0
f8c3371
627e4e0
 
f8c3371
fc0272c
 
627e4e0
 
 
9b71414
f8c3371
9b71414
627e4e0
9b71414
627e4e0
 
 
 
9b71414
f8c3371
11f57da
f8c3371
8800bcc
 
 
f8c3371
9b71414
 
 
 
822a909
86f3801
627e4e0
9b71414
627e4e0
822a909
8800bcc
9b71414
 
 
 
6386640
9b71414
627e4e0
 
 
 
6386640
11f57da
8800bcc
 
 
 
822a909
627e4e0
 
11f57da
627e4e0
11f57da
 
627e4e0
11f57da
627e4e0
9b71414
 
627e4e0
9b71414
627e4e0
9b71414
627e4e0
9b71414
627e4e0
 
9b71414
6031ed0
62714b3
f8c3371
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
# GLITCHCRAFT NEXUS v3.5 -- KUSANAGI "CHRONOS" EDITION
import numpy as np
from PIL import Image, ImageFile, ImageOps, ImageFilter, ImageEnhance
import io
import zipfile
import random
import warnings
import gradio as gr
import time
import tempfile
import cv2
from typing import List, Tuple, Dict, Any, Optional, Iterator

# --- KERNEL CONFIGURATION ---
warnings.filterwarnings("ignore", category=Image.DecompressionBombWarning)
ImageFile.LOAD_TRUNCATED_IMAGES = True

# --- CONSTANTS ---
MAX_DIMENSION = 1920
HEADER_BYPASS_RATIO = 0.15

# --- AESTHETICS & UI ---
HACKER_TERMINAL_CSS = """
@import url('https://fonts.googleapis.com/css2?family=Share+Tech+Mono&display=swap');
:root {
    --matrix-green: #00ff41; --scanline-b: rgba(0,0,0,0.7);
    --dark-bg: #05050a; --panel-bg: rgba(10, 20, 25, 0.6);
    --panel-border: rgba(0, 255, 65, 0.2); --text-color: #e0e0e0;
    --glow-color: 0 0 5px var(--matrix-green), 0 0 10px var(--matrix-green), 0 0 15px var(--matrix-green);
}
body, .gradio-container { font-family: 'Share Tech Mono', monospace; background-color: var(--dark-bg); color: var(--text-color); }
body::before { content: ""; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-image: linear-gradient(var(--scanline-b) 50%, transparent 50%); background-size: 100% 4px; z-index: -1; animation: scanlines 0.2s linear infinite; }
@keyframes scanlines { from { background-position: 0 0; } to { background-position: 0 4px; } }
.main-title { text-align: center; font-size: 3rem !important; color: var(--matrix-green); text-shadow: var(--glow-color); animation: flicker 1.5s infinite alternate; }
@keyframes flicker { 0%, 18%, 22%, 25%, 53%, 57%, 100% { opacity: 1; } 20%, 24%, 55% { opacity: 0.6; } }
.pro-panel { background: var(--panel-bg) !important; border: 1px solid var(--panel-border) !important; border-radius: 8px !important; box-shadow: inset 0 0 15px rgba(0, 255, 65, 0.1) !important; backdrop-filter: blur(10px) !important; -webkit-backdrop-filter: blur(10px) !important; }
.gr-button { background: var(--matrix-green) !important; color: var(--dark-bg) !important; border: 1px solid var(--matrix-green) !important; font-weight: bold !important; transition: all 0.2s ease !important; box-shadow: var(--glow-color); }
.gr-button:hover { background: var(--dark-bg) !important; color: var(--matrix-green) !important; }
.log-output textarea { background-color: rgba(0,0,0,0.8) !important; color: var(--matrix-green) !important; border-color: var(--panel-border) !important; }
.log-output textarea::after { content: '█'; animation: blink 1s step-end infinite; }
@keyframes blink { 50% { opacity: 0; } }
.sys-monitor .label-wrap { display: flex; flex-direction: column; align-items: center; gap: 4px; padding: 12px; }
.sys-monitor .label-wrap > .label-title { font-size: 0.8em; color: #888; }
.sys-monitor .label-wrap > .secondary-wrap { font-size: 1.5em; color: var(--matrix-green); text-shadow: var(--glow-color); }
"""

# ==============================================================================
# CORRUPTION & ALTERATION ENGINES
# ==============================================================================

def safe_effect(func):
    """Decorator to ensure a faulty effect doesn't crash the entire pipeline."""
    def wrapper(image_matrix: Image.Image, log: list, **kwargs) -> Tuple[Image.Image, list]:
        try:
            log.append(f"[EXEC] Running Sub-Routine: {func.__name__}...")
            result = func(image_matrix, **kwargs)
            log.append(f"[ OK ] {func.__name__} completed.")
            return result, log
        except Exception as e:
            log.append(f"[CRITICAL_FAIL] Sub-Routine '{func.__name__}' crashed. Bypassing. Reason: {e}")
            import traceback
            traceback.print_exc()
            gr.Warning(f"Effect '{func.__name__}' failed and was skipped.")
            return image_matrix, log
    return wrapper

# --- NEW EFFECTS (ADDED IN LAST STEPS) ---

@safe_effect
def black_and_white_control(image_matrix: Image.Image, bw_apply: bool, bw_contrast: float, bw_brightness: float, **kwargs) -> Image.Image:
    if not bw_apply: return image_matrix
    img = image_matrix.convert("L")
    enhancer = ImageEnhance.Contrast(img)
    img = enhancer.enhance(bw_contrast)
    enhancer = ImageEnhance.Brightness(img)
    img = enhancer.enhance(bw_brightness)
    return img.convert("RGB")

@safe_effect
def cinematic_blur(image_matrix: Image.Image, film_blur_radius: float, **kwargs) -> Image.Image:
    if film_blur_radius == 0: return image_matrix
    return image_matrix.filter(ImageFilter.GaussianBlur(radius=film_blur_radius))

@safe_effect
def motion_blur(image_matrix: Image.Image, motion_blur_intensity: int, motion_blur_angle: float, **kwargs) -> Image.Image:
    if motion_blur_intensity <= 1: return image_matrix
    arr = np.array(image_matrix)
    intensity = max(1, motion_blur_intensity)
    angle_rad = np.deg2rad(motion_blur_angle)
    # Create the motion blur kernel
    kernel = np.zeros((intensity, intensity))
    center = intensity // 2
    # This creates a line of ones along the specified angle
    cv2.line(kernel, (0, center), (intensity - 1, center), 1.0, 1)
    # Rotate the kernel
    M = cv2.getRotationMatrix2D((center, center), -motion_blur_angle, 1.0)
    kernel = cv2.warpAffine(kernel, M, (intensity, intensity))
    kernel /= np.sum(kernel)
    # Apply the kernel
    blurred_arr = cv2.filter2D(arr, -1, kernel)
    return Image.fromarray(blurred_arr)

@safe_effect
def low_res_effect(image_matrix: Image.Image, low_res_factor: int, **kwargs) -> Image.Image:
    if low_res_factor <= 1: return image_matrix
    w, h = image_matrix.size
    small_img = image_matrix.resize((w // low_res_factor, h // low_res_factor), resample=Image.Resampling.NEAREST)
    return small_img.resize(image_matrix.size, Image.Resampling.NEAREST)

@safe_effect
def film_grain(image_matrix: Image.Image, film_grain_amount: float, **kwargs) -> Image.Image:
    if film_grain_amount == 0: return image_matrix
    arr = np.array(image_matrix, dtype=np.float32)
    h, w, _ = arr.shape
    noise = np.random.randn(h, w, 3) * film_grain_amount * 128
    grained_arr = np.clip(arr + noise, 0, 255).astype(np.uint8)
    return Image.fromarray(grained_arr)

@safe_effect
def texture_overlay(image_matrix: Image.Image, texture_type: str, texture_opacity: float, **kwargs) -> Image.Image:
    if texture_opacity == 0 or texture_type == "None": return image_matrix
    base_arr = np.array(image_matrix)
    h, w, _ = base_arr.shape
    texture = np.zeros((h, w, 3), dtype=np.float32)

    if texture_type == "Scan Lines":
        for y in range(h):
            if y % 3 == 0:
                texture[y, :, :] = random.uniform(0.8, 1.0)
    elif texture_type == "Dust & Scratches":
        # Dust
        num_specks = int(w * h * 0.0005)
        xs, ys = np.random.randint(0, w, num_specks), np.random.randint(0, h, num_specks)
        speck_colors = np.random.uniform(0.8, 1.0, (num_specks, 3))
        texture[ys, xs] = speck_colors
        # Scratches
        for _ in range(15):
            start_x, start_y = random.randint(0, w), random.randint(0, h)
            end_x, end_y = start_x + random.randint(-w//20, w//20), start_y + random.randint(-h//5, h//5)
            color = tuple(np.random.uniform(0.8, 1.0, 3) * 255)
            cv2.line(texture, (start_x, start_y), (end_x, end_y), color, 1)
    elif texture_type == "VHS Lines":
        num_lines = random.randint(5, 15)
        for _ in range(num_lines):
            y = random.randint(0, h - 5)
            line_height = random.randint(1, 4)
            texture[y:y+line_height, :, :] = np.random.uniform(0.7, 1.0)

    texture_img = Image.fromarray((texture * 255).astype(np.uint8))
    texture_blurred = texture_img.filter(ImageFilter.GaussianBlur(radius=0.5))
    texture_arr = np.array(texture_blurred, dtype=np.float32) / 255.0

    # Blend using Screen mode: 1 - (1 - base) * (1 - overlay)
    base_norm = base_arr.astype(np.float32) / 255.0
    overlayed_norm = 1.0 - (1.0 - base_norm) * (1.0 - texture_arr)
    # Blend with original using opacity
    final_norm = base_norm * (1.0 - texture_opacity) + overlayed_norm * texture_opacity
    final_arr = np.clip(final_norm * 255, 0, 255).astype(np.uint8)
    return Image.fromarray(final_arr)

@safe_effect
def slit_scan_effect(image_matrix: Image.Image, slit_scan_amount: int, slit_scan_freq: float, **kwargs) -> Image.Image:
    if slit_scan_amount == 0: return image_matrix
    arr = np.array(image_matrix)
    h, w, c = arr.shape
    output_arr = np.zeros_like(arr)
    wave = np.sin(np.linspace(0, slit_scan_freq * np.pi, w)) * slit_scan_amount
    for i in range(w):
        shift = int(wave[i])
        output_arr[:, i, :] = np.roll(arr[:, i, :], shift, axis=0)
    return Image.fromarray(output_arr)


# --- ORIGINAL EFFECTS (ALL INCLUDED AND PRESERVED) ---

@safe_effect
def bloom_glare(image_matrix: Image.Image, bloom_threshold: float, bloom_radius: int, haze_amount: float, **kwargs) -> Image.Image:
    if bloom_radius == 0 and haze_amount == 0:
        return image_matrix
    original_arr = np.array(image_matrix).astype(np.float32)
    if bloom_radius > 0:
        brightness_map = np.dot(original_arr[...,:3], [0.2989, 0.5870, 0.1140])
        threshold_value = bloom_threshold * 255
        highlight_mask = (brightness_map > threshold_value).astype(np.uint8) * 255
        highlight_img = Image.fromarray(highlight_mask)
        blurred_highlights = highlight_img.filter(ImageFilter.GaussianBlur(radius=bloom_radius))
        glare_map = np.array(blurred_highlights).astype(np.float32)[:, :, np.newaxis] / 255.0
        base = original_arr / 255.0
        screened_arr = (1.0 - (1.0 - base) * (1.0 - glare_map)) * 255.0
    else:
        screened_arr = original_arr
    if haze_amount > 0:
        haze_color = (200, 200, 200)
        hazy_arr = screened_arr * (1.0 - haze_amount) + np.array(haze_color) * haze_amount
    else:
        hazy_arr = screened_arr
    final_arr = np.clip(hazy_arr, 0, 255).astype(np.uint8)
    return Image.fromarray(final_arr)

@safe_effect
def pixel_art_conversion(image_matrix: Image.Image, pixel_size: int, eight_bit_colors: int, eight_bit_dither: bool, **kwargs) -> Image.Image:
    if pixel_size <= 1 and eight_bit_colors >= 256: return image_matrix
    img = image_matrix.copy()
    if pixel_size > 1:
        w, h = img.size
        small_img = img.resize((w // pixel_size, h // pixel_size), resample=Image.Resampling.LANCZOS)
        img = small_img.resize(img.size, Image.Resampling.NEAREST)
    if eight_bit_colors < 256:
        dither_mode = Image.Dither.FLOYDSTEINBERG if eight_bit_dither else Image.Dither.NONE
        img = img.quantize(colors=eight_bit_colors, method=Image.Quantize.MEDIANCUT, dither=dither_mode).convert('RGB')
    return img

@safe_effect
def datamosh_corruption(image_matrix: Image.Image, datamosh_amount: float, **kwargs) -> Image.Image:
    if datamosh_amount == 0: return image_matrix
    buffer = io.BytesIO()
    image_matrix.save(buffer, format='BMP')
    data = bytearray(buffer.getvalue())
    data_len = len(data)
    header_size = int(data_len * HEADER_BYPASS_RATIO)
    iterations = int(datamosh_amount * 50)
    max_pump = int(datamosh_amount * 200) + 1
    for _ in range(iterations):
        pump_spot = random.randint(header_size, data_len - max_pump)
        pump_size = random.randint(1, max_pump)
        pump_data = data[pump_spot : pump_spot + pump_size]
        injection_spot = random.randint(header_size, data_len)
        data[injection_spot:injection_spot] = pump_data
    try: return Image.open(io.BytesIO(data))
    except Exception: return image_matrix

@safe_effect
def crt_scanlines(image_matrix: Image.Image, scanline_amount: float, **kwargs) -> Image.Image:
    if scanline_amount == 0: return image_matrix
    arr = np.array(image_matrix, dtype=np.float32)
    h, w, _ = arr.shape
    scanlines = np.ones((h, w, 1))
    scanlines[::2, :] = 1.0 - scanline_amount
    y_coords, x_coords = np.mgrid[-1:1:h*1j, -1:1:w*1j]
    wave = np.sin(y_coords * np.pi * 4 + x_coords * np.pi * 2) * scanline_amount * 5
    map_x = (x_coords * w/2 + w/2 + wave).astype(np.float32)
    map_y = (y_coords * h/2 + h/2).astype(np.float32)
    distorted_arr = cv2.remap(arr, map_x, map_y, interpolation=cv2.INTER_LINEAR)
    final_arr = np.clip(distorted_arr * scanlines, 0, 255).astype(np.uint8)
    return Image.fromarray(final_arr)

@safe_effect
def block_corruption(image_matrix: Image.Image, block_size: int, corruption_ratio: float, **kwargs) -> Image.Image:
    if corruption_ratio == 0 or block_size <= 1: return image_matrix
    arr = np.array(image_matrix)
    h, w, c = arr.shape
    bs = min(block_size, h, w)
    pad_h = (bs - h % bs) % bs; pad_w = (bs - w % bs) % bs
    padded = np.pad(arr, ((0, pad_h), (0, pad_w), (0, 0)), mode='constant')
    ph, pw, _ = padded.shape
    blocks = padded.reshape(ph//bs, bs, pw//bs, bs, c).swapaxes(1, 2).reshape(-1, bs, bs, c)
    indices = np.random.choice(len(blocks), size=int(len(blocks) * corruption_ratio), replace=False)
    np.random.shuffle(blocks[indices])
    corrupted_padded = blocks.reshape(ph//bs, pw//bs, bs, bs, c).swapaxes(1, 2).reshape(ph, pw, c)
    return Image.fromarray(corrupted_padded[:h, :w, :])

@safe_effect
def pixel_sorting(image_matrix: Image.Image, probability: float, threshold: float, **kwargs) -> Image.Image:
    if probability == 0: return image_matrix
    arr = np.array(image_matrix)
    rows_to_process = np.where(np.random.random(arr.shape[0]) < probability)[0]
    brightness = np.dot(arr[...,:3], [0.2989, 0.5870, 0.1140])
    for y in rows_to_process:
        row_brightness = brightness[y]
        mask = row_brightness >= (threshold * 255)
        if not np.any(mask): continue
        pixels_to_sort = arr[y, mask]
        arr[y, mask] = np.sort(pixels_to_sort, axis=0) if random.random() > 0.5 else np.sort(pixels_to_sort, axis=0)[::-1]
    return Image.fromarray(arr)

@safe_effect
def rgb_shift(image_matrix: Image.Image, shift_x: int, shift_y: int, **kwargs) -> Image.Image:
    if shift_x == 0 and shift_y == 0: return image_matrix
    arr = np.array(image_matrix)
    r, g, b = arr[:,:,0], arr[:,:,1], arr[:,:,2]
    r_shifted = np.roll(r, int(shift_x * (random.random() * 0.5 + 0.5)), axis=1)
    b_shifted = np.roll(b, -int(shift_x * (random.random() * 0.5 + 0.5)), axis=1)
    g_shifted = np.roll(g, int(shift_y * (random.random() * 0.5 + 0.5)), axis=0)
    return Image.fromarray(np.stack([r_shifted, g_shifted, b_shifted], axis=-1))

@safe_effect
def jpeg_artifacts(image_matrix: Image.Image, quality: int, cycles: int, **kwargs) -> Image.Image:
    if cycles == 0: return image_matrix
    img = image_matrix.copy()
    for _ in range(cycles):
        buffer = io.BytesIO()
        img.save(buffer, format='JPEG', quality=quality)
        buffer.seek(0)
        img = Image.open(buffer)
    return img

@safe_effect
def analog_noise(image_matrix: Image.Image, noise_amount: float, mono: bool, **kwargs) -> Image.Image:
    if noise_amount == 0: return image_matrix
    arr = np.array(image_matrix, dtype=np.float32)
    sigma = noise_amount * 128
    noise_shape = (arr.shape[0], arr.shape[1], 1) if mono else arr.shape
    noise = np.random.normal(0, sigma, noise_shape)
    noisy_arr = np.clip(arr + noise, 0, 255).astype(np.uint8)
    if noise_amount > 0.05:
        return Image.fromarray(noisy_arr).filter(ImageFilter.GaussianBlur(radius=1))
    return Image.fromarray(noisy_arr)

@safe_effect
def lens_distortion(image_matrix: Image.Image, distortion_strength: float, **kwargs) -> Image.Image:
    if distortion_strength == 0: return image_matrix
    arr = np.array(image_matrix); h, w, _ = arr.shape
    camera_matrix = np.array([[w, 0, w/2], [0, h, h/2], [0, 0, 1]], dtype=np.float32)
    dist_coeffs = np.array([distortion_strength, 0, 0, 0], dtype=np.float32)
    new_camera_matrix, roi = cv2.getOptimalNewCameraMatrix(camera_matrix, dist_coeffs, (w, h), 1, (w, h))
    distorted_arr = cv2.undistort(arr, camera_matrix, dist_coeffs, None, new_camera_matrix)
    x, y, w_roi, h_roi = roi; distorted_arr = distorted_arr[y:y+h_roi, x:x+w_roi]
    return Image.fromarray(distorted_arr)

@safe_effect
def chromatic_aberration(image_matrix: Image.Image, aberration_strength: int, **kwargs) -> Image.Image:
    if aberration_strength == 0: return image_matrix
    arr = np.array(image_matrix); h, w, _ = arr.shape
    r, g, b = cv2.split(arr); scale_factor = 1.0 + (aberration_strength / 1000.0)
    center_x, center_y = w // 2, h // 2
    M_r = np.array([[scale_factor, 0, (1 - scale_factor) * center_x], [0, scale_factor, (1 - scale_factor) * center_y]], dtype=np.float32)
    inv_scale_factor = 1.0 / scale_factor
    M_b = np.array([[inv_scale_factor, 0, (1 - inv_scale_factor) * center_x], [0, inv_scale_factor, (1 - inv_scale_factor) * center_y]], dtype=np.float32)
    r_aberrated = cv2.warpAffine(r, M_r, (w, h)); b_aberrated = cv2.warpAffine(b, M_b, (w, h))
    aberrated_arr = cv2.merge([r_aberrated, g, b_aberrated])
    return Image.fromarray(aberrated_arr)

# ==============================================================================
# PIPELINE, CONFIGS, AND PRESETS
# ==============================================================================
EFFECT_FUNCTIONS = {
    'B&W Control': black_and_white_control, 'Cinematic Blur': cinematic_blur, 'Motion Blur': motion_blur,
    'Low-Res FX': low_res_effect, 'Film Grain': film_grain, 'Texture Overlay': texture_overlay,
    'Slit-Scan FX': slit_scan_effect, 'Bloom & Glare': bloom_glare, '8-Bit Crush': pixel_art_conversion,
    'Datamosh': datamosh_corruption, 'Block Corruption': block_corruption, 'CRT Scanlines': crt_scanlines,
    'Pixel Sorting': pixel_sorting, 'RGB Shift': rgb_shift, 'JPEG Artifacts': jpeg_artifacts,
    'Analog Noise': analog_noise, 'Lens Distortion': lens_distortion, 'Chromatic Aberration': chromatic_aberration
}

EFFECT_CONFIG = {
    'B&W Control': {'params': {
        'bw_apply': {'label': 'Enable B&W Mode', 'component': gr.Checkbox, 'args': {'value': False}},
        'bw_contrast': {'label': 'Contrast', 'component': gr.Slider, 'args': {'minimum': 0.1, 'maximum': 3.0, 'value': 1.0}},
        'bw_brightness': {'label': 'Brightness', 'component': gr.Slider, 'args': {'minimum': 0.1, 'maximum': 3.0, 'value': 1.0}},
    }},
    'Cinematic Blur': {'params': {'film_blur_radius': {'label': 'Blur Radius', 'component': gr.Slider, 'args': {'minimum': 0, 'maximum': 10, 'value': 0}}}},
    'Motion Blur': {'params': {
        'motion_blur_intensity': {'label': 'Intensity', 'component': gr.Slider, 'args': {'minimum': 0, 'maximum': 50, 'step': 1, 'value': 0}},
        'motion_blur_angle': {'label': 'Angle', 'component': gr.Slider, 'args': {'minimum': 0, 'maximum': 360, 'step': 1, 'value': 0}},
    }},
    'Low-Res FX': {'params': {'low_res_factor': {'label': 'Downscale Factor', 'component': gr.Slider, 'args': {'minimum': 1, 'maximum': 16, 'step': 1, 'value': 1}}}},
    'Film Grain': {'params': {'film_grain_amount': {'label': 'Grain Amount', 'component': gr.Slider, 'args': {'minimum': 0, 'maximum': 1, 'value': 0}}}},
    'Texture Overlay': {'params': {
        'texture_type': {'label': 'Texture Type', 'component': gr.Dropdown, 'args': {'choices': ['None', 'Scan Lines', 'Dust & Scratches', 'VHS Lines'], 'value': 'None'}},
        'texture_opacity': {'label': 'Opacity', 'component': gr.Slider, 'args': {'minimum': 0, 'maximum': 1, 'value': 0}}
    }},
    'Slit-Scan FX': {'params': {
        'slit_scan_amount': {'label': 'Distortion Amount', 'component': gr.Slider, 'args': {'minimum': 0, 'maximum': 200, 'step': 1, 'value': 0}},
        'slit_scan_freq': {'label': 'Wave Frequency', 'component': gr.Slider, 'args': {'minimum': 0.1, 'maximum': 10, 'value': 2.0}},
    }},
    'Bloom & Glare': {'params': {
        'bloom_threshold': {'label': 'Bloom Threshold', 'component': gr.Slider, 'args': {'minimum': 0, 'maximum': 1, 'value': 0.8}},
        'bloom_radius': {'label': 'Bloom Radius', 'component': gr.Slider, 'args': {'minimum': 0, 'maximum': 100, 'step': 1, 'value': 0}},
        'haze_amount': {'label': 'Haze Amount', 'component': gr.Slider, 'args': {'minimum': 0, 'maximum': 1, 'value': 0}}
    }},
    '8-Bit Crush': {'params': {
        'pixel_size': {'label': 'Pixel Size', 'component': gr.Slider, 'args': {'minimum': 1, 'maximum': 32, 'step': 1, 'value': 1}},
        'eight_bit_colors': {'label': 'Color Palette Size', 'component': gr.Slider, 'args': {'minimum': 2, 'maximum': 256, 'step': 1, 'value': 256}},
        'eight_bit_dither': {'label': 'Apply Dithering', 'component': gr.Checkbox, 'args': {'value': True}}
    }},
    'Datamosh': {'params': {'datamosh_amount': {'label': 'Corruption Amount', 'component': gr.Slider, 'args': {'minimum': 0, 'maximum': 1, 'value': 0.0}}}},
    'Block Corruption': {'params': {
        'block_size': {'label': 'Block Size (px)', 'component': gr.Slider, 'args': {'minimum': 0, 'maximum': 64, 'step': 2, 'value': 0}},
        'corruption_ratio': {'label': 'Corruption Ratio', 'component': gr.Slider, 'args': {'minimum': 0, 'maximum': 1, 'value': 0}}
    }},
    'CRT Scanlines': {'params': {'scanline_amount': {'label': 'Intensity', 'component': gr.Slider, 'args': {'minimum': 0, 'maximum': 1, 'value': 0.0}}}},
    'Pixel Sorting': {'params': {
        'probability': {'label': 'Row Probability', 'component': gr.Slider, 'args': {'minimum': 0, 'maximum': 1, 'value': 0.0}},
        'threshold': {'label': 'Brightness Threshold', 'component': gr.Slider, 'args': {'minimum': 0, 'maximum': 1, 'value': 0.25}}
    }},
    'RGB Shift': {'params': {
        'shift_x': {'label': 'Horizontal Shift', 'component': gr.Slider, 'args': {'minimum': 0, 'maximum': 100, 'step': 1, 'value': 0}},
        'shift_y': {'label': 'Vertical Shift', 'component': gr.Slider, 'args': {'minimum': 0, 'maximum': 100, 'step': 1, 'value': 0}}
    }},
    'JPEG Artifacts': {'params': {
        'quality': {'label': 'JPEG Quality', 'component': gr.Slider, 'args': {'minimum': 1, 'maximum': 100, 'step': 1, 'value': 100}},
        'cycles': {'label': 'Re-compression Cycles', 'component': gr.Slider, 'args': {'minimum': 0, 'maximum': 10, 'step': 1, 'value': 0}}
    }},
    'Analog Noise': {'params': {
        'noise_amount': {'label': 'Noise Amount', 'component': gr.Slider, 'args': {'minimum': 0, 'maximum': 1, 'value': 0.0}},
        'mono': {'label': 'Monochromatic Noise', 'component': gr.Checkbox, 'args': {'value': True}}
    }},
    'Lens Distortion': {'params': {'distortion_strength': {'label': 'Distortion Strength', 'component': gr.Slider, 'args': {'minimum': -0.5, 'maximum': 0.5, 'value': 0.0}}}},
    'Chromatic Aberration': {'params': {'aberration_strength': {'label': 'Aberration Strength', 'component': gr.Slider, 'args': {'minimum': 0, 'maximum': 50, 'step': 1, 'value': 0}}}},
}

ALL_PARAM_KEYS = [param_name for effect in EFFECT_CONFIG.values() for param_name in effect['params'].keys()]
DEFAULT_PRESET_VALS = {key: cfg['params'][key]['args']['value'] for cfg in EFFECT_CONFIG.values() for key in cfg['params']}

PRESETS = {
    'Subtle Anomaly': {**DEFAULT_PRESET_VALS, 'scanline_amount': 0.05, 'probability': 0.02, 'shift_x': 2, 'shift_y': 1, 'quality': 95, 'cycles': 1, 'noise_amount': 0.03},
    'Vaporwave Dream': {**DEFAULT_PRESET_VALS, 'scanline_amount': 0.2, 'shift_x': 15, 'shift_y': 5, 'quality': 70, 'cycles': 1, 'noise_amount': 0.1, 'mono': False, 'pixel_size': 2, 'eight_bit_colors': 128, 'aberration_strength': 20},
    'Surveillance Ghost': {**DEFAULT_PRESET_VALS, 'block_size': 16, 'corruption_ratio': 0.05, 'scanline_amount': 0.4, 'shift_x': 5, 'shift_y': 2, 'quality': 40, 'cycles': 3, 'noise_amount': 0.3, 'pixel_size': 4, 'eight_bit_colors': 64, 'eight_bit_dither': False, 'distortion_strength': 0.2},
    'Data Drain': {**DEFAULT_PRESET_VALS, 'datamosh_amount': 0.2, 'block_size': 8, 'corruption_ratio': 0.2, 'probability': 0.1, 'shift_x': 8, 'shift_y': 8, 'quality': 25, 'cycles': 2, 'noise_amount': 0.05},
    'Deepfried Datacrash': {**DEFAULT_PRESET_VALS, 'datamosh_amount': 0.8, 'block_size': 32, 'corruption_ratio': 0.7, 'scanline_amount': 0.1, 'probability': 0.7, 'shift_x': 50, 'shift_y': 50, 'quality': 2, 'cycles': 8, 'noise_amount': 0.2, 'mono': False, 'pixel_size': 8, 'eight_bit_colors': 16, 'eight_bit_dither': False},
    'Retro Gameboy': {**DEFAULT_PRESET_VALS, 'scanline_amount': 0.25, 'shift_x': 1, 'shift_y': 1, 'noise_amount': 0.15, 'pixel_size': 12, 'eight_bit_colors': 4},
    'Cursed Bitmap': {**DEFAULT_PRESET_VALS, 'datamosh_amount': 0.4, 'probability': 0.05, 'pixel_size': 6, 'eight_bit_colors': 16, 'eight_bit_dither': False},
    'Nightdrive Glitch': {**DEFAULT_PRESET_VALS, 'scanline_amount': 0.3, 'shift_x': 20, 'shift_y': 3, 'quality': 60, 'cycles': 1, 'noise_amount': 0.1, 'mono': False, 'pixel_size': 3, 'eight_bit_colors': 64, 'aberration_strength': 10},
    'Dreamy Haze': {**DEFAULT_PRESET_VALS, 'bloom_threshold': 0.7, 'bloom_radius': 60, 'haze_amount': 0.25, 'noise_amount': 0.05, 'shift_x': 2, 'shift_y': 2, 'aberration_strength': 5},
    'Analog Decay': {**DEFAULT_PRESET_VALS, 'distortion_strength': 0.1, 'aberration_strength': 15, 'scanline_amount': 0.1, 'quality': 80, 'cycles': 1, 'noise_amount': 0.08, 'mono': False},
    'Faded Memory': {**DEFAULT_PRESET_VALS, 'bw_apply': True, 'bw_contrast': 0.8, 'bw_brightness': 1.2, 'film_grain_amount': 0.15, 'texture_type': 'Dust & Scratches', 'texture_opacity': 0.4, 'film_blur_radius': 1.5, 'aberration_strength': 5},
    'VHS Glitch': {**DEFAULT_PRESET_VALS, 'scanline_amount': 0.3, 'shift_x': 10, 'shift_y': 3, 'quality': 50, 'cycles': 2, 'aberration_strength': 15, 'distortion_strength': 0.05, 'texture_type': 'VHS Lines', 'texture_opacity': 0.7, 'low_res_factor': 2},
}

# ==============================================================================
# GRADIO CORE CONTROLLER & INTERFACE
# ==============================================================================
def resize_image_if_needed(img: Optional[Image.Image]) -> Optional[Image.Image]:
    if img and (img.width > MAX_DIMENSION or img.height > MAX_DIMENSION):
        gr.Info(f"Large image detected. Resizing to {MAX_DIMENSION}px for optimal performance.")
        img.thumbnail((MAX_DIMENSION, MAX_DIMENSION), Image.Resampling.LANCZOS)
    return img

def master_controller(original_image, batch_size, base_seed, active_effects, *all_params) -> Iterator[Dict]:
    if original_image is None:
        gr.Warning(">> NO INPUT DETECTED. UPLOAD AN IMAGE TO BEGIN REALITY ALTERATION. <<")
        yield {ui_components['log_output']: gr.update(value="[ERROR] NO IMAGE DATA IN BUFFER. AWAITING INPUT.")}
        return
    params = dict(zip(ALL_PARAM_KEYS, all_params))
    batch_size = int(batch_size)
    seeds = [base_seed + i for i in range(batch_size)]
    log = [f"GLITCHCRAFT NEXUS v3.5 -- 'Chronos' Edition Online.", f"Batch Size: {batch_size} | Base Seed: {base_seed}"]
    yield {ui_components['log_output']: gr.update(value="\n".join(log)), ui_components['sys_kernel']: gr.update(value=f"{random.uniform(5,10):.1f}%"), ui_components['sys_mem']: gr.update(value=f"{random.uniform(95,99):.1f}%"), ui_components['sys_anom']: gr.update(value="0")}
    final_batch_images = []
    for i, seed in enumerate(seeds):
        log.append(f"\n[BATCH {i+1}/{batch_size}] Processing with Seed {seed}...")
        random.seed(seed); np.random.seed(seed)
        image = original_image.convert('RGB')
        steps_data = [(image.copy(), "Original")]
        effects_to_run = [fx for fx in active_effects if fx in EFFECT_FUNCTIONS]
        for name in effects_to_run:
            func = EFFECT_FUNCTIONS[name]
            image, log = func(image_matrix=image, log=log, **params)
            steps_data.append((image.copy(), name))
            yield {ui_components['log_output']: gr.update(value="\n".join(log)), ui_components['sys_kernel']: gr.update(value=f"{random.uniform(20,80):.1f}%"), ui_components['sys_mem']: gr.update(value=f"{random.uniform(80,95):.1f}%"), ui_components['sys_anom']: gr.update(value=str(int(params.get('datamosh_amount',0)*100 + params.get('corruption_ratio',0)*50)))}
        final_batch_images.append(image)
        log.append(f"[ OK ] Seed {seed} processed successfully.")
        yield {ui_components['log_output']: gr.update(value="\n".join(log))}
    log.append("\n[SUCCESS] All batch operations complete. Packaging artifacts..."); yield {ui_components['log_output']: gr.update(value="\n".join(log)),}
    try:
        with tempfile.NamedTemporaryFile(suffix=".gif", delete=False) as tmp_gif, tempfile.NamedTemporaryFile(suffix=".zip", delete=False) as tmp_zip:
            gif_path, zip_path = tmp_gif.name, tmp_zip.name
            images_for_gif = [step_img for step_img, _ in steps_data]
            images_for_gif[0].save(gif_path, save_all=True, append_images=images_for_gif[1:], duration=350, loop=0, optimize=True)
            with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
                for i_zip, img_zip in enumerate(final_batch_images):
                    byte_io = io.BytesIO(); img_zip.save(byte_io, 'PNG'); byte_io.seek(0)
                    zf.writestr(f"result_seed_{seeds[i_zip]}.png", byte_io.getvalue())
        log.append("[ OK ] Artifacts packaged. Mission accomplished.")
    except Exception as e:
        log.append(f"[CRITICAL_FAIL] Could not generate download files. Reason: {e}")
        gif_path, zip_path = None, None
    yield {
        ui_components['log_output']: gr.update(value="\n".join(log)), ui_components['hero_output']: gr.update(value=final_batch_images[0]),
        ui_components['gallery_output']: gr.update(value=final_batch_images), ui_components['gif_output']: gr.update(value=gif_path),
        ui_components['zip_output']: gr.update(value=zip_path), ui_components['output_tabs']: gr.update(selected="gallery_tab"),
        ui_components['sys_kernel']: gr.update(value="1.0%"), ui_components['sys_mem']: gr.update(value="99.9%"), ui_components['sys_anom']: gr.update(value="0"),
    }

def apply_preset(preset_name: str) -> List[Any]:
    preset_values = PRESETS.get(preset_name, {})
    # Ensure all keys are present, falling back to default if a preset is old
    updated_values = {**DEFAULT_PRESET_VALS, **preset_values}
    return [gr.update(value=updated_values.get(key)) for key in ALL_PARAM_KEYS]

with gr.Blocks(theme=gr.themes.Monochrome(font=gr.themes.GoogleFont("Share Tech Mono")), css=HACKER_TERMINAL_CSS) as demo:
    gr.Markdown("<h1 class='main-title'>> GLITCHCRAFT NEXUS // KUSANAGI <</h1>")
    original_image_state = gr.State()
    ui_components = {}
    all_param_components = []
    with gr.Row():
        with gr.Column(scale=1, min_width=350):
            with gr.Group(elem_classes=["pro-panel"]):
                gr.Markdown("### > 1_SYSTEM_INPUT"); ui_components['image_input'] = gr.Image(type="pil", label="UPLOAD DATA PACKET", height=250)
            with gr.Group(elem_classes=["pro-panel"]):
                gr.Markdown("### > 2_EXECUTION_PARAMS"); ui_components['active_effects'] = gr.CheckboxGroup(choices=list(EFFECT_FUNCTIONS.keys()), value=list(EFFECT_FUNCTIONS.keys()), label="ACTIVE SUB-ROUTINES")
                with gr.Accordion("SEED & BATCH CONFIG", open=True):
                    ui_components['seed_input'] = gr.Number(label="Base Seed", value=int(time.time() % 1e9), precision=0)
                    ui_components['randomize_seed_btn'] = gr.Button("New Random Seed 🎲")
                    ui_components['batch_size_input'] = gr.Slider(minimum=1, maximum=20, value=1, step=1, label="Batch Size")
            with gr.Group(elem_classes=["pro-panel"]):
                gr.Markdown("### > 3_PRESET_PROTOCOLS")
                preset_buttons = []; preset_names = list(PRESETS.keys())
                for i in range(0, len(preset_names), 3):
                     with gr.Row():
                        for name in preset_names[i:i+3]: preset_buttons.append(gr.Button(name))
            with gr.Group(elem_classes=["pro-panel"]):
                gr.Markdown("### > 4_PARAMETER_MATRIX")
                for effect_name in EFFECT_FUNCTIONS.keys():
                    if effect_name not in EFFECT_CONFIG: continue
                    config = EFFECT_CONFIG[effect_name]
                    with gr.Accordion(f"> {effect_name.upper()}", open=False):
                        for param_name, param_config in config['params'].items():
                            param_component = param_config['component'](label=param_config['label'], **param_config['args'])
                            all_param_components.append(param_component); ui_components[param_name] = param_component
            ui_components['generate_button'] = gr.Button(">>> INJECT CHAOS <<<", variant="primary", scale=2)
        with gr.Column(scale=2, min_width=600):
            with gr.Tabs(elem_id="output_tabs") as output_tabs:
                with gr.TabItem("🖼️ PRIMARY_VIEWPORT", id="gallery_tab"):
                    ui_components['hero_output'] = gr.Image(label="Main Result", interactive=False); ui_components['gallery_output'] = gr.Gallery(label="Batch Results", columns=4, height=400, object_fit="contain", preview=True)
                with gr.TabItem("📦 ARTIFACT_DOWNLOAD", id="downloads_tab"):
                    ui_components['gif_output'] = gr.File(label="Download Process Trace (GIF)"); ui_components['zip_output'] = gr.File(label="Download Full Batch (ZIP)")
            with gr.Group(elem_classes=["pro-panel", "sys-monitor"]):
                gr.Markdown("### > SYSTEM_MONITOR")
                with gr.Row(): ui_components['sys_kernel'] = gr.Label(label="KERNEL LOAD", value="0.0%"); ui_components['sys_mem'] = gr.Label(label="MEM INTEGRITY", value="100.0%"); ui_components['sys_anom'] = gr.Label(label="ANOMALIES", value="0")
            with gr.Group(elem_classes=["pro-panel"]):
                gr.Markdown("### > LIVE_TERMINAL_LOG"); ui_components['log_output'] = gr.Textbox(label="", lines=20, max_lines=20, interactive=False, elem_classes=["log-output"])
    ui_components['output_tabs'] = output_tabs
    def store_and_resize(img): return (r := resize_image_if_needed(img)), r, "[OK] Image data loaded. Ready."
    ui_components['image_input'].upload(fn=store_and_resize, inputs=[ui_components['image_input']], outputs=[ui_components['image_input'], original_image_state, ui_components['log_output']])
    ui_components['generate_button'].click(fn=master_controller, inputs=[original_image_state, ui_components['batch_size_input'], ui_components['seed_input'], ui_components['active_effects'], *all_param_components], outputs=list(ui_components.values()))
    for button in preset_buttons: button.click(fn=apply_preset, inputs=[gr.State(button.value)], outputs=all_param_components)
    ui_components['randomize_seed_btn'].click(fn=lambda: random.randint(0, 1_000_000_000), outputs=[ui_components['seed_input']])

if __name__ == "__main__":
    demo.launch(debug=True, show_error=True)