Spaces:
Sleeping
Sleeping
Download app.py from Anuran66/PHORENSICS: direct link, hf CLI and curl.
- Browser
- Download file 35.7 kB
-
https://huggingface.co/spaces/Anuran66/PHORENSICS/resolve/main/app.py
- Command line
-
hf download hf://spaces/Anuran66/PHORENSICS/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Anuran66/PHORENSICS/resolve/main/app.py
35.7 kB
| import os | |
| import cv2 | |
| import time | |
| import datetime | |
| import tempfile | |
| import numpy as np | |
| import warnings | |
| import psutil | |
| import gradio as gr | |
| import plotly.graph_objects as go | |
| import matplotlib.pyplot as plt | |
| # ============================================================================== | |
| # 0. HARDWARE & ZERO-GPU INTEGRATION | |
| # ============================================================================== | |
| java8_opts = ( | |
| "-XX:+IgnoreUnrecognizedVMOptions --add-opens=java.base/java.lang=ALL-UNNAMED " | |
| "--add-opens=java.base/java.lang.invoke=ALL-UNNAMED --add-opens=java.base/java.lang.reflect=ALL-UNNAMED " | |
| "--add-opens=java.base/java.io=ALL-UNNAMED --add-opens=java.base/java.net=ALL-UNNAMED " | |
| "--add-opens=java.base/java.nio=ALL-UNNAMED --add-opens=java.base/java.util=ALL-UNNAMED " | |
| "--add-opens=java.base/java.util.concurrent=ALL-UNNAMED --add-opens=java.base/java.util.concurrent.atomic=ALL-UNNAMED " | |
| "--add-opens=java.base/jdk.internal.ref=ALL-UNNAMED --add-opens=java.base/sun.nio.ch=ALL-UNNAMED " | |
| "--add-opens=java.base/sun.nio.cs=ALL-UNNAMED --add-opens=java.base/sun.security.action=ALL-UNNAMED " | |
| "--add-opens=java.base/sun.util.calendar=ALL-UNNAMED --add-opens=java.security.jgss/sun.security.krb5=ALL-UNNAMED" | |
| ) | |
| os.environ["PYSPARK_SUBMIT_ARGS"] = f'--driver-java-options "{java8_opts}" pyspark-shell' | |
| os.environ["SPARK_LOCAL_IP"] = "127.0.0.1" | |
| # Hugging Face ZeroGPU Allocation logic | |
| try: | |
| import spaces | |
| gpu_decorator = spaces.GPU | |
| except ImportError: | |
| def gpu_decorator(fn): return fn # Fallback if running locally without the spaces library | |
| try: | |
| import torch | |
| import torch.nn.functional as F | |
| HAS_TORCH = True | |
| except ImportError: | |
| HAS_TORCH = False | |
| try: | |
| from pyspark.sql import SparkSession | |
| HAS_SPARK = True | |
| except ImportError: | |
| HAS_SPARK = False | |
| try: | |
| from fpdf import FPDF | |
| HAS_FPDF = True | |
| except ImportError: | |
| HAS_FPDF = False | |
| warnings.filterwarnings('ignore') | |
| # ============================================================================== | |
| # 1. CORE PHYSICS ENGINE (CMOS DNA & Spectral Analysis) | |
| # ============================================================================== | |
| class UnbiasedPhysicsForensics: | |
| def __init__(self, image_path, max_dim=600, patch_size=128, stride=64): | |
| self.image_path = image_path | |
| self.filename = os.path.basename(image_path) | |
| self.patch_size = patch_size | |
| self.stride = stride | |
| self.device = 'cuda' if torch.cuda.is_available() else 'cpu' | |
| img = cv2.imread(image_path, cv2.IMREAD_UNCHANGED) | |
| self.valid = False | |
| if img is not None: | |
| if len(img.shape) == 2: img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) | |
| elif len(img.shape) == 3 and img.shape[2] == 4: img = img[:, :, :3] | |
| if img.dtype == np.uint16: img = (img / 256).astype(np.uint8) | |
| h, w = img.shape[:2] | |
| if max(h, w) > max_dim: | |
| scale = max_dim / max(h, w) | |
| img = cv2.resize(img, (int(w * scale), int(h * scale)), interpolation=cv2.INTER_AREA) | |
| self.img_bgr = img | |
| self.img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) | |
| self.h, self.w = self.img_bgr.shape[:2] | |
| self.valid = True | |
| def _extract_patches(self, tensor): | |
| tensor = tensor.to(self.device) | |
| c, h, w = tensor.shape | |
| pad_h = max(0, self.patch_size - h) if h < self.patch_size else 0 | |
| pad_w = max(0, self.patch_size - w) if w < self.patch_size else 0 | |
| if pad_h > 0 or pad_w > 0: | |
| tensor = F.pad(tensor, (0, pad_w, 0, pad_h), mode='reflect') | |
| _, h, w = tensor.shape | |
| n_h = (h - self.patch_size) // self.stride + 1 | |
| n_w = (w - self.patch_size) // self.stride + 1 | |
| patches = tensor.unfold(1, self.patch_size, self.stride).unfold(2, self.patch_size, self.stride) | |
| patches = patches.contiguous().view(c, -1, self.patch_size, self.patch_size).permute(1, 0, 2, 3) | |
| return patches, n_h, n_w | |
| def analyze_global_spectrum(self): | |
| gray = cv2.cvtColor(self.img_bgr, cv2.COLOR_BGR2GRAY) | |
| f = np.fft.fft2(gray) | |
| power = np.abs(np.fft.fftshift(f))**2 | |
| h, w = power.shape | |
| cy, cx = h // 2, w // 2 | |
| y, x = np.indices((h, w)) | |
| r = np.sqrt((x - cx)**2 + (y - cy)**2).astype(int) | |
| tbin = np.bincount(r.ravel(), power.ravel()) | |
| nr = np.bincount(r.ravel()) | |
| radial_profile = tbin / np.maximum(nr, 1) | |
| r_vals = np.arange(1, len(radial_profile)) | |
| p_vals = radial_profile[1:] | |
| log_r = np.log10(r_vals) | |
| log_p = np.log10(p_vals + 1e-10) | |
| slope, intercept = np.polyfit(log_r, log_p, 1) | |
| alpha = -slope * 0.70 | |
| ai_score = 0.0 | |
| if 2.0 <= alpha <= 3.5: ai_score = 99.9 | |
| elif alpha < 2.0: ai_score = max(((alpha - 1.0) / 1.0) * 49.9, 0.0) | |
| else: ai_score = max(((4.5 - alpha) / 1.0) * 49.9, 0.0) | |
| return min(max(ai_score, 0), 99.9), alpha, r_vals, p_vals, intercept | |
| def compute_rgb_matrix(self, max_chroma_z): | |
| pixels = self.img_rgb.reshape(-1, 3).astype(np.float32) / 255.0 | |
| rgb_corr = np.corrcoef(pixels.T) | |
| violation = False | |
| reason = "Channels Intact (Normal Physical Overlap)" | |
| if np.isnan(rgb_corr).any(): | |
| rgb_corr = np.nan_to_num(rgb_corr, nan=0.1) | |
| violation = True | |
| if max_chroma_z > 3.5: | |
| violation = True | |
| reason = f"Color Chroma Anomaly ({max_chroma_z:.2f} Z) forced channel detachment." | |
| for i in range(3): | |
| for j in range(3): | |
| if i != j: rgb_corr[i, j] *= (1.5 / max_chroma_z) | |
| elif np.min(rgb_corr) < 0.25: | |
| violation = True | |
| reason = "Natural physical channel correlation broken (<0.25)." | |
| return rgb_corr, violation, reason | |
| def analyze(self): | |
| def robust_z(pts): | |
| m = torch.median(pts) | |
| return 0.6745 * torch.abs(pts - m) / (torch.median(torch.abs(pts - m)) + 1e-3) | |
| _, enc = cv2.imencode('.jpg', self.img_bgr, [int(cv2.IMWRITE_JPEG_QUALITY), 90]) | |
| 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) | |
| p_ela, n_h, n_w = self._extract_patches(diff.unsqueeze(0)) | |
| z_ela = robust_z(torch.var(p_ela.view(p_ela.shape[0], -1), dim=1)).to('cpu') | |
| gray = cv2.cvtColor(self.img_bgr, cv2.COLOR_BGR2GRAY) | |
| t_gray = torch.from_numpy(gray).float().unsqueeze(0).unsqueeze(0).to(self.device) | |
| kernel = torch.tensor([[[[0., 1., 0.], [1., -4., 1.], [0., 1., 0.]]]]).to(self.device) | |
| noise_map = F.conv2d(t_gray, kernel, padding=1).squeeze(0) | |
| p_noise, _, _ = self._extract_patches(noise_map) | |
| z_noise = robust_z(torch.var(p_noise.view(p_noise.shape[0], -1), dim=1)).to('cpu') | |
| ycc = cv2.cvtColor(self.img_bgr, cv2.COLOR_BGR2YCrCb) | |
| t_ycc = torch.from_numpy(ycc).float().permute(2, 0, 1).to(self.device) | |
| p_chroma, _, _ = self._extract_patches(t_ycc) | |
| y_var = torch.var(p_chroma[:, 0, :, :].reshape(p_chroma.shape[0], -1), dim=1) + 1e-5 | |
| z_chroma = robust_z((torch.var(p_chroma[:, 1, :, :].reshape(p_chroma.shape[0], -1), dim=1) + | |
| torch.var(p_chroma[:, 2, :, :].reshape(p_chroma.shape[0], -1), dim=1)) / y_var).to('cpu') | |
| max_ela = torch.quantile(z_ela.float(), 0.98).item() | |
| max_noise = torch.quantile(z_noise.float(), 0.98).item() | |
| max_chroma_val = torch.quantile(z_chroma.float(), 0.98).item() | |
| rgb_corr, rgb_violation, rgb_reason = self.compute_rgb_matrix(max_chroma_val) | |
| combined_z = (z_ela + z_noise + z_chroma) / 3.0 | |
| z_grid = combined_z.view(n_h, n_w).numpy() | |
| ela_norm = max(0.0, min(((max_ela - 2.5) / 1.5) * 100.0, 100.0)) | |
| noise_norm = max(0.0, min(((max_noise - 2.5) / 1.5) * 100.0, 100.0)) | |
| chroma_norm = max(0.0, min(((max_chroma_val - 2.5) / 1.5) * 100.0, 100.0)) | |
| rgb_norm = 100.0 if rgb_violation else 0.0 | |
| sub_metric_composite = (ela_norm * 0.25) + (noise_norm * 0.35) + (chroma_norm * 0.20) + (rgb_norm * 0.20) | |
| global_fake_prob, alpha_val, r_vals, p_vals, intercept = self.analyze_global_spectrum() | |
| weight_sub_metrics = 0.60 if global_fake_prob > 80.0 else 0.70 | |
| weight_fft = 0.40 if global_fake_prob > 80.0 else 0.30 | |
| final_fake_prob = (sub_metric_composite * weight_sub_metrics) + (global_fake_prob * weight_fft) | |
| cluster_ratio = torch.sum(combined_z > 3.5).item() / combined_z.shape[0] | |
| 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]) | |
| return { | |
| "Filename": self.filename, | |
| "Fake_Prob": min(final_fake_prob, 99.9), | |
| "Sub_Metric_Score": sub_metric_composite, | |
| "Global_Prob": global_fake_prob, | |
| "Threat_Flags": internal_threat_flags, | |
| "Max_Z": {"ELA": max_ela, "CMOS_DNA": max_noise, "Chroma": max_chroma_val}, | |
| "Z_Arrays": {"ELA": z_ela.numpy().flatten(), "CMOS_DNA": z_noise.numpy().flatten(), "Chroma": z_chroma.numpy().flatten()}, | |
| "RGB_Matrix": rgb_corr, | |
| "RGB_Violation": rgb_violation, | |
| "RGB_Reason": rgb_reason, | |
| "Alpha_Val": alpha_val, | |
| "R_Vals": r_vals, "P_Vals": p_vals, "Intercept": intercept, | |
| "Z_Grid": z_grid, | |
| "Image": self.img_rgb | |
| } | |
| def process_file_wrapper(fpath): | |
| engine = UnbiasedPhysicsForensics(fpath) | |
| if engine.valid: return engine.analyze() | |
| return None | |
| # ============================================================================== | |
| # 2. PDF REPORT GENERATOR | |
| # ============================================================================== | |
| def generate_pdf_report_gradio(data): | |
| if not HAS_FPDF: return None | |
| pdf = FPDF() | |
| pdf.set_auto_page_break(auto=True, margin=15) | |
| pdf.add_page() | |
| pdf.set_font('Arial', 'B', 18) | |
| pdf.cell(0, 10, f"DeepScan OS Telemetry: {data['Filename']}", ln=True, align='C') | |
| pdf.set_font('Arial', '', 12) | |
| pdf.cell(0, 10, f"Generated on: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}", ln=True, align='C') | |
| pdf.ln(5) | |
| pdf.set_font('Arial', 'B', 14) | |
| pdf.cell(0, 10, "1. System Clearance Status", ln=True) | |
| pdf.set_font('Arial', '', 12) | |
| status = "SYNTHETIC ANOMALY DETECTED" if data['Fake_Prob'] >= 50 else "PHYSICAL PROVENANCE VERIFIED" | |
| pdf.cell(0, 10, f"System Status: {status}", ln=True) | |
| pdf.cell(0, 10, f"Aggregated Generative Probability: {data['Fake_Prob']:.1f}%", ln=True) | |
| pdf.ln(5) | |
| with tempfile.TemporaryDirectory() as tmpdir: | |
| img_path = os.path.join(tmpdir, "base.jpg") | |
| cv2.imwrite(img_path, cv2.cvtColor(data['Image'], cv2.COLOR_RGB2BGR)) | |
| pdf.image(img_path, x=10, w=90) | |
| hm_path = os.path.join(tmpdir, "heatmap.jpg") | |
| plt.figure(figsize=(4,3)) | |
| plt.imshow(data['Z_Grid'], cmap='magma', vmin=0, vmax=4.5) | |
| plt.axis('off') | |
| plt.tight_layout() | |
| plt.savefig(hm_path) | |
| plt.close() | |
| pdf.image(hm_path, x=110, y=pdf.get_y()-65, w=90) | |
| pdf.ln(70) | |
| pdf.set_font('Arial', 'B', 14) | |
| pdf.cell(0, 10, "2. Spectral Frequency-Domain Analysis", ln=True) | |
| pdf.set_font('Arial', '', 12) | |
| fft_path = os.path.join(tmpdir, "fft.png") | |
| plt.figure(figsize=(8,4)) | |
| limit = min(200, len(data['R_Vals'])) | |
| x_freq = data['R_Vals'][1:limit] | |
| y_actual_log = np.log10(data['P_Vals'][1:limit] + 1e-10) | |
| y_upper = -2.0 * np.log10(x_freq) + data['Intercept'] | |
| y_lower = -3.5 * np.log10(x_freq) + data['Intercept'] | |
| plt.fill_between(x_freq, y_lower, y_upper, color='#ff007f', alpha=0.15, label='Threat Zone') | |
| plt.plot(x_freq, y_upper, 'r--', alpha=0.5) | |
| plt.plot(x_freq, y_lower, 'r--', alpha=0.5) | |
| line_color = '#ff007f' if data['Global_Prob'] > 50 else '#00f2fe' | |
| plt.plot(x_freq, y_actual_log, color=line_color, linewidth=2, label=f"Calibrated Signal (α={data['Alpha_Val']:.2f})") | |
| plt.title(f"Power Spectrum Decay Score: {data['Global_Prob']:.1f}%") | |
| plt.xscale('log') | |
| plt.legend() | |
| plt.savefig(fft_path) | |
| plt.close() | |
| pdf.image(fft_path, x=15, w=180) | |
| pdf.ln(90) | |
| pdf.add_page() | |
| pdf.set_font('Arial', 'B', 14) | |
| pdf.cell(0, 10, "3. Physics-Informed Sub-Metrics", ln=True) | |
| pdf.set_font('Arial', '', 12) | |
| pdf.cell(0, 10, f"- Compression Variance (ELA): {data['Max_Z']['ELA']:.2f} Z", ln=True) | |
| pdf.cell(0, 10, f"- CMOS DNA Absence (PRNU): {data['Max_Z']['CMOS_DNA']:.2f} Z", ln=True) | |
| pdf.cell(0, 10, f"- Color Chroma Anomaly: {data['Max_Z']['Chroma']:.2f} Z", ln=True) | |
| rgb_status = "VIOLATION" if data['RGB_Violation'] else "Passed (Channels Intact)" | |
| pdf.cell(0, 10, f"- RGB Cross-Correlation Status: {rgb_status}", ln=True) | |
| pdf_bytes = pdf.output(dest='S').encode('latin-1') | |
| temp_pdf = tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") | |
| temp_pdf.write(pdf_bytes) | |
| temp_pdf.close() | |
| return temp_pdf.name | |
| # ============================================================================== | |
| # 3. HIGH-CONTRAST FUTURISTIC PLOTLY BUILDERS | |
| # ============================================================================== | |
| font_config = dict(color="#f8fafc", family="Inter, sans-serif") | |
| grid_config = dict(gridcolor="rgba(255,255,255,0.08)", zerolinecolor="rgba(255,255,255,0.08)", title_font=font_config, tickfont=font_config) | |
| def create_pure_heatmap(z_grid): | |
| fig = go.Figure(data=go.Heatmap(z=z_grid, colorscale='Magma', zmin=0, zmax=4.5, hovertemplate='Anomaly Z-Score: %{z:.2f}<extra></extra>')) | |
| 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)') | |
| return fig | |
| def create_spectral_forensics_plot(r_vals, p_vals, alpha, intercept, is_fake): | |
| limit = min(200, len(r_vals)) | |
| x_freq = r_vals[1:limit] | |
| y_actual_log = np.log10(p_vals[1:limit] + 1e-10) | |
| log_x = np.log10(x_freq) | |
| raw_alpha = alpha / 0.70 | |
| y_calibrated_log = y_actual_log + (raw_alpha - alpha) * log_x | |
| y_upper_threat = -2.0 * log_x + intercept | |
| y_lower_threat = -3.5 * log_x + intercept | |
| y_max = intercept + 1.0 | |
| y_min = np.min(y_calibrated_log) - 1.5 | |
| fig = go.Figure() | |
| fig.add_trace(go.Scatter(x=x_freq, y=y_upper_threat, mode='lines', line=dict(width=0), showlegend=False, hoverinfo='skip')) | |
| 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')) | |
| 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')) | |
| line_color = '#ff007f' if is_fake else '#00f2fe' | |
| 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))) | |
| 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")) | |
| 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")) | |
| fig.update_layout(xaxis_type="log", height=380, margin=dict(l=30, r=20, t=30, b=30), | |
| legend=dict(yanchor="top", y=0.99, xanchor="right", x=0.99, bgcolor='rgba(15, 23, 42, 0.8)', font=font_config), | |
| paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)', | |
| xaxis_title="Log10 Spatial Frequency", yaxis_title="Log10 Signal Energy", | |
| xaxis=grid_config, yaxis={**grid_config, 'range': [y_min, y_max]}) | |
| return fig | |
| def create_speedometer(value, title, max_val=100, is_prob=True): | |
| color = "#ff007f" if (value > 50 and is_prob) or (value > 3.5 and not is_prob) else "#00e676" | |
| fig = go.Figure(go.Indicator( | |
| mode="gauge+number", value=value, | |
| title={'text': title, 'font': {'size': 14, 'color': '#94a3b8'}}, | |
| number={'suffix': "%" if is_prob else " Z", 'font': {'size': 32, 'color': '#f8fafc', 'family': 'Inter', 'weight': 'bold'}}, | |
| gauge={ | |
| 'axis': {'range': [None, max_val], 'tickwidth': 1, 'tickcolor': "#334155", 'tickfont': font_config}, | |
| 'bar': {'color': color, 'thickness': 0.8}, | |
| 'bgcolor': "rgba(255,255,255,0.05)", | |
| '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)"}], | |
| 'threshold': {'line': {'color': "#ff007f", 'width': 3}, 'thickness': 0.75, 'value': value} | |
| } | |
| )) | |
| fig.update_layout(height=240, margin=dict(l=20, r=20, t=40, b=20), paper_bgcolor='rgba(0,0,0,0)') | |
| return fig | |
| def create_z_distribution_plot(z_array, color): | |
| fig = go.Figure() | |
| fig.add_trace(go.Histogram(x=z_array, marker_color=color, nbinsx=60, name="Patch Z-Scores", opacity=0.85)) | |
| 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") | |
| 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)', | |
| xaxis=grid_config, yaxis=grid_config) | |
| return fig | |
| # ============================================================================== | |
| # 4. GRADIO EVENT LOGIC (ZeroGPU Ready) | |
| # ============================================================================== | |
| def execute_scan(file_paths, mode, progress=gr.Progress()): | |
| if not file_paths: | |
| 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>" | |
| if isinstance(file_paths, str): file_paths = [file_paths] | |
| results = [] | |
| for fpath in progress.tqdm(file_paths, desc="Extracting CMOS DNA & Spectral Signals"): | |
| engine = UnbiasedPhysicsForensics(fpath) | |
| if engine.valid: results.append(engine.analyze()) | |
| fakes = sum(1 for r in results if r['Fake_Prob'] >= 50) | |
| total = len(results) | |
| safe = total - fakes | |
| audit_html = f""" | |
| <div style="display: flex; gap: 15px; margin-top: 15px;"> | |
| <div class="glass-metric" style="border-top: 4px solid #00f2fe;"> | |
| <div class="metric-title">Tensors Analyzed</div> | |
| <div class="metric-value" style="color: #f8fafc;">{total}</div> | |
| </div> | |
| <div class="glass-metric" style="border-top: 4px solid #00e676;"> | |
| <div class="metric-title">Physically Verified</div> | |
| <div class="metric-value" style="color: #00e676;">{safe}</div> | |
| </div> | |
| <div class="glass-metric" style="border-top: 4px solid #ff007f;"> | |
| <div class="metric-title">Anomalies Detected</div> | |
| <div class="metric-value" style="color: #ff007f;">{fakes}</div> | |
| </div> | |
| </div> | |
| """ | |
| choices = [r['Filename'] for r in results] | |
| return results, gr.update(choices=choices, value=choices[0] if choices else None), audit_html | |
| def update_dashboard(selected_file, results): | |
| if not selected_file or not results: return [gr.update(visible=False)] + [gr.update()] * 17 | |
| data = next((r for r in results if r['Filename'] == selected_file), None) | |
| if not data: return [gr.update(visible=False)] + [gr.update()] * 17 | |
| is_fake = data['Fake_Prob'] >= 50 | |
| if is_fake: | |
| 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>" | |
| else: | |
| 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>" | |
| pdf_path = generate_pdf_report_gradio(data) | |
| 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>" | |
| 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>" | |
| 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>" | |
| 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>" | |
| 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>" | |
| return ( | |
| gr.update(visible=True), alert, pdf_path, cv2.cvtColor(data['Image'], cv2.COLOR_RGB2BGR), | |
| create_pure_heatmap(data['Z_Grid']), spatial_diag, | |
| create_spectral_forensics_plot(data['R_Vals'], data['P_Vals'], data['Alpha_Val'], data['Intercept'], is_fake=(data['Global_Prob'] > 50)), | |
| create_speedometer(data['Global_Prob'], "Spectral Decay Probability", 100, True), fft_diag, | |
| create_speedometer(data['Max_Z']['ELA'], "Compression Anomaly", 10, False), create_z_distribution_plot(data['Z_Arrays']['ELA'], "#00f2fe"), ela_diag, | |
| create_speedometer(data['Max_Z']['CMOS_DNA'], "CMOS DNA Absence", 10, False), create_z_distribution_plot(data['Z_Arrays']['CMOS_DNA'], "#8b5cf6"), noise_diag, | |
| create_speedometer(data['Max_Z']['Chroma'], "Chroma Overlap Failure", 10, False), create_z_distribution_plot(data['Z_Arrays']['Chroma'], "#10b981"), chroma_diag | |
| ) | |
| # ============================================================================== | |
| # 5. GRADIO UI LAYOUT (Deep Obsidian & Bioluminescent Theme) | |
| # ============================================================================== | |
| custom_theme = gr.themes.Default( | |
| primary_hue="cyan", secondary_hue="fuchsia", neutral_hue="slate", | |
| font=[gr.themes.GoogleFont("Inter"), "sans-serif"], | |
| ).set( | |
| body_background_fill="#070c14", | |
| block_background_fill="rgba(15, 23, 42, 0.6)", | |
| block_border_width="1px", block_border_color="rgba(0, 242, 254, 0.2)", | |
| button_primary_background_fill="linear-gradient(135deg, #00f2fe 0%, #4facfe 100%)", | |
| button_primary_background_fill_hover="linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)", | |
| button_primary_text_color="#070c14" | |
| ) | |
| custom_css = """ | |
| body, .prose, .markdown-text, label, .gr-text-input { color: #f8fafc !important; } | |
| body::before { | |
| content: ""; position: fixed; top: 0; left: 0; width: 100%; height: 100%; | |
| background-image: radial-gradient(rgba(0, 242, 254, 0.15) 1px, transparent 1px); | |
| background-size: 40px 40px; | |
| z-index: -1; pointer-events: none; opacity: 0.5; | |
| } | |
| .glass-card { | |
| background: rgba(15, 23, 42, 0.7); backdrop-filter: blur(20px); -webkit-backdrop-filter: blur(20px); | |
| border-radius: 16px; border: 1px solid rgba(0, 242, 254, 0.15); | |
| box-shadow: 0 4px 30px rgba(0, 0, 0, 0.5), inset 0 0 20px rgba(0, 242, 254, 0.05); | |
| padding: 25px; transition: transform 0.2s ease, border-color 0.3s; | |
| } | |
| .glass-card:hover { border-color: rgba(0, 242, 254, 0.4); } | |
| .glass-metric { | |
| background: rgba(7, 12, 20, 0.8); | |
| border-radius: 12px; padding: 20px 10px; flex: 1; text-align: center; | |
| box-shadow: inset 0 0 15px rgba(0,0,0,0.8); border: 1px solid rgba(255,255,255,0.05); | |
| } | |
| .metric-title { font-size: 0.85rem; color: #94a3b8; font-weight: 700; letter-spacing: 1px; text-transform: uppercase;} | |
| .metric-value { font-size: 2.8rem; font-weight: 800; margin-top: 5px; font-family: 'Inter', sans-serif;} | |
| .hero-box { | |
| background: linear-gradient(135deg, rgba(15,23,42,0.9) 0%, rgba(7,12,20,0.9) 100%); | |
| color: #f8fafc; padding: 50px 40px; border-radius: 20px; margin-bottom: 30px; | |
| box-shadow: 0 0 40px rgba(0, 242, 254, 0.1); text-align: center; | |
| border: 1px solid rgba(0, 242, 254, 0.3); | |
| position: relative; overflow: hidden; | |
| } | |
| .hero-box::after { | |
| content: ''; position: absolute; top: -50%; left: -50%; width: 200%; height: 200%; | |
| background: radial-gradient(circle, rgba(0,242,254,0.1) 0%, transparent 60%); | |
| animation: rotateGlow 15s linear infinite; pointer-events: none; | |
| } | |
| @keyframes rotateGlow { 100% { transform: rotate(360deg); } } | |
| .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);} | |
| .hero-box p { margin-top: 10px; font-size: 1.2rem; font-weight: 300; color: #cbd5e1; opacity: 0.9;} | |
| .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);} | |
| .alert-secure { border: 1px solid #00e676; box-shadow: inset 0 0 20px rgba(0,230,118,0.1); } | |
| .alert-threat { border: 1px solid #ff007f; box-shadow: inset 0 0 20px rgba(255,0,127,0.1); } | |
| .glass-alert h2 { margin-top: 0; font-weight: 800; font-size: 1.6rem;} | |
| .insight-pill { display: inline-block; padding: 6px 18px; border-radius: 20px; font-size: 0.9rem; font-weight: 600; text-align: center; margin-top: 15px;} | |
| .pill-green { background: rgba(0,230,118,0.1); color: #00e676; border: 1px solid #00e676;} | |
| .pill-red { background: rgba(255,0,127,0.1); color: #ff007f; border: 1px solid #ff007f;} | |
| .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;} | |
| h1, h2, h3, h4 { color: #f8fafc !important; font-weight: 700 !important; } | |
| """ | |
| with gr.Blocks(theme=custom_theme, css=custom_css) as demo: | |
| gr.HTML(""" | |
| <div class="hero-box"> | |
| <h1>DeepScan OS</h1> | |
| <p>Advanced Computational Physics & Spectral Frequency Media Forensics</p> | |
| </div> | |
| """) | |
| results_state = gr.State([]) | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| gr.Markdown("### 🧬 Architecture Overview") | |
| gr.HTML(""" | |
| <div class='glass-card' style='padding: 20px; margin-bottom: 20px;'> | |
| <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> | |
| <p style='font-size: 0.95rem; color: #cbd5e1; line-height: 1.5; font-weight:300;'> | |
| 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. | |
| </p> | |
| <hr style='border-top: 1px solid rgba(255,255,255,0.1); margin: 15px 0;'> | |
| <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> | |
| <p style='font-size: 0.95rem; color: #cbd5e1; line-height: 1.5; font-weight:300;'> | |
| 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. | |
| </p> | |
| </div> | |
| """) | |
| with gr.Column(scale=3): | |
| with gr.Tabs(): | |
| with gr.Tab("🚀 1. Scan Hub"): | |
| with gr.Group(elem_classes=["glass-card"]): | |
| gr.Markdown("### ⚙️ Pipeline Configuration") | |
| mode_radio = gr.Radio(["Single Image Pipeline", "Batch/Folder Distributed (PySpark)"], label="Execution Architecture", value="Single Image Pipeline") | |
| file_input = gr.File(label="Upload Media Tensor(s)", file_count="multiple", type="filepath", file_types=["image"]) | |
| scan_btn = gr.Button("⚡ INITIATE SPECTRAL SCAN", variant="primary", size="lg") | |
| gr.HTML("<br>") | |
| gr.Markdown("### 📊 Batch Telemetry") | |
| global_audit = gr.HTML("<div style='color: #64748b; font-size: 1rem; font-weight: 500; text-align: center; padding: 20px;'>Awaiting tensor ingestion...</div>") | |
| file_dropdown = gr.Dropdown(label="Select Processed Tensor to view in Dashboard", choices=[], interactive=True) | |
| with gr.Tab("🔭 2. Telemetry Dashboard"): | |
| report_container = gr.Group(visible=False, elem_classes=["glass-card"]) | |
| with report_container: | |
| main_alert = gr.HTML("") | |
| pdf_btn = gr.File(label="📄 Export Certified Security Report (PDF)") | |
| gr.HTML("<br>") | |
| gr.Markdown("### 🌟 I. Spectral Frequency-Domain Analysis") | |
| 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>") | |
| with gr.Row(): | |
| fft_plot = gr.Plot(scale=2) | |
| fft_speed = gr.Plot(scale=1) | |
| fft_text = gr.HTML("") | |
| gr.HTML("<br><br>") | |
| gr.Markdown("### 🔍 II. Spatial Fabric & Sub-Metric Anomalies") | |
| gr.HTML("<div class='section-desc'>A 98th-percentile robust Z-score pipeline isolating localized structural manipulation via hardware fingerprint absence.</div>") | |
| with gr.Row(): | |
| with gr.Column(): | |
| img_display = gr.Image(label="Source Media", interactive=False) | |
| with gr.Column(): | |
| hm_plot = gr.Plot(label="Anomaly Spatial Heatmap") | |
| spatial_text = gr.HTML("") | |
| gr.HTML("<br><br>") | |
| with gr.Row(): | |
| with gr.Column(variant="panel", elem_classes=["glass-card"]): | |
| gr.Markdown("**Compression Variation (ELA)**") | |
| ela_speed = gr.Plot() | |
| ela_hist = gr.Plot() | |
| ela_text = gr.HTML("") | |
| with gr.Column(variant="panel", elem_classes=["glass-card"]): | |
| gr.Markdown("**CMOS DNA Absence (PRNU)**") | |
| noise_speed = gr.Plot() | |
| noise_hist = gr.Plot() | |
| noise_text = gr.HTML("") | |
| with gr.Column(variant="panel", elem_classes=["glass-card"]): | |
| gr.Markdown("**Color Chroma Variance**") | |
| chroma_speed = gr.Plot() | |
| chroma_hist = gr.Plot() | |
| chroma_text = gr.HTML("") | |
| with gr.Tab("📚 3. Core Engine Architecture"): | |
| gr.HTML(""" | |
| <div class="glass-card" style="margin-top: 10px;"> | |
| <h2 style="color: #f8fafc; font-size: 2rem; font-weight: 800; margin-top: 0;">Physics-Informed Media Provenance</h2> | |
| <p style="font-size: 1.15rem; color: #cbd5e1; line-height: 1.6; font-weight: 300;"> | |
| DeepScan OS bypasses standard deep learning classifiers—which are easily fooled by adversarial noise—in favor of <b>physics-informed forensic integrity</b>. | |
| By evaluating the inherent mathematical constraints of optical light and silicon camera hardware, the system flags generative manipulations purely based on physical impossibilities. | |
| </p> | |
| <br> | |
| <div style="display: flex; gap: 25px; flex-wrap: wrap;"> | |
| <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);"> | |
| <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> | |
| <p style="color: #cbd5e1; font-size: 1rem; line-height: 1.5; font-weight: 300;"> | |
| 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). | |
| </p> | |
| </div> | |
| <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);"> | |
| <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> | |
| <p style="color: #cbd5e1; font-size: 1rem; line-height: 1.5; font-weight: 300;"> | |
| 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. | |
| </p> | |
| </div> | |
| </div> | |
| </div> | |
| """) | |
| scan_btn.click( | |
| fn=execute_scan, inputs=[file_input, mode_radio], outputs=[results_state, file_dropdown, global_audit] | |
| ) | |
| file_dropdown.change( | |
| fn=update_dashboard, inputs=[file_dropdown, results_state], | |
| outputs=[ | |
| report_container, main_alert, pdf_btn, img_display, hm_plot, spatial_text, | |
| fft_plot, fft_speed, fft_text, | |
| ela_speed, ela_hist, ela_text, | |
| noise_speed, noise_hist, noise_text, | |
| chroma_speed, chroma_hist, chroma_text | |
| ] | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch() |