Skip to content

Latest commit

 

History

History
476 lines (400 loc) · 18.1 KB

implementation_plan.md

File metadata and controls

476 lines (400 loc) · 18.1 KB

Truth Engine — Architecture & Technology Blueprint (v2)

System Overview

A defense-in-depth verification platform that evaluates digital assets across three axes (Content Authenticity, Contextual Consistency, Source Credibility), unified by an explainable AI layer and a 3D-interactive frontend.

Hard Constraints:

  • ✅ All free-tier APIs — zero cost
  • ✅ No local ML inference — everything runs in the cloud
  • ✅ Cloudflare Workers AI — primary LLM/VLM provider (free Llama 70B + Vision 11B)
  • ✅ Spline embed — 3D Trust Sphere via @splinetool/react-spline/next
  • ✅ Latest framework versions — Next.js 15, etc.
  • ✅ Environment-agnostic — no assumptions about dev machine
graph TB
    subgraph "Frontend — Next.js 15 App Router"
        UI["3D Trust Sphere<br/>(Spline Embed)"]
        Upload["Media Upload<br/>(react-dropzone)"]
        Report["Glass Box CoT Report"]
        Dash["Analysis Dashboard"]
    end

    subgraph "Backend — FastAPI (Python)"
        Router["Async API Router"]
        Orch["Analysis Orchestrator"]
        CoT["CoT Report Generator"]
    end

    subgraph "Axis I — Content Authenticity"
        META["C2PA / EXIF Extractor"]
        HF["HuggingFace Inference API<br/>(Deepfake Detection)"]
        CLASH["Integrity Clash Auditor"]
        IMBD["ImBD Stylometric Analyzer"]
    end

    subgraph "Axis II — Contextual Consistency"
        CFVLM["Cloudflare AI<br/>Llama 3.2 Vision 11B"]
        COS["Cosine Similarity<br/>(Sentence Embeddings)"]
    end

    subgraph "Axis III — Source Credibility"
        WHOIS["WHOIS Lookup<br/>(python-whois)"]
        VT["VirusTotal API<br/>(Free Tier)"]
        SAFE["Google Safe Browsing<br/>(Free API)"]
    end

    subgraph "LLM Layer — Cloudflare Workers AI"
        LLAMA["Llama 3.3 70B<br/>(CoT Report Generation)"]
        EMBED["BGE Embeddings<br/>(Cosine Similarity)"]
    end

    Upload --> Router
    Router --> Orch
    Orch --> META & HF & IMBD & CFVLM & WHOIS & VT & SAFE
    META & HF --> CLASH
    CFVLM --> COS
    COS -.-> EMBED
    CLASH & IMBD & COS & WHOIS & VT & SAFE --> CoT
    CoT -.-> LLAMA
    CoT --> Report
    Report --> UI
Loading

Technology Stack

Frontend

Layer Technology Justification
Framework Next.js 15 (App Router) SSR, API routes, React Server Components
Language TypeScript Type safety for complex verification payloads
3D Engine @splinetool/react-spline Pre-designed Trust Sphere via Spline editor
Styling Tailwind CSS 4 Rapid hackathon velocity, utility-first
Animations Framer Motion Orchestrated transitions, layout animations
Charts Recharts Stylometric curves, radar charts
State Zustand Lightweight reactive state for analysis flow
File Upload react-dropzone Drag-and-drop with validation
Markdown react-markdown + remark-gfm Rendering CoT forensic reports
Icons Lucide React Consistent icon set

Backend

Layer Technology Justification
Framework FastAPI Async-first, auto OpenAPI docs
Package Manager uv Fast dependency resolution
Image Analysis Pillow + python-magic EXIF extraction, file type validation
C2PA Parsing c2pa-python Content Credentials extraction
WHOIS python-whois Domain registration data (free, no API key)
HTTP Client httpx Async HTTP for all API calls

Free Cloud APIs (Zero Cost)

Service What It Provides Free Tier Limits
Cloudflare Workers AI Llama 3.3 70B (text), Llama 3.2 11B Vision, BGE embeddings 10,000 neurons/day
HuggingFace Inference API Deepfake detection models (Deep-Fake-Detector-v2-Model) Rate-limited, generous for prototyping
VirusTotal API Domain/URL threat intelligence 4 requests/minute, 500/day (free key)
Google Safe Browsing URL malware/phishing check 10,000 requests/day (free key)
python-whois WHOIS domain data Unlimited (direct WHOIS queries, no API)

