Anuran66 commited on
Commit
6df5dab
·
verified ·
1 Parent(s): 8467fbd

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +640 -0
app.py ADDED
@@ -0,0 +1,640 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import cv2
3
+ import time
4
+ import datetime
5
+ import tempfile
6
+ import numpy as np
7
+ import warnings
8
+ import psutil
9
+ import gradio as gr
10
+ import plotly.graph_objects as go
11
+ import matplotlib.pyplot as plt
12
+
13
+ # ==============================================================================
14
+ # 0. HARDWARE & ZERO-GPU INTEGRATION
15
+ # ==============================================================================
16
+ java8_opts = (
17
+ "-XX:+IgnoreUnrecognizedVMOptions --add-opens=java.base/java.lang=ALL-UNNAMED "
18
+ "--add-opens=java.base/java.lang.invoke=ALL-UNNAMED --add-opens=java.base/java.lang.reflect=ALL-UNNAMED "
19
+ "--add-opens=java.base/java.io=ALL-UNNAMED --add-opens=java.base/java.net=ALL-UNNAMED "
20
+ "--add-opens=java.base/java.nio=ALL-UNNAMED --add-opens=java.base/java.util=ALL-UNNAMED "
21
+ "--add-opens=java.base/java.util.concurrent=ALL-UNNAMED --add-opens=java.base/java.util.concurrent.atomic=ALL-UNNAMED "
22
+ "--add-opens=java.base/jdk.internal.ref=ALL-UNNAMED --add-opens=java.base/sun.nio.ch=ALL-UNNAMED "
23
+ "--add-opens=java.base/sun.nio.cs=ALL-UNNAMED --add-opens=java.base/sun.security.action=ALL-UNNAMED "
24
+ "--add-opens=java.base/sun.util.calendar=ALL-UNNAMED --add-opens=java.security.jgss/sun.security.krb5=ALL-UNNAMED"
25
+ )
26
+ os.environ["PYSPARK_SUBMIT_ARGS"] = f'--driver-java-options "{java8_opts}" pyspark-shell'
27
+ os.environ["SPARK_LOCAL_IP"] = "127.0.0.1"
28
+
29
+ # Hugging Face ZeroGPU Allocation logic
30
+ try:
31
+ import spaces
32
+ gpu_decorator = spaces.GPU
33
+ except ImportError:
34
+ def gpu_decorator(fn): return fn # Fallback if running locally without the spaces library
35
+
36
+ try:
37
+ import torch
38
+ import torch.nn.functional as F
39
+ HAS_TORCH = True
40
+ except ImportError:
41
+ HAS_TORCH = False
42
+
43
+ try:
44
+ from pyspark.sql import SparkSession
45
+ HAS_SPARK = True
46
+ except ImportError:
47
+ HAS_SPARK = False
48
+
49
+ try:
50
+ from fpdf import FPDF
51
+ HAS_FPDF = True
52
+ except ImportError:
53
+ HAS_FPDF = False
54
+
55
+ warnings.filterwarnings('ignore')
56
+
57
+ # ==============================================================================
58
+ # 1. CORE PHYSICS ENGINE (CMOS DNA & Spectral Analysis)
59
+ # ==============================================================================
60
+ class UnbiasedPhysicsForensics:
61
+ def __init__(self, image_path, max_dim=600, patch_size=128, stride=64):
62
+ self.image_path = image_path
63
+ self.filename = os.path.basename(image_path)
64
+ self.patch_size = patch_size
65
+ self.stride = stride
66
+ self.device = 'cuda' if torch.cuda.is_available() else 'cpu'
67
+
68
+ img = cv2.imread(image_path, cv2.IMREAD_UNCHANGED)
69
+ self.valid = False
70
+
71
+ if img is not None:
72
+ if len(img.shape) == 2: img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
73
+ elif len(img.shape) == 3 and img.shape[2] == 4: img = img[:, :, :3]
74
+ if img.dtype == np.uint16: img = (img / 256).astype(np.uint8)
75
+
76
+ h, w = img.shape[:2]
77
+ if max(h, w) > max_dim:
78
+ scale = max_dim / max(h, w)
79
+ img = cv2.resize(img, (int(w * scale), int(h * scale)), interpolation=cv2.INTER_AREA)
80
+
81
+ self.img_bgr = img
82
+ self.img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
83
+ self.h, self.w = self.img_bgr.shape[:2]
84
+ self.valid = True
85
+
86
+ def _extract_patches(self, tensor):
87
+ tensor = tensor.to(self.device)
88
+ c, h, w = tensor.shape
89
+ pad_h = max(0, self.patch_size - h) if h < self.patch_size else 0
90
+ pad_w = max(0, self.patch_size - w) if w < self.patch_size else 0
91
+ if pad_h > 0 or pad_w > 0:
92
+ tensor = F.pad(tensor, (0, pad_w, 0, pad_h), mode='reflect')
93
+ _, h, w = tensor.shape
94
+
95
+ n_h = (h - self.patch_size) // self.stride + 1
96
+ n_w = (w - self.patch_size) // self.stride + 1
97
+ patches = tensor.unfold(1, self.patch_size, self.stride).unfold(2, self.patch_size, self.stride)
98
+ patches = patches.contiguous().view(c, -1, self.patch_size, self.patch_size).permute(1, 0, 2, 3)
99
+ return patches, n_h, n_w
100
+
101
+ def analyze_global_spectrum(self):
102
+ gray = cv2.cvtColor(self.img_bgr, cv2.COLOR_BGR2GRAY)
103
+ f = np.fft.fft2(gray)
104
+ power = np.abs(np.fft.fftshift(f))**2
105
+
106
+ h, w = power.shape
107
+ cy, cx = h // 2, w // 2
108
+ y, x = np.indices((h, w))
109
+ r = np.sqrt((x - cx)**2 + (y - cy)**2).astype(int)
110
+
111
+ tbin = np.bincount(r.ravel(), power.ravel())
112
+ nr = np.bincount(r.ravel())
113
+ radial_profile = tbin / np.maximum(nr, 1)
114
+
115
+ r_vals = np.arange(1, len(radial_profile))
116
+ p_vals = radial_profile[1:]
117
+
118
+ log_r = np.log10(r_vals)
119
+ log_p = np.log10(p_vals + 1e-10)
120
+ slope, intercept = np.polyfit(log_r, log_p, 1)
121
+
122
+ alpha = -slope * 0.70
123
+
124
+ ai_score = 0.0
125
+ if 2.0 <= alpha <= 3.5: ai_score = 99.9
126
+ elif alpha < 2.0: ai_score = max(((alpha - 1.0) / 1.0) * 49.9, 0.0)
127
+ else: ai_score = max(((4.5 - alpha) / 1.0) * 49.9, 0.0)
128
+
129
+ return min(max(ai_score, 0), 99.9), alpha, r_vals, p_vals, intercept
130
+
131
+ def compute_rgb_matrix(self, max_chroma_z):
132
+ pixels = self.img_rgb.reshape(-1, 3).astype(np.float32) / 255.0
133
+ rgb_corr = np.corrcoef(pixels.T)
134
+ violation = False
135
+ reason = "Channels Intact (Normal Physical Overlap)"
136
+
137
+ if np.isnan(rgb_corr).any():
138
+ rgb_corr = np.nan_to_num(rgb_corr, nan=0.1)
139
+ violation = True
140
+ if max_chroma_z > 3.5:
141
+ violation = True
142
+ reason = f"Color Chroma Anomaly ({max_chroma_z:.2f} Z) forced channel detachment."
143
+ for i in range(3):
144
+ for j in range(3):
145
+ if i != j: rgb_corr[i, j] *= (1.5 / max_chroma_z)
146
+ elif np.min(rgb_corr) < 0.25:
147
+ violation = True
148
+ reason = "Natural physical channel correlation broken (<0.25)."
149
+
150
+ return rgb_corr, violation, reason
151
+
152
+ def analyze(self):
153
+ def robust_z(pts):
154
+ m = torch.median(pts)
155
+ return 0.6745 * torch.abs(pts - m) / (torch.median(torch.abs(pts - m)) + 1e-3)
156
+
157
+ _, enc = cv2.imencode('.jpg', self.img_bgr, [int(cv2.IMWRITE_JPEG_QUALITY), 90])
158
+ diff = torch.abs(torch.from_numpy(self.img_bgr).float().to(self.device) - torch.from_numpy(cv2.imdecode(enc, cv2.IMREAD_COLOR)).float().to(self.device)).mean(dim=2)
159
+ p_ela, n_h, n_w = self._extract_patches(diff.unsqueeze(0))
160
+ z_ela = robust_z(torch.var(p_ela.view(p_ela.shape[0], -1), dim=1)).to('cpu')
161
+
162
+ gray = cv2.cvtColor(self.img_bgr, cv2.COLOR_BGR2GRAY)
163
+ t_gray = torch.from_numpy(gray).float().unsqueeze(0).unsqueeze(0).to(self.device)
164
+ kernel = torch.tensor([[[[0., 1., 0.], [1., -4., 1.], [0., 1., 0.]]]]).to(self.device)
165
+ noise_map = F.conv2d(t_gray, kernel, padding=1).squeeze(0)
166
+ p_noise, _, _ = self._extract_patches(noise_map)
167
+ z_noise = robust_z(torch.var(p_noise.view(p_noise.shape[0], -1), dim=1)).to('cpu')
168
+
169
+ ycc = cv2.cvtColor(self.img_bgr, cv2.COLOR_BGR2YCrCb)
170
+ t_ycc = torch.from_numpy(ycc).float().permute(2, 0, 1).to(self.device)
171
+ p_chroma, _, _ = self._extract_patches(t_ycc)
172
+ y_var = torch.var(p_chroma[:, 0, :, :].reshape(p_chroma.shape[0], -1), dim=1) + 1e-5
173
+ z_chroma = robust_z((torch.var(p_chroma[:, 1, :, :].reshape(p_chroma.shape[0], -1), dim=1) +
174
+ torch.var(p_chroma[:, 2, :, :].reshape(p_chroma.shape[0], -1), dim=1)) / y_var).to('cpu')
175
+
176
+ max_ela = torch.quantile(z_ela.float(), 0.98).item()
177
+ max_noise = torch.quantile(z_noise.float(), 0.98).item()
178
+ max_chroma_val = torch.quantile(z_chroma.float(), 0.98).item()
179
+
180
+ rgb_corr, rgb_violation, rgb_reason = self.compute_rgb_matrix(max_chroma_val)
181
+ combined_z = (z_ela + z_noise + z_chroma) / 3.0
182
+ z_grid = combined_z.view(n_h, n_w).numpy()
183
+
184
+ ela_norm = max(0.0, min(((max_ela - 2.5) / 1.5) * 100.0, 100.0))
185
+ noise_norm = max(0.0, min(((max_noise - 2.5) / 1.5) * 100.0, 100.0))
186
+ chroma_norm = max(0.0, min(((max_chroma_val - 2.5) / 1.5) * 100.0, 100.0))
187
+ rgb_norm = 100.0 if rgb_violation else 0.0
188
+
189
+ sub_metric_composite = (ela_norm * 0.25) + (noise_norm * 0.35) + (chroma_norm * 0.20) + (rgb_norm * 0.20)
190
+ global_fake_prob, alpha_val, r_vals, p_vals, intercept = self.analyze_global_spectrum()
191
+
192
+ weight_sub_metrics = 0.60 if global_fake_prob > 80.0 else 0.70
193
+ weight_fft = 0.40 if global_fake_prob > 80.0 else 0.30
194
+ final_fake_prob = (sub_metric_composite * weight_sub_metrics) + (global_fake_prob * weight_fft)
195
+
196
+ cluster_ratio = torch.sum(combined_z > 3.5).item() / combined_z.shape[0]
197
+ internal_threat_flags = sum([1 for metric in [max_ela/3.5, max_noise/3.5, max_chroma_val/3.5, rgb_violation, cluster_ratio/0.02] if metric >= 1.0])
198
+
199
+ return {
200
+ "Filename": self.filename,
201
+ "Fake_Prob": min(final_fake_prob, 99.9),
202
+ "Sub_Metric_Score": sub_metric_composite,
203
+ "Global_Prob": global_fake_prob,
204
+ "Threat_Flags": internal_threat_flags,
205
+ "Max_Z": {"ELA": max_ela, "CMOS_DNA": max_noise, "Chroma": max_chroma_val},
206
+ "Z_Arrays": {"ELA": z_ela.numpy().flatten(), "CMOS_DNA": z_noise.numpy().flatten(), "Chroma": z_chroma.numpy().flatten()},
207
+ "RGB_Matrix": rgb_corr,
208
+ "RGB_Violation": rgb_violation,
209
+ "RGB_Reason": rgb_reason,
210
+ "Alpha_Val": alpha_val,
211
+ "R_Vals": r_vals, "P_Vals": p_vals, "Intercept": intercept,
212
+ "Z_Grid": z_grid,
213
+ "Image": self.img_rgb
214
+ }
215
+
216
+ def process_file_wrapper(fpath):
217
+ engine = UnbiasedPhysicsForensics(fpath)
218
+ if engine.valid: return engine.analyze()
219
+ return None
220
+
221
+ # ==============================================================================
222
+ # 2. PDF REPORT GENERATOR
223
+ # ==============================================================================
224
+ def generate_pdf_report_gradio(data):
225
+ if not HAS_FPDF: return None
226
+
227
+ pdf = FPDF()
228
+ pdf.set_auto_page_break(auto=True, margin=15)
229
+ pdf.add_page()
230
+
231
+ pdf.set_font('Arial', 'B', 18)
232
+ pdf.cell(0, 10, f"DeepScan OS Telemetry: {data['Filename']}", ln=True, align='C')
233
+ pdf.set_font('Arial', '', 12)
234
+ pdf.cell(0, 10, f"Generated on: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}", ln=True, align='C')
235
+ pdf.ln(5)
236
+
237
+ pdf.set_font('Arial', 'B', 14)
238
+ pdf.cell(0, 10, "1. System Clearance Status", ln=True)
239
+ pdf.set_font('Arial', '', 12)
240
+ status = "SYNTHETIC ANOMALY DETECTED" if data['Fake_Prob'] >= 50 else "PHYSICAL PROVENANCE VERIFIED"
241
+ pdf.cell(0, 10, f"System Status: {status}", ln=True)
242
+ pdf.cell(0, 10, f"Aggregated Generative Probability: {data['Fake_Prob']:.1f}%", ln=True)
243
+ pdf.ln(5)
244
+
245
+ with tempfile.TemporaryDirectory() as tmpdir:
246
+ img_path = os.path.join(tmpdir, "base.jpg")
247
+ cv2.imwrite(img_path, cv2.cvtColor(data['Image'], cv2.COLOR_RGB2BGR))
248
+ pdf.image(img_path, x=10, w=90)
249
+
250
+ hm_path = os.path.join(tmpdir, "heatmap.jpg")
251
+ plt.figure(figsize=(4,3))
252
+ plt.imshow(data['Z_Grid'], cmap='magma', vmin=0, vmax=4.5)
253
+ plt.axis('off')
254
+ plt.tight_layout()
255
+ plt.savefig(hm_path)
256
+ plt.close()
257
+ pdf.image(hm_path, x=110, y=pdf.get_y()-65, w=90)
258
+ pdf.ln(70)
259
+
260
+ pdf.set_font('Arial', 'B', 14)
261
+ pdf.cell(0, 10, "2. Spectral Frequency-Domain Analysis", ln=True)
262
+ pdf.set_font('Arial', '', 12)
263
+ fft_path = os.path.join(tmpdir, "fft.png")
264
+
265
+ plt.figure(figsize=(8,4))
266
+ limit = min(200, len(data['R_Vals']))
267
+ x_freq = data['R_Vals'][1:limit]
268
+ y_actual_log = np.log10(data['P_Vals'][1:limit] + 1e-10)
269
+ y_upper = -2.0 * np.log10(x_freq) + data['Intercept']
270
+ y_lower = -3.5 * np.log10(x_freq) + data['Intercept']
271
+
272
+ plt.fill_between(x_freq, y_lower, y_upper, color='#ff007f', alpha=0.15, label='Threat Zone')
273
+ plt.plot(x_freq, y_upper, 'r--', alpha=0.5)
274
+ plt.plot(x_freq, y_lower, 'r--', alpha=0.5)
275
+
276
+ line_color = '#ff007f' if data['Global_Prob'] > 50 else '#00f2fe'
277
+ plt.plot(x_freq, y_actual_log, color=line_color, linewidth=2, label=f"Calibrated Signal (α={data['Alpha_Val']:.2f})")
278
+ plt.title(f"Power Spectrum Decay Score: {data['Global_Prob']:.1f}%")
279
+ plt.xscale('log')
280
+ plt.legend()
281
+ plt.savefig(fft_path)
282
+ plt.close()
283
+
284
+ pdf.image(fft_path, x=15, w=180)
285
+ pdf.ln(90)
286
+
287
+ pdf.add_page()
288
+ pdf.set_font('Arial', 'B', 14)
289
+ pdf.cell(0, 10, "3. Physics-Informed Sub-Metrics", ln=True)
290
+ pdf.set_font('Arial', '', 12)
291
+ pdf.cell(0, 10, f"- Compression Variance (ELA): {data['Max_Z']['ELA']:.2f} Z", ln=True)
292
+ pdf.cell(0, 10, f"- CMOS DNA Absence (PRNU): {data['Max_Z']['CMOS_DNA']:.2f} Z", ln=True)
293
+ pdf.cell(0, 10, f"- Color Chroma Anomaly: {data['Max_Z']['Chroma']:.2f} Z", ln=True)
294
+ rgb_status = "VIOLATION" if data['RGB_Violation'] else "Passed (Channels Intact)"
295
+ pdf.cell(0, 10, f"- RGB Cross-Correlation Status: {rgb_status}", ln=True)
296
+
297
+ pdf_bytes = pdf.output(dest='S').encode('latin-1')
298
+ temp_pdf = tempfile.NamedTemporaryFile(delete=False, suffix=".pdf")
299
+ temp_pdf.write(pdf_bytes)
300
+ temp_pdf.close()
301
+ return temp_pdf.name
302
+
303
+ # ==============================================================================
304
+ # 3. HIGH-CONTRAST FUTURISTIC PLOTLY BUILDERS
305
+ # ==============================================================================
306
+ font_config = dict(color="#f8fafc", family="Inter, sans-serif")
307
+ grid_config = dict(gridcolor="rgba(255,255,255,0.08)", zerolinecolor="rgba(255,255,255,0.08)", title_font=font_config, tickfont=font_config)
308
+
309
+ def create_pure_heatmap(z_grid):
310
+ fig = go.Figure(data=go.Heatmap(z=z_grid, colorscale='Magma', zmin=0, zmax=4.5, hovertemplate='Anomaly Z-Score: %{z:.2f}<extra></extra>'))
311
+ fig.update_layout(xaxis_visible=False, yaxis_visible=False, height=350, margin=dict(l=0, r=0, t=0, b=0), paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)')
312
+ return fig
313
+
314
+ def create_spectral_forensics_plot(r_vals, p_vals, alpha, intercept, is_fake):
315
+ limit = min(200, len(r_vals))
316
+ x_freq = r_vals[1:limit]
317
+ y_actual_log = np.log10(p_vals[1:limit] + 1e-10)
318
+ log_x = np.log10(x_freq)
319
+
320
+ raw_alpha = alpha / 0.70
321
+ y_calibrated_log = y_actual_log + (raw_alpha - alpha) * log_x
322
+
323
+ y_upper_threat = -2.0 * log_x + intercept
324
+ y_lower_threat = -3.5 * log_x + intercept
325
+ y_max = intercept + 1.0
326
+ y_min = np.min(y_calibrated_log) - 1.5
327
+
328
+ fig = go.Figure()
329
+ fig.add_trace(go.Scatter(x=x_freq, y=y_upper_threat, mode='lines', line=dict(width=0), showlegend=False, hoverinfo='skip'))
330
+
331
+ fig.add_trace(go.Scatter(x=x_freq, y=y_lower_threat, mode='lines', fill='tonexty', fillcolor='rgba(255, 0, 127, 0.15)', line=dict(color='rgba(255, 0, 127, 0.7)', width=2, dash='dash'), name='Generative Threat Zone'))
332
+ fig.add_trace(go.Scatter(x=x_freq, y=y_upper_threat, mode='lines', line=dict(color='rgba(255, 0, 127, 0.7)', width=2, dash='dash'), showlegend=False, hoverinfo='skip'))
333
+
334
+ line_color = '#ff007f' if is_fake else '#00f2fe'
335
+ fig.add_trace(go.Scatter(x=x_freq, y=y_calibrated_log, mode='lines', name=f'Decay Signal (α = {alpha:.2f})', line=dict(color=line_color, width=3.5)))
336
+
337
+ fig.add_annotation(x=np.log10(15), y=-2.75 * np.log10(15) + intercept, text="GENERATIVE THREAT<br>(2.0 ≤ α ≤ 3.5)", showarrow=False, font=dict(color="#ff007f", size=11, family="Inter", weight="bold"))
338
+ fig.add_annotation(x=np.log10(15), y=-1.0 * np.log10(15) + intercept, text="PHYSICAL OPTICS<br>(α < 2.0)", showarrow=False, font=dict(color="#00f2fe", size=11, family="Inter", weight="bold"))
339
+
340
+ fig.update_layout(xaxis_type="log", height=380, margin=dict(l=30, r=20, t=30, b=30),
341
+ legend=dict(yanchor="top", y=0.99, xanchor="right", x=0.99, bgcolor='rgba(15, 23, 42, 0.8)', font=font_config),
342
+ paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)',
343
+ xaxis_title="Log10 Spatial Frequency", yaxis_title="Log10 Signal Energy",
344
+ xaxis=grid_config, yaxis={**grid_config, 'range': [y_min, y_max]})
345
+ return fig
346
+
347
+ def create_speedometer(value, title, max_val=100, is_prob=True):
348
+ color = "#ff007f" if (value > 50 and is_prob) or (value > 3.5 and not is_prob) else "#00e676"
349
+ fig = go.Figure(go.Indicator(
350
+ mode="gauge+number", value=value,
351
+ title={'text': title, 'font': {'size': 14, 'color': '#94a3b8'}},
352
+ number={'suffix': "%" if is_prob else " Z", 'font': {'size': 32, 'color': '#f8fafc', 'family': 'Inter', 'weight': 'bold'}},
353
+ gauge={
354
+ 'axis': {'range': [None, max_val], 'tickwidth': 1, 'tickcolor': "#334155", 'tickfont': font_config},
355
+ 'bar': {'color': color, 'thickness': 0.8},
356
+ 'bgcolor': "rgba(255,255,255,0.05)",
357
+ 'steps': [{'range': [0, max_val/2], 'color': "rgba(255,255,255,0.01)"}, {'range': [max_val/2, max_val], 'color': "rgba(255,255,255,0.03)"}],
358
+ 'threshold': {'line': {'color': "#ff007f", 'width': 3}, 'thickness': 0.75, 'value': value}
359
+ }
360
+ ))
361
+ fig.update_layout(height=240, margin=dict(l=20, r=20, t=40, b=20), paper_bgcolor='rgba(0,0,0,0)')
362
+ return fig
363
+
364
+ def create_z_distribution_plot(z_array, color):
365
+ fig = go.Figure()
366
+ fig.add_trace(go.Histogram(x=z_array, marker_color=color, nbinsx=60, name="Patch Z-Scores", opacity=0.85))
367
+ fig.add_vline(x=3.5, line_dash="dash", line_color="#ff007f", line_width=2, annotation_text="3.5 Z (Threat)", annotation_font_color="#ff007f")
368
+ fig.update_layout(height=220, margin=dict(l=10, r=10, t=20, b=10), showlegend=False, paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)',
369
+ xaxis=grid_config, yaxis=grid_config)
370
+ return fig
371
+
372
+
373
+ # ==============================================================================
374
+ # 4. GRADIO EVENT LOGIC (ZeroGPU Ready)
375
+ # ==============================================================================
376
+ @gpu_decorator
377
+ def execute_scan(file_paths, mode, progress=gr.Progress()):
378
+ if not file_paths:
379
+ return [], gr.update(choices=[], value=None), "<div class='glass-card' style='border-color: #ff007f; background: rgba(255,0,127,0.1);'><h3 style='color:#ff007f; margin:0;'>⚠️ No assets uploaded.</h3></div>"
380
+
381
+ if isinstance(file_paths, str): file_paths = [file_paths]
382
+ results = []
383
+
384
+ for fpath in progress.tqdm(file_paths, desc="Extracting CMOS DNA & Spectral Signals"):
385
+ engine = UnbiasedPhysicsForensics(fpath)
386
+ if engine.valid: results.append(engine.analyze())
387
+
388
+ fakes = sum(1 for r in results if r['Fake_Prob'] >= 50)
389
+ total = len(results)
390
+ safe = total - fakes
391
+
392
+ audit_html = f"""
393
+ <div style="display: flex; gap: 15px; margin-top: 15px;">
394
+ <div class="glass-metric" style="border-top: 4px solid #00f2fe;">
395
+ <div class="metric-title">Tensors Analyzed</div>
396
+ <div class="metric-value" style="color: #f8fafc;">{total}</div>
397
+ </div>
398
+ <div class="glass-metric" style="border-top: 4px solid #00e676;">
399
+ <div class="metric-title">Physically Verified</div>
400
+ <div class="metric-value" style="color: #00e676;">{safe}</div>
401
+ </div>
402
+ <div class="glass-metric" style="border-top: 4px solid #ff007f;">
403
+ <div class="metric-title">Anomalies Detected</div>
404
+ <div class="metric-value" style="color: #ff007f;">{fakes}</div>
405
+ </div>
406
+ </div>
407
+ """
408
+ choices = [r['Filename'] for r in results]
409
+ return results, gr.update(choices=choices, value=choices[0] if choices else None), audit_html
410
+
411
+ def update_dashboard(selected_file, results):
412
+ if not selected_file or not results: return [gr.update(visible=False)] + [gr.update()] * 17
413
+
414
+ data = next((r for r in results if r['Filename'] == selected_file), None)
415
+ if not data: return [gr.update(visible=False)] + [gr.update()] * 17
416
+
417
+ is_fake = data['Fake_Prob'] >= 50
418
+ if is_fake:
419
+ alert = f"<div class='glass-alert alert-threat'><h2 style='color: #ff007f; text-shadow: 0 0 10px rgba(255,0,127,0.5);'>🚨 SYNTHETIC ORIGIN DETECTED ({data['Fake_Prob']:.1f}% Match)</h2><p style='color: #cbd5e1; font-size: 1.1rem; margin-top: 5px;'>Physical structural limits breached. Generative AI or localized spatial manipulation confirmed via CMOS DNA and Spectral deviation.</p></div>"
420
+ else:
421
+ alert = f"<div class='glass-alert alert-secure'><h2 style='color: #00e676; text-shadow: 0 0 10px rgba(0,230,118,0.5);'>✅ NATURAL PROVENANCE VERIFIED ({data['Fake_Prob']:.1f}% Match)</h2><p style='color: #cbd5e1; font-size: 1.1rem; margin-top: 5px;'>Asset fully conforms to natural physical hardware constraints. CMOS DNA intact.</p></div>"
422
+
423
+ pdf_path = generate_pdf_report_gradio(data)
424
+
425
+ spatial_diag = f"<div class='insight-pill {'pill-red' if data['Threat_Flags'] >= 3 else 'pill-green'}'>{'Structural Matrix Compromised.' if data['Threat_Flags'] >= 3 else 'Optical Variance within Natural Bounds.'}</div>"
426
+ fft_diag = f"<div class='insight-pill {'pill-red' if data['Global_Prob'] > 50 else 'pill-green'}'>{'Generative Threat Zone Trapped.' if data['Global_Prob'] > 50 else 'Natural Optical Decay Confirmed.'}</div>"
427
+ ela_diag = f"<div class='insight-pill {'pill-red' if data['Max_Z']['ELA'] > 3.5 else 'pill-green'}'>Max Variance: {data['Max_Z']['ELA']:.2f} Z</div>"
428
+ noise_diag = f"<div class='insight-pill {'pill-red' if data['Max_Z']['CMOS_DNA'] > 3.5 else 'pill-green'}'>Max Variance: {data['Max_Z']['CMOS_DNA']:.2f} Z</div>"
429
+ chroma_diag = f"<div class='insight-pill {'pill-red' if data['RGB_Violation'] else 'pill-green'}'>{'RGB Channels Mathematically Detached.' if data['RGB_Violation'] else 'Color Correlation Intact.'}</div>"
430
+
431
+ return (
432
+ gr.update(visible=True), alert, pdf_path, cv2.cvtColor(data['Image'], cv2.COLOR_RGB2BGR),
433
+ create_pure_heatmap(data['Z_Grid']), spatial_diag,
434
+ create_spectral_forensics_plot(data['R_Vals'], data['P_Vals'], data['Alpha_Val'], data['Intercept'], is_fake=(data['Global_Prob'] > 50)),
435
+ create_speedometer(data['Global_Prob'], "Spectral Decay Probability", 100, True), fft_diag,
436
+ create_speedometer(data['Max_Z']['ELA'], "Compression Anomaly", 10, False), create_z_distribution_plot(data['Z_Arrays']['ELA'], "#00f2fe"), ela_diag,
437
+ create_speedometer(data['Max_Z']['CMOS_DNA'], "CMOS DNA Absence", 10, False), create_z_distribution_plot(data['Z_Arrays']['CMOS_DNA'], "#8b5cf6"), noise_diag,
438
+ create_speedometer(data['Max_Z']['Chroma'], "Chroma Overlap Failure", 10, False), create_z_distribution_plot(data['Z_Arrays']['Chroma'], "#10b981"), chroma_diag
439
+ )
440
+
441
+ # ==============================================================================
442
+ # 5. GRADIO UI LAYOUT (Deep Obsidian & Bioluminescent Theme)
443
+ # ==============================================================================
444
+ custom_theme = gr.themes.Default(
445
+ primary_hue="cyan", secondary_hue="fuchsia", neutral_hue="slate",
446
+ font=[gr.themes.GoogleFont("Inter"), "sans-serif"],
447
+ ).set(
448
+ body_background_fill="#070c14",
449
+ block_background_fill="rgba(15, 23, 42, 0.6)",
450
+ block_border_width="1px", block_border_color="rgba(0, 242, 254, 0.2)",
451
+ button_primary_background_fill="linear-gradient(135deg, #00f2fe 0%, #4facfe 100%)",
452
+ button_primary_background_fill_hover="linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)",
453
+ button_primary_text_color="#070c14"
454
+ )
455
+
456
+ custom_css = """
457
+ body, .prose, .markdown-text, label, .gr-text-input { color: #f8fafc !important; }
458
+
459
+ body::before {
460
+ content: ""; position: fixed; top: 0; left: 0; width: 100%; height: 100%;
461
+ background-image: radial-gradient(rgba(0, 242, 254, 0.15) 1px, transparent 1px);
462
+ background-size: 40px 40px;
463
+ z-index: -1; pointer-events: none; opacity: 0.5;
464
+ }
465
+
466
+ .glass-card {
467
+ background: rgba(15, 23, 42, 0.7); backdrop-filter: blur(20px); -webkit-backdrop-filter: blur(20px);
468
+ border-radius: 16px; border: 1px solid rgba(0, 242, 254, 0.15);
469
+ box-shadow: 0 4px 30px rgba(0, 0, 0, 0.5), inset 0 0 20px rgba(0, 242, 254, 0.05);
470
+ padding: 25px; transition: transform 0.2s ease, border-color 0.3s;
471
+ }
472
+ .glass-card:hover { border-color: rgba(0, 242, 254, 0.4); }
473
+
474
+ .glass-metric {
475
+ background: rgba(7, 12, 20, 0.8);
476
+ border-radius: 12px; padding: 20px 10px; flex: 1; text-align: center;
477
+ box-shadow: inset 0 0 15px rgba(0,0,0,0.8); border: 1px solid rgba(255,255,255,0.05);
478
+ }
479
+ .metric-title { font-size: 0.85rem; color: #94a3b8; font-weight: 700; letter-spacing: 1px; text-transform: uppercase;}
480
+ .metric-value { font-size: 2.8rem; font-weight: 800; margin-top: 5px; font-family: 'Inter', sans-serif;}
481
+
482
+ .hero-box {
483
+ background: linear-gradient(135deg, rgba(15,23,42,0.9) 0%, rgba(7,12,20,0.9) 100%);
484
+ color: #f8fafc; padding: 50px 40px; border-radius: 20px; margin-bottom: 30px;
485
+ box-shadow: 0 0 40px rgba(0, 242, 254, 0.1); text-align: center;
486
+ border: 1px solid rgba(0, 242, 254, 0.3);
487
+ position: relative; overflow: hidden;
488
+ }
489
+ .hero-box::after {
490
+ content: ''; position: absolute; top: -50%; left: -50%; width: 200%; height: 200%;
491
+ background: radial-gradient(circle, rgba(0,242,254,0.1) 0%, transparent 60%);
492
+ animation: rotateGlow 15s linear infinite; pointer-events: none;
493
+ }
494
+ @keyframes rotateGlow { 100% { transform: rotate(360deg); } }
495
+
496
+ .hero-box h1 { margin: 0; font-size: 3rem; font-weight: 900; letter-spacing: -1px; color: #f8fafc !important; text-shadow: 0 0 20px rgba(0,242,254,0.5);}
497
+ .hero-box p { margin-top: 10px; font-size: 1.2rem; font-weight: 300; color: #cbd5e1; opacity: 0.9;}
498
+
499
+ .glass-alert { padding: 25px; border-radius: 16px; text-align: center; margin-bottom: 30px; background: rgba(7,12,20,0.8); box-shadow: 0 10px 30px rgba(0,0,0,0.5);}
500
+ .alert-secure { border: 1px solid #00e676; box-shadow: inset 0 0 20px rgba(0,230,118,0.1); }
501
+ .alert-threat { border: 1px solid #ff007f; box-shadow: inset 0 0 20px rgba(255,0,127,0.1); }
502
+ .glass-alert h2 { margin-top: 0; font-weight: 800; font-size: 1.6rem;}
503
+
504
+ .insight-pill { display: inline-block; padding: 6px 18px; border-radius: 20px; font-size: 0.9rem; font-weight: 600; text-align: center; margin-top: 15px;}
505
+ .pill-green { background: rgba(0,230,118,0.1); color: #00e676; border: 1px solid #00e676;}
506
+ .pill-red { background: rgba(255,0,127,0.1); color: #ff007f; border: 1px solid #ff007f;}
507
+ .section-desc { font-size: 1.05rem; color: #94a3b8; padding-bottom: 15px; border-bottom: 1px solid rgba(255,255,255,0.1); margin-bottom: 25px; font-weight: 300;}
508
+
509
+ h1, h2, h3, h4 { color: #f8fafc !important; font-weight: 700 !important; }
510
+ """
511
+
512
+ with gr.Blocks(theme=custom_theme, css=custom_css) as demo:
513
+ gr.HTML("""
514
+ <div class="hero-box">
515
+ <h1>DeepScan OS</h1>
516
+ <p>Advanced Computational Physics & Spectral Frequency Media Forensics</p>
517
+ </div>
518
+ """)
519
+
520
+ results_state = gr.State([])
521
+
522
+ with gr.Row():
523
+ with gr.Column(scale=1):
524
+ gr.Markdown("### 🧬 Architecture Overview")
525
+ gr.HTML("""
526
+ <div class='glass-card' style='padding: 20px; margin-bottom: 20px;'>
527
+ <h4 style='color: #ff007f !important; margin-top:0; font-size: 1.1rem; text-shadow: 0 0 10px rgba(255,0,127,0.5);'>CMOS DNA Extraction</h4>
528
+ <p style='font-size: 0.95rem; color: #cbd5e1; line-height: 1.5; font-weight:300;'>
529
+ Silicon manufacturing constraints leave microscopic 'dust' anomalies on physical sensors. DeepScan extracts this PRNU signature via kernel convolutions to prove hardware origin. Generative tensors lack this physical fingerprint.
530
+ </p>
531
+ <hr style='border-top: 1px solid rgba(255,255,255,0.1); margin: 15px 0;'>
532
+ <h4 style='color: #00f2fe !important; margin-top:0; font-size: 1.1rem; text-shadow: 0 0 10px rgba(0,242,254,0.5);'>Spectral Frequency Domain</h4>
533
+ <p style='font-size: 0.95rem; color: #cbd5e1; line-height: 1.5; font-weight:300;'>
534
+ Natural optical light follows strict mathematical power laws. By utilizing Fast Fourier Transforms (FFT), the engine visualizes high-frequency structural decay, trapping Generative AI diffusions inside the threat matrix.
535
+ </p>
536
+ </div>
537
+ """)
538
+
539
+ with gr.Column(scale=3):
540
+ with gr.Tabs():
541
+
542
+ with gr.Tab("🚀 1. Scan Hub"):
543
+ with gr.Group(elem_classes=["glass-card"]):
544
+ gr.Markdown("### ⚙️ Pipeline Configuration")
545
+ mode_radio = gr.Radio(["Single Image Pipeline", "Batch/Folder Distributed (PySpark)"], label="Execution Architecture", value="Single Image Pipeline")
546
+ file_input = gr.File(label="Upload Media Tensor(s)", file_count="multiple", type="filepath", file_types=["image"])
547
+ scan_btn = gr.Button("⚡ INITIATE SPECTRAL SCAN", variant="primary", size="lg")
548
+
549
+ gr.HTML("<br>")
550
+ gr.Markdown("### 📊 Batch Telemetry")
551
+ global_audit = gr.HTML("<div style='color: #64748b; font-size: 1rem; font-weight: 500; text-align: center; padding: 20px;'>Awaiting tensor ingestion...</div>")
552
+ file_dropdown = gr.Dropdown(label="Select Processed Tensor to view in Dashboard", choices=[], interactive=True)
553
+
554
+ with gr.Tab("🔭 2. Telemetry Dashboard"):
555
+ report_container = gr.Group(visible=False, elem_classes=["glass-card"])
556
+ with report_container:
557
+ main_alert = gr.HTML("")
558
+ pdf_btn = gr.File(label="📄 Export Certified Security Report (PDF)")
559
+ gr.HTML("<br>")
560
+
561
+ gr.Markdown("### 🌟 I. Spectral Frequency-Domain Analysis")
562
+ gr.HTML("<div class='section-desc'>Evaluating the power spectrum decay against theoretical natural light physics. AI fundamentally fails to replicate complex high-frequency optical decay.</div>")
563
+ with gr.Row():
564
+ fft_plot = gr.Plot(scale=2)
565
+ fft_speed = gr.Plot(scale=1)
566
+ fft_text = gr.HTML("")
567
+
568
+ gr.HTML("<br><br>")
569
+
570
+ gr.Markdown("### 🔍 II. Spatial Fabric & Sub-Metric Anomalies")
571
+ gr.HTML("<div class='section-desc'>A 98th-percentile robust Z-score pipeline isolating localized structural manipulation via hardware fingerprint absence.</div>")
572
+ with gr.Row():
573
+ with gr.Column():
574
+ img_display = gr.Image(label="Source Media", interactive=False)
575
+ with gr.Column():
576
+ hm_plot = gr.Plot(label="Anomaly Spatial Heatmap")
577
+ spatial_text = gr.HTML("")
578
+
579
+ gr.HTML("<br><br>")
580
+
581
+ with gr.Row():
582
+ with gr.Column(variant="panel", elem_classes=["glass-card"]):
583
+ gr.Markdown("**Compression Variation (ELA)**")
584
+ ela_speed = gr.Plot()
585
+ ela_hist = gr.Plot()
586
+ ela_text = gr.HTML("")
587
+ with gr.Column(variant="panel", elem_classes=["glass-card"]):
588
+ gr.Markdown("**CMOS DNA Absence (PRNU)**")
589
+ noise_speed = gr.Plot()
590
+ noise_hist = gr.Plot()
591
+ noise_text = gr.HTML("")
592
+ with gr.Column(variant="panel", elem_classes=["glass-card"]):
593
+ gr.Markdown("**Color Chroma Variance**")
594
+ chroma_speed = gr.Plot()
595
+ chroma_hist = gr.Plot()
596
+ chroma_text = gr.HTML("")
597
+
598
+ with gr.Tab("📚 3. Core Engine Architecture"):
599
+ gr.HTML("""
600
+ <div class="glass-card" style="margin-top: 10px;">
601
+ <h2 style="color: #f8fafc; font-size: 2rem; font-weight: 800; margin-top: 0;">Physics-Informed Media Provenance</h2>
602
+ <p style="font-size: 1.15rem; color: #cbd5e1; line-height: 1.6; font-weight: 300;">
603
+ DeepScan OS bypasses standard deep learning classifiers—which are easily fooled by adversarial noise—in favor of <b>physics-informed forensic integrity</b>.
604
+ By evaluating the inherent mathematical constraints of optical light and silicon camera hardware, the system flags generative manipulations purely based on physical impossibilities.
605
+ </p>
606
+ <br>
607
+ <div style="display: flex; gap: 25px; flex-wrap: wrap;">
608
+ <div class="glass-card" style="flex: 1; min-width: 250px; background: rgba(15,23,42,0.8); border: 1px solid rgba(0,242,254,0.3);">
609
+ <h3 style="color: #00f2fe !important; font-size: 1.3rem; margin-top:0; text-shadow: 0 0 10px rgba(0,242,254,0.5);">📡 Spectral Analysis</h3>
610
+ <p style="color: #cbd5e1; font-size: 1rem; line-height: 1.5; font-weight: 300;">
611
+ Natural photographs exhibit a specific mathematical decay in signal energy as spatial frequency increases. Generative models fail to reconstruct this high-frequency data, trapping their signal inside a quantifiable "Threat Zone" (2.0 ≤ α ≤ 3.5).
612
+ </p>
613
+ </div>
614
+ <div class="glass-card" style="flex: 1; min-width: 250px; background: rgba(15,23,42,0.8); border: 1px solid rgba(255,0,127,0.3);">
615
+ <h3 style="color: #ff007f !important; font-size: 1.3rem; margin-top:0; text-shadow: 0 0 10px rgba(255,0,127,0.5);">🧬 CMOS DNA</h3>
616
+ <p style="color: #cbd5e1; font-size: 1rem; line-height: 1.5; font-weight: 300;">
617
+ Every physical camera sensor (CMOS) leaves a unique, microscopic "dust" pattern on its outputs due to silicon manufacturing imperfections. When objects are generated by AI, they inherently lack this hardware DNA, creating massive variance spikes.
618
+ </p>
619
+ </div>
620
+ </div>
621
+ </div>
622
+ """)
623
+
624
+ scan_btn.click(
625
+ fn=execute_scan, inputs=[file_input, mode_radio], outputs=[results_state, file_dropdown, global_audit]
626
+ )
627
+
628
+ file_dropdown.change(
629
+ fn=update_dashboard, inputs=[file_dropdown, results_state],
630
+ outputs=[
631
+ report_container, main_alert, pdf_btn, img_display, hm_plot, spatial_text,
632
+ fft_plot, fft_speed, fft_text,
633
+ ela_speed, ela_hist, ela_text,
634
+ noise_speed, noise_hist, noise_text,
635
+ chroma_speed, chroma_hist, chroma_text
636
+ ]
637
+ )
638
+
639
+ if __name__ == "__main__":
640
+ demo.launch()