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}
(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
(α < 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)
# ==============================================================================
@gpu_decorator
def execute_scan(file_paths, mode, progress=gr.Progress()):
if not file_paths:
return [], gr.update(choices=[], value=None), "
Physical structural limits breached. Generative AI or localized spatial manipulation confirmed via CMOS DNA and Spectral deviation.
Asset fully conforms to natural physical hardware constraints. CMOS DNA intact.
Advanced Computational Physics & Spectral Frequency Media Forensics
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.
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.
DeepScan OS bypasses standard deep learning classifiers—which are easily fooled by adversarial noise—in favor of physics-informed forensic integrity. By evaluating the inherent mathematical constraints of optical light and silicon camera hardware, the system flags generative manipulations purely based on physical impossibilities.
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).
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.