Note

API Keys Required (all free):


Frontend Architecture

Spline Integration

// Direct embed using the Next.js-optimized Spline component
import Spline from '@splinetool/react-spline/next';

export default function TrustSphere({ trustScore }: { trustScore: number }) {
  return (
    <Spline
      scene="https://prod.spline.design/HiewMHr9ZSjwuSqh/scene.splinecode"
      onLoad={(splineApp) => {
        // Data-bind trust score to Spline variables for visual state changes
        // splineApp.setVariable('trustScore', trustScore);
      }}
    />
  );
}

Trust Sphere Visual States

State Trust Score Visual Behavior
Idle — Gentle rotation, translucent glow
Analyzing — Speed up rotation, pulsing particles
Verified > 80 Stable, smooth green/blue aura
Suspicious 50–80 Slight fractures, amber glow, wobble
Manipulated < 50 Shatters, red pulse, erratic orbit

Page Structure

/                     → Landing page with 3D Trust Sphere hero
/analyze              → Upload + real-time analysis interface
/analyze/[id]         → Full forensic report with all 3 axes
/about                → Methodology explainer

Key UI Components

Component Purpose
TrustSphere3D Spline 3D embed with data-bound visual states
UploadZone Drag-and-drop with file type detection (image/text/URL)
AnalysisProgress Step-by-step progress across all 3 axes
IntegrityClashCard Side-by-side metadata vs. AI detection comparison
HeatmapViewer Manipulation heatmap overlay on original image
StyleCurveChart ImBD curvature plot (Recharts line chart)
ContextCompare VLM description vs. user claim with diff highlighting
ThreatRadar OSINT threat matrix radar chart
GlassBoxReport Formatted CoT markdown with collapsible reasoning steps
TrustScoreGauge Animated circular gauge (0–100)

API Contract

POST /api/v1/analyze

Content-Type: multipart/form-data

Fields:
  file:          <binary>      — image or text file
  claim:         <string>      — user's caption/claim about the media (Axis II)
  source_url:    <string>      — URL where media was found (Axis III, optional)

Response: VerificationReport

interface VerificationReport {
  id: string;
  timestamp: string;
  overall_trust_score: number;  // 0–100
  risk_level: "LOW" | "MEDIUM" | "HIGH" | "CRITICAL";

  // ── Axis I: Content Authenticity ──
  axis_1_authenticity: {
    score: number;
    integrity_clash: {
      metadata_claim: string | null;       // e.g. "Human Created"
      ai_detection_result: string;         // e.g. "AI Generated (94%)"
      contradiction_detected: boolean;
      severity: "NONE" | "LOW" | "HIGH";
    };
    spatial_localization: {
      heatmap_base64: string | null;       // Grad-CAM overlay as base64 PNG
      manipulation_probability: number;
    };
    stylometric_analysis: {               // only populated for text uploads
      enabled: boolean;
      imbd_alignment_score: number;        // 0–1
      curvature_data: number[];            // for frontend chart
      verdict: string;
    };
  };

  // ── Axis II: Contextual Consistency ──
  axis_2_context: {
    score: number;
    vlm_description: string;               // what the VLM independently sees
    user_claim: string;                    // what the user claimed
    cosine_similarity: number;             // 0–1
    semantic_mismatch_detected: boolean;
    mismatch_details: string | null;
  };

  // ── Axis III: Source Credibility ──
  axis_3_source: {
    score: number;
    domain_info: {
      domain: string;
      registration_age_days: number;
      registrar: string;
      ssl_valid: boolean;
    } | null;
    threat_intel: {
      virustotal_detections: number | null;
      blocklist_hits: string[];
      safe_browsing_threats: string[];
    };
    risk_assessment: string;
  };

  // ── Explainable AI ──
  glass_box_report: {
    chain_of_thought: string;   // Full CoT reasoning in markdown
    summary: string;             // 2–3 sentence executive summary
    confidence: number;
  };
}

Axis Implementation Details

Axis I: Content Authenticity

1.1 Integrity Clash Auditor

Image Upload → c2pa-python (extract provenance) 
             → HuggingFace API (AI detection: prithivMLmods/Deep-Fake-Detector-v2-Model)
             → Clash Logic: if metadata says "human" but detector says >80% AI → CONTRADICTION

1.2 Spatial Localization (Heatmap)

Image Upload → HuggingFace API (deepfake detection with attention/confidence map)
             → Generate heatmap overlay (Pillow/matplotlib on backend)
             → Return as base64 PNG

Note

Full Grad-CAM requires model internals. For the hackathon, we'll use the HF model's confidence scores to generate a pseudo-heatmap, or use a model that exposes attention maps. This is a pragmatic trade-off — the heatmap will be a confidence visualization rather than true Grad-CAM, but visually serves the same purpose for the demo.

1.3 ImBD Stylometric Analysis (Text)

Text Upload → Tokenize → Send to Cloudflare AI (Llama 3.3 70B) with logprobs
            → Compute token probability curvature locally (lightweight math)
            → Return alignment score + curvature array for charting
  • Cloudflare AI Llama supports logprobs — we measure how predictable the text is to the AI
  • High predictability (low curvature variance) = likely AI-generated/revised

Axis II: Contextual Consistency

2.1 Generate-then-Detect

Image + Claim → Cloudflare AI Llama 3.2 Vision 11B (generate scene description)
              → Cloudflare AI BGE Embeddings (embed both description + claim)
              → Cosine similarity computation
              → If similarity < threshold → SEMANTIC MISMATCH
  • All within Cloudflare's free tier — zero cost
  • BGE-base-en-v1.5 is available on Cloudflare Workers AI for embeddings

Axis III: Source Credibility

3.1 OSINT Threat Matrix

URL → python-whois (domain age, registrar)
    → VirusTotal API (malware/phishing detections)
    → Google Safe Browsing API (threat lists)
    → Aggregate into risk score
  • All free. python-whois requires no API key at all.

Glass Box CoT Report

All Axis Results → Structured prompt to Cloudflare AI Llama 3.3 70B
                 → Chain-of-Thought forensic analysis
                 → Markdown formatted report

Prompt Strategy:

You are a digital forensics expert. Analyze the following verification data 
and produce a Chain-of-Thought forensic report. Explain your reasoning step 
by step, citing specific numerical evidence from each axis.

AXIS I DATA: {integrity_clash_results}
AXIS II DATA: {context_analysis_results}  
AXIS III DATA: {osint_results}

Format your response as:
## Chain of Thought
[step-by-step reasoning]

## Executive Summary
[2-3 sentence conclusion]

## Confidence
[0-100 score with justification]

Project Structure

menacraft_hackathon/
├── web-app/                          # Next.js 15 App
│   ├── src/
│   │   ├── app/
│   │   │   ├── layout.tsx             # Root layout + fonts + metadata
│   │   │   ├── page.tsx               # Landing page with Trust Sphere
│   │   │   ├── analyze/
│   │   │   │   ├── page.tsx           # Upload + analysis interface
│   │   │   │   └── [id]/
│   │   │   │       └── page.tsx       # Full report view
│   │   │   └── about/
│   │   │       └── page.tsx           # Methodology explainer
│   │   ├── components/
│   │   │   ├── TrustSphere3D.tsx      # Spline embed
│   │   │   ├── UploadZone.tsx         # File upload drag-and-drop
│   │   │   ├── AnalysisProgress.tsx   # Step progress indicator
│   │   │   ├── IntegrityClashCard.tsx # Axis I clash visualization
│   │   │   ├── HeatmapViewer.tsx      # Manipulation heatmap overlay
│   │   │   ├── StyleCurveChart.tsx    # ImBD stylometric chart
│   │   │   ├── ContextCompare.tsx     # Axis II VLM vs claim
│   │   │   ├── ThreatRadar.tsx        # Axis III radar chart
│   │   │   ├── GlassBoxReport.tsx     # CoT forensic report
│   │   │   ├── TrustScoreGauge.tsx    # Animated score gauge
│   │   │   └── Navbar.tsx             # Navigation
│   │   ├── lib/
│   │   │   ├── api.ts                 # Backend API client
│   │   │   └── types.ts              # TypeScript interfaces
│   │   └── store/
│   │       └── analysis.ts           # Zustand store
│   ├── public/
│   ├── tailwind.config.ts
│   ├── next.config.ts
│   └── package.json
│
├── backend/
│   ├── core/
│   │   ├── __init__.py
│   │   ├── main.py                    # FastAPI app entry point
│   │   ├── config.py                  # Environment variables / API keys
│   │   ├── models.py                  # Pydantic response models
│   │   └── orchestrator.py            # Analysis pipeline coordinator
│   ├── services/
│   │   ├── __init__.py
│   │   ├── authenticity/
│   │   │   ├── __init__.py
│   │   │   ├── metadata_extractor.py  # C2PA + EXIF extraction
│   │   │   ├── ai_detector.py         # HuggingFace deepfake API
│   │   │   ├── integrity_clash.py     # Clash logic
│   │   │   ├── heatmap_generator.py   # Manipulation heatmap
│   │   │   └── stylometric.py         # ImBD text analysis
│   │   ├── context/
│   │   │   ├── __init__.py
│   │   │   └── context_auditor.py     # VLM + cosine similarity
│   │   ├── osint/
│   │   │   ├── __init__.py
│   │   │   ├── whois_lookup.py        # Domain WHOIS data
│   │   │   ├── virustotal.py          # VT API integration
│   │   │   └── safe_browsing.py       # Google Safe Browsing
│   │   └── llm/
│   │       ├── __init__.py
│   │       └── cloudflare_ai.py       # Cloudflare Workers AI client
│   ├── pyproject.toml                 # uv project config
│   └── .env.example                   # Required API keys template
│
├── docs/
│   └── specification.md               # This spec document
├── .gitignore
├── LICENSE
└── README.md

Team Work Split

Important

All team members develop against the shared VerificationReport TypeScript interface. Backend stubs mock data on day 1 so frontend can develop in parallel.

Role Scope Key Deliverables
Frontend Next.js app, Spline, all components, Tailwind styling Landing page, Upload flow, Report page, 3D sphere
ML/API Engineer Axis I services (HF API, C2PA, ImBD via CF AI) authenticity/ service module
Backend Engineer FastAPI server, Axis II + III, orchestrator, CoT report backend/core/, backend/services/context-consistency-service/, backend/services/source-intelligence-service/, backend/services/ai-inference-service/
Integration API contract, CORS, deployment, demo data End-to-end flow, demo prep

Phased Implementation Roadmap

Phase 1: Scaffold (30 min)

  • Initialize Next.js 15 app in web-app/
  • Initialize FastAPI project with uv in backend/
  • Set up Tailwind CSS 4, Spline, Framer Motion
  • Create .env.example with all required API key slots
  • Stub /api/v1/analyze returning mock VerificationReport

Phase 2: Frontend Shell (2–3 hrs)

  • Landing page with Spline Trust Sphere hero
  • Upload page with drag-and-drop
  • Report page layout with all component shells
  • Dark theme design system (glassmorphism, gradients)

Phase 3: Backend Pipelines (3–4 hrs)

  • Cloudflare AI client (Llama 70B text + Vision 11B + BGE embeddings)
  • Axis I: C2PA extractor → HF deepfake detector → Integrity Clash logic
  • Axis I: ImBD stylometric analyzer via CF AI logprobs
  • Axis II: VLM scene description → embedding similarity
  • Axis III: WHOIS + VirusTotal + Safe Browsing aggregation
  • Orchestrator: parallel execution of all axes
  • CoT Report: Llama 70B forensic synthesis

Phase 4: Integration & Polish (2 hrs)

  • Connect frontend to live backend
  • Wire Trust Sphere state to trust score
  • Animate analysis progress
  • Polish Glass Box report rendering
  • Error handling, loading states

Phase 5: Demo Prep (1 hr)

  • Prepare demo assets (known deepfake, miscontextualized photo, suspicious domain)
  • End-to-end walkthrough
  • README with setup instructions

Verification Plan

Automated

  • npm run build — frontend compiles cleanly
  • pytest — backend unit tests with mocked API responses
  • Lighthouse audit — performance + accessibility

Demo Scenarios

  1. Upload known deepfake → Axis I flags manipulation + heatmap highlights face
  2. Upload authentic image with forged C2PA → Integrity Clash triggers contradiction
  3. Upload AI-generated text → ImBD alignment score > 0.7
  4. Upload real photo + false caption → Axis II flags semantic mismatch
  5. Submit suspicious/new domain → Axis III threat radar populates
  6. Verify Trust Sphere 3D reacts to different final scores