Commit ·
7b09f2e
1
Parent(s): c438edd
Add free enhanced verification pipeline
Browse filesFiles changed (24)
- DEPLOYMENT.mdAdded+103
- README.md+39
- backend/.dockerignoreAdded+7
- backend/.env.exampleAdded+18
- backend/DockerfileAdded+19
- backend/README.mdAdded+44
- backend/analyzers/ai_detectors.pyAdded+197
- backend/analyzers/config.pyAdded+61
- backend/analyzers/enhanced.pyAdded+303
- backend/analyzers/feedback.pyAdded+137
- backend/analyzers/image_analyzer.py+9-1
- backend/analyzers/provenance.pyAdded+147
- backend/analyzers/text_analyzer.py+3-1
- backend/analyzers/video_analyzer.py+3-1
- backend/analyzers/web_research.pyAdded+266
- backend/main.py+24-8
- backend/models/schemas.py+48
- backend/tests/test_enhanced_analysis.pyAdded+140
- frontend/.env.exampleAdded+1
- frontend/public/_redirectsAdded+1
- frontend/src/components/EnhancedInsights.tsxAdded+200
- frontend/src/components/ResultCard.tsx+3
- frontend/src/lib/types.ts+48
- frontend/wrangler.jsoncAdded+5
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103# Deployment
TruthShield AI deploys as two separate services:
- Frontend: Cloudflare Pages from `frontend/`- Backend: Hugging Face Spaces Docker Space from `backend/`
## 1. Deploy The Backend To Hugging Face Spaces
Create a new Hugging Face Space:
- Owner: your Hugging Face username or org- Space name: `truthshield-ai-backend`- SDK: Docker- Visibility: public or private
The Space root should contain the contents of this repo's `backend/` folder, including `Dockerfile`, `README.md`, `requirements.txt`, `main.py`, `analyzers/`, `models/`, and `utils/`.
With Git:
```powershellgit clone https://huggingface.co/spaces/<hf-user>/truthshield-ai-backend hf-truthshield-backendCopy-Item -Recurse -Force .\backend\* .\hf-truthshield-backend\Set-Location .\hf-truthshield-backendgit add .git commit -m "Deploy TruthShield backend"git push```
After the Space builds, the backend URL will be:
```texthttps://<hf-user>-truthshield-ai-backend.hf.space```
Check:
```texthttps://<hf-user>-truthshield-ai-backend.hf.space/api/health```
## 2. Deploy The Frontend To Cloudflare Pages
Set the frontend production environment variable:
```textVITE_API_BASE_URL=https://<hf-user>-truthshield-ai-backend.hf.space```
If you deploy from the Cloudflare dashboard:
- Connect the GitHub repo- Root directory: `frontend`- Framework preset: Vite- Build command: `npm run build`- Build output directory: `dist`- Environment variable: `VITE_API_BASE_URL`
If you deploy from the CLI:
```powershellSet-Location .\frontend$env:VITE_API_BASE_URL = "https://<hf-user>-truthshield-ai-backend.hf.space"npm run buildnpx wrangler loginnpx wrangler pages deploy .\dist --project-name=truthshield-ai-frontendRemove-Item Env:VITE_API_BASE_URL```
The Pages URL will look like:
```texthttps://truthshield-ai-frontend.pages.dev```
## 3. Lock Backend CORS To Your Frontend
After Cloudflare Pages gives you the final frontend URL, set this Space variable:
```textFRONTEND_ORIGINS=https://truthshield-ai-frontend.pages.dev```
If you add a custom domain later, append it with a comma:
```textFRONTEND_ORIGINS=https://truthshield-ai-frontend.pages.dev,https://www.your-domain.com```
## 4. Final Smoke Test
Open the deployed frontend and run:
- Text scan with one of the demo examples- Image upload with a small `.jpg` or `.png`- Health check directly at `/api/health`
If the frontend loads but requests fail, first check:
- Cloudflare Pages environment variable `VITE_API_BASE_URL`- Hugging Face Space build logs- Hugging Face Space variable `FRONTEND_ORIGINS`- Browser devtools console for CORS or network errors19 unmodified lines20212223242542 unmodified lines68697071727316 unmodified lines90919293949523 unmodified lines11912012112212312445 unmodified lines1701711721731741751 unmodified line17717817918018118219 unmodified lines- Text/post analysis with demo examples for judges- Truth Score, risk level, verdict, summary, and recommendations- Evidence breakdown for metadata, visual consistency, compression, language risk, and claim risk- AI apocalypse command-center UI- Local-only MVP with no paid API keys required- Safe file handling with temporary video storage and cleanup42 unmodified lineshttp://localhost:8000/api/health```## Run The FrontendOpen a second terminal:16 unmodified linesVITE_API_BASE_URL=http://localhost:8000```## API Endpoints### GET `/api/health`23 unmodified lines- `recommendations`- `evidence`- `technical_details`- `disclaimer`### POST `/api/analyze/video`45 unmodified lines- Entropy- Blur / over-smoothing estimate- Compression and texture consistency- Sampled video frame scoresText checks include:1 unmodified line- Source or link indicators- Balanced wording- Dates, locations, or verifiable details- All-caps ratio- Urgency and fear language- Conspiracy-style phrases19 unmodified lines2021222324252642 unmodified lines697071727374757677787980818283848586878889909192939495969716 unmodified lines11411511611711811912012112212323 unmodified lines14714814915015115215315415515615715815945 unmodified lines2052062072082092102112122131 unmodified line21521621721821922022119 unmodified lines- Text/post analysis with demo examples for judges- Truth Score, risk level, verdict, summary, and recommendations- Evidence breakdown for metadata, visual consistency, compression, language risk, and claim risk- Free enhanced verification with local synthetic-image signals, optional C2PA provenance checks, optional free-capped Brave Search research, citations, and custom feedback- AI apocalypse command-center UI- Local-only MVP with no paid API keys required- Safe file handling with temporary video storage and cleanup42 unmodified lineshttp://localhost:8000/api/health```### Optional Free Enhanced VerificationEnhanced analysis is enabled by default and remains free. If optional tools are missing, TruthShield falls back to deterministic local signals and explains what was unavailable in the report.Backend environment variables:```textENABLE_ENHANCED_ANALYSIS=trueBRAVE_SEARCH_API_KEY=WEB_RESEARCH_PER_SCAN_LIMIT=2WEB_RESEARCH_MONTHLY_LIMIT=150ENABLE_LOCAL_AI_MODELS=trueAI_IMAGE_DETECTOR_MODELS=dima806/deepfake_vs_real_image_detectionLOCAL_REASONING_BASE_URL=```Notes:- `BRAVE_SEARCH_API_KEY` is optional. When present, TruthShield uses free-capped Brave Web/Image Search requests for source leads and citations. When absent or quota-limited, analysis stays local.- Local Hugging Face detectors are optional and free, but require `transformers` and `torch` in the backend environment and may download model files. If they are unavailable, TruthShield uses a deterministic synthetic-likelihood fallback.- C2PA provenance checks use `c2pa-python` or `c2patool` if available. Missing content credentials are treated as a risk signal, not proof that media is fake.- Free web research is indexed web/image search from generated queries. It is not an unlimited exact reverse image search across the entire internet.## Run The FrontendOpen a second terminal:16 unmodified linesVITE_API_BASE_URL=http://localhost:8000```## DeploymentDeployment notes for Cloudflare Pages and Hugging Face Spaces are in [DEPLOYMENT.md](./DEPLOYMENT.md).## API Endpoints### GET `/api/health`23 unmodified lines- `recommendations`- `evidence`- `technical_details`- `analysis_mode`- `confidence`- `detectors`- `provenance`- `web_research`- `citations`- `custom_feedback`- `disclaimer`### POST `/api/analyze/video`45 unmodified lines- Entropy- Blur / over-smoothing estimate- Compression and texture consistency- Local synthetic-image detector signals- Optional C2PA content credentials check- Optional free-capped indexed web/image research- Sampled video frame scoresText checks include:1 unmodified line- Source or link indicators- Balanced wording- Dates, locations, or verifiable details- Optional free-capped indexed web research for extracted claims- All-caps ratio- Urgency and fear language- Conspiracy-style phrases
1234567venv/.venv/__pycache__/*.py[cod].env.git/.gitignore123456789101112131415161718FRONTEND_ORIGINS=https://truthshield-ai-frontend.pages.dev
# Enhanced verification is free-only and falls back safely when optional tools are absent.ENABLE_ENHANCED_ANALYSIS=true
# Optional free Brave Search key. Leave blank for local-only reports.BRAVE_SEARCH_API_KEY=WEB_RESEARCH_PER_SCAN_LIMIT=2WEB_RESEARCH_MONTHLY_LIMIT=150
# Optional local Hugging Face image classifiers. These may require installing# transformers and torch in the backend environment and may download model files.ENABLE_LOCAL_AI_MODELS=trueAI_IMAGE_DETECTOR_MODELS=dima806/deepfake_vs_real_image_detection
# Optional local Ollama/OpenAI-compatible endpoint for rewriting feedback.# Deterministic feedback is used when this is blank or unreachable.LOCAL_REASONING_BASE_URL=12345678910111213141516171819FROM python:3.11-slim
ENV PYTHONDONTWRITEBYTECODE=1ENV PYTHONUNBUFFERED=1
WORKDIR /app
RUN apt-get update \ && apt-get install -y --no-install-recommends libgl1 libglib2.0-0 \ && rm -rf /var/lib/apt/lists/*
COPY requirements.txt .RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 7860
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]1234567891011121314151617181920212223242526272829303132333435363738394041424344---title: TruthShield AI Backendsdk: dockerapp_port: 7860pinned: falselicense: mit---
# TruthShield AI Backend
FastAPI backend for TruthShield AI.
## Endpoints
- `GET /api/health`- `POST /api/analyze/image`- `POST /api/analyze/video`- `POST /api/analyze/text`
## Environment Variables
Set `FRONTEND_ORIGINS` to the comma-separated list of deployed frontend origins that may call this API.
Example:
```textFRONTEND_ORIGINS=https://truthshield-ai-frontend.pages.dev,https://www.example.com```
Cloudflare Pages preview and production domains ending in `.pages.dev` are allowed by default through `FRONTEND_ORIGIN_REGEX`.
Enhanced verification stays free-only and is controlled with:
```textENABLE_ENHANCED_ANALYSIS=trueBRAVE_SEARCH_API_KEY=WEB_RESEARCH_PER_SCAN_LIMIT=2WEB_RESEARCH_MONTHLY_LIMIT=150ENABLE_LOCAL_AI_MODELS=trueAI_IMAGE_DETECTOR_MODELS=dima806/deepfake_vs_real_image_detectionLOCAL_REASONING_BASE_URL=```
`BRAVE_SEARCH_API_KEY`, Hugging Face model dependencies, C2PA tooling, and a local reasoning endpoint are optional. The API still returns a valid report when any of them are absent.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197from __future__ import annotations
import functoolsfrom typing import Any, Dict, List
from PIL import Image
from analyzers.config import get_settings
SYNTHETIC_LABEL_MARKERS = ("fake", "ai", "generated", "synthetic", "deepfake", "sdxl", "diffusion")REAL_LABEL_MARKERS = ("real", "authentic", "natural", "camera", "human")FILENAME_SYNTHETIC_MARKERS = ("chatgpt", "dall", "dalle", "midjourney", "stable-diffusion", "sdxl", "generated", "ai")
def run_image_detectors( image: Image.Image, filename: str, metadata_present: bool, technical_details: Dict[str, Any],) -> List[Dict[str, Any]]: settings = get_settings() results = [ _heuristic_synthetic_detector( filename=filename, metadata_present=metadata_present, technical_details=technical_details, ) ] if not settings.enable_local_ai_models: results.append( { "name": "huggingface_image_detector", "status": "skipped", "label": None, "score": None, "synthetic_probability": None, "details": {"reason": "ENABLE_LOCAL_AI_MODELS is false."}, } ) return results
for model_id in settings.ai_image_detector_models: results.append(_run_huggingface_detector(image, model_id)) return results
def highest_synthetic_probability(detectors: List[Dict[str, Any]]) -> float | None: probabilities = [ float(detector["synthetic_probability"]) for detector in detectors if isinstance(detector.get("synthetic_probability"), (int, float)) ] if not probabilities: return None return max(0.0, min(1.0, max(probabilities)))
def completed_model_count(detectors: List[Dict[str, Any]]) -> int: return sum( 1 for detector in detectors if detector.get("status") == "completed" and detector.get("name") != "local_heuristic_synthetic_likelihood" )
def _heuristic_synthetic_detector(filename: str, metadata_present: bool, technical_details: Dict[str, Any]) -> Dict[str, Any]: probability = 0.18 reasons: List[str] = [] lowered_filename = filename.lower() if any(marker in lowered_filename for marker in FILENAME_SYNTHETIC_MARKERS): probability += 0.40 reasons.append("The filename contains wording commonly used by AI generation tools.") if not metadata_present: probability += 0.12 reasons.append("No readable camera metadata was found.") detected_format = str(technical_details.get("detected_format") or "").upper() if detected_format in {"PNG", "WEBP"} and not metadata_present: probability += 0.08 reasons.append("The file format and metadata pattern are common for generated or exported images.") entropy = _float_detail(technical_details, "entropy") if entropy is not None and (entropy < 3.5 or entropy > 7.8): probability += 0.10 reasons.append("Image entropy is outside the typical range.") blur = _float_detail(technical_details, "blur_laplacian_variance") if blur is not None and blur < 35: probability += 0.12 reasons.append("The image has possible over-smoothing or heavy blur.") compression = technical_details.get("compression_consistency") if isinstance(compression, dict) and compression.get("is_inconsistent"): probability += 0.08 reasons.append("Compression or texture consistency is uneven.") if not reasons: reasons.append("No strong local synthetic markers were found.")
probability = max(0.02, min(0.98, probability)) label = "likely_ai_generated" if probability >= 0.65 else "uncertain" if probability >= 0.35 else "likely_camera_or_natural" return { "name": "local_heuristic_synthetic_likelihood", "status": "completed", "label": label, "score": round(probability, 3), "synthetic_probability": round(probability, 3), "details": {"reasons": reasons, "model_type": "deterministic_free_fallback"}, }
def _run_huggingface_detector(image: Image.Image, model_id: str) -> Dict[str, Any]: try: classifier = _load_pipeline(model_id) outputs = classifier(image.convert("RGB")) except ImportError: return { "name": model_id, "status": "unavailable", "label": None, "score": None, "synthetic_probability": None, "details": {"reason": "Install transformers and torch to enable this free local model."}, } except Exception as exc: return { "name": model_id, "status": "error", "label": None, "score": None, "synthetic_probability": None, "details": {"reason": str(exc)[:300]}, }
normalized = _normalize_outputs(outputs) synthetic_probability = _synthetic_probability(normalized) top = normalized[0] if normalized else {"label": "unknown", "score": 0.0} return { "name": model_id, "status": "completed", "label": str(top["label"]), "score": round(float(top["score"]), 4), "synthetic_probability": round(synthetic_probability, 4), "details": { "model_provider": "huggingface_local", "top_labels": normalized[:5], "note": "Model output is an evidence signal, not proof of authenticity or manipulation.", }, }
@functools.lru_cache(maxsize=4)def _load_pipeline(model_id: str) -> Any: try: from transformers import pipeline # type: ignore except Exception as exc: raise ImportError("transformers is not installed") from exc return pipeline("image-classification", model=model_id)
def _normalize_outputs(outputs: Any) -> List[Dict[str, Any]]: if isinstance(outputs, dict): outputs = [outputs] if not isinstance(outputs, list): return [] normalized = [] for item in outputs: if not isinstance(item, dict): continue normalized.append( { "label": str(item.get("label", "unknown")), "score": float(item.get("score") or 0.0), } ) return sorted(normalized, key=lambda item: item["score"], reverse=True)
def _synthetic_probability(outputs: List[Dict[str, Any]]) -> float: synthetic = 0.0 real = 0.0 unknown = 0.0 for item in outputs: label = item["label"].lower() score = float(item["score"]) if any(marker in label for marker in SYNTHETIC_LABEL_MARKERS): synthetic += score elif any(marker in label for marker in REAL_LABEL_MARKERS): real += score else: unknown += score if synthetic == 0.0 and real == 0.0: return 0.5 if unknown > 0 else 0.0 return max(0.0, min(1.0, synthetic / max(1e-6, synthetic + real)))
def _float_detail(details: Dict[str, Any], key: str) -> float | None: value = details.get(key) if isinstance(value, (int, float)): return float(value) return None12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061from __future__ import annotations
import osimport tempfilefrom dataclasses import dataclassfrom pathlib import Path
def _env_bool(name: str, default: bool) -> bool: value = os.getenv(name) if value is None: return default return value.strip().lower() in {"1", "true", "yes", "on"}
def _env_int(name: str, default: int, minimum: int = 0) -> int: value = os.getenv(name) if value is None: return default try: return max(minimum, int(value)) except ValueError: return default
def _env_list(name: str, default: str) -> list[str]: raw = os.getenv(name, default) return [item.strip() for item in raw.split(",") if item.strip()]
@dataclass(frozen=True)class EnhancedSettings: enable_enhanced_analysis: bool brave_search_api_key: str | None web_research_per_scan_limit: int web_research_monthly_limit: int enable_local_ai_models: bool local_reasoning_base_url: str | None ai_image_detector_models: list[str] monthly_counter_path: Path
def get_settings() -> EnhancedSettings: return EnhancedSettings( enable_enhanced_analysis=_env_bool("ENABLE_ENHANCED_ANALYSIS", True), brave_search_api_key=os.getenv("BRAVE_SEARCH_API_KEY") or None, web_research_per_scan_limit=_env_int("WEB_RESEARCH_PER_SCAN_LIMIT", 2, minimum=0), web_research_monthly_limit=_env_int("WEB_RESEARCH_MONTHLY_LIMIT", 150, minimum=0), enable_local_ai_models=_env_bool("ENABLE_LOCAL_AI_MODELS", True), local_reasoning_base_url=(os.getenv("LOCAL_REASONING_BASE_URL") or "").rstrip("/") or None, ai_image_detector_models=_env_list( "AI_IMAGE_DETECTOR_MODELS", "dima806/deepfake_vs_real_image_detection", ), monthly_counter_path=Path( os.getenv( "WEB_RESEARCH_COUNTER_PATH", str(Path(tempfile.gettempdir()) / "truthshield_web_research_counter.json"), ) ), )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303from __future__ import annotations
from typing import Any, Dict, List
from PIL import Image
from analyzers.ai_detectors import completed_model_count, highest_synthetic_probability, run_image_detectorsfrom analyzers.config import get_settingsfrom analyzers.feedback import build_custom_feedbackfrom analyzers.provenance import verify_image_provenancefrom analyzers.scoring import clamp_score, get_risk_level, summarize_result, unique_messagesfrom analyzers.web_research import research_image_context, research_text_claims, research_video_context
def enhance_image_result( result: Dict[str, Any], image: Image.Image, filename: str, content_bytes: bytes | None, content_label: str,) -> Dict[str, Any]: settings = get_settings() if not settings.enable_enhanced_analysis: return _with_local_mode(result)
technical = result.get("technical_details", {}) metadata_present = bool(technical.get("metadata_fields_found")) detectors = run_image_detectors(image, filename, metadata_present, technical) provenance = verify_image_provenance(content_bytes, filename) if content_bytes else None web_research = research_image_context(filename) if content_bytes else None
evidence = dict(result.get("evidence", {})) detector_probability = highest_synthetic_probability(detectors) detector_truth = 50.0 if detector_probability is None else 100.0 - detector_probability * 100.0 provenance_score = float(provenance["score"]) if provenance else 50.0 web_score = float(web_research["score"]) if web_research else 50.0 recalibrated_score = _weighted_score( { "metadata": evidence.get("metadata_score", 50.0), "visual": evidence.get("visual_consistency_score", result.get("truth_score", 50.0)), "compression": evidence.get("compression_score", 50.0), "detector": detector_truth, "provenance": provenance_score, "web": web_score, }, { "metadata": 0.08, "visual": 0.12, "compression": 0.08, "detector": 0.42, "provenance": 0.15, "web": 0.15, }, )
warnings = list(result.get("warnings", [])) positives = list(result.get("positive_signals", [])) if detector_probability is not None and detector_probability >= 0.70: warnings.append("AI detector signals indicate a high likelihood of synthetic or generated imagery.") elif detector_probability is not None and detector_probability <= 0.30: positives.append("AI detector signals did not strongly indicate generated imagery.") if provenance and provenance["status"] in {"no_manifest", "tool_unavailable"}: warnings.append("No verifiable C2PA content credentials were found for this file.") elif provenance and provenance["status"] == "verified": positives.append("Verifiable C2PA content credentials were found.") if web_research and web_research["status"] == "no_results": warnings.append("Automated indexed web research did not find corroborating source leads.") elif web_research and web_research["matches_found"] > 0: positives.append("Automated indexed web research found possible source or context leads.")
final_score = clamp_score(recalibrated_score) risk_level, verdict = get_risk_level(final_score) evidence.update( { "ai_generation_score": round(100.0 - detector_truth, 2), "provenance_score": round(provenance_score, 2), "web_corroboration_score": round(web_score, 2), "overall_risk_score": float(100 - final_score), } ) result.update( { "truth_score": final_score, "risk_level": risk_level, "verdict": verdict, "summary": summarize_result(content_label, final_score, warnings, positives), "warnings": unique_messages(warnings), "positive_signals": unique_messages(positives), "evidence": evidence, "analysis_mode": _analysis_mode(web_research), "confidence": _confidence(detectors, provenance, web_research), "detectors": detectors, "provenance": provenance, "web_research": web_research, "citations": (web_research or {}).get("citations", []), } ) result["custom_feedback"] = build_custom_feedback( content_label, final_score, result["warnings"], result["positive_signals"], detectors, provenance, web_research, ) return result
def enhance_text_result(result: Dict[str, Any], text: str) -> Dict[str, Any]: settings = get_settings() if not settings.enable_enhanced_analysis: return _with_local_mode(result)
web_research = research_text_claims(text) warnings = list(result.get("warnings", [])) positives = list(result.get("positive_signals", [])) base_score = float(result.get("truth_score", 50)) web_score = float(web_research["score"]) if web_research["matches_found"] > 0: positives.append("Automated indexed web research found possible corroborating context.") elif web_research["status"] == "no_results": warnings.append("Automated indexed web research did not find corroborating results for the extracted claim.")
if web_research["status"] in {"completed", "no_results"}: final_score = clamp_score(base_score * 0.62 + web_score * 0.38) else: final_score = clamp_score(base_score) risk_level, verdict = get_risk_level(final_score) evidence = dict(result.get("evidence", {})) evidence.update({"web_corroboration_score": round(web_score, 2), "overall_risk_score": float(100 - final_score)}) result.update( { "truth_score": final_score, "risk_level": risk_level, "verdict": verdict, "summary": summarize_result("text post", final_score, warnings, positives), "warnings": unique_messages(warnings), "positive_signals": unique_messages(positives), "evidence": evidence, "analysis_mode": _analysis_mode(web_research), "confidence": _confidence([], None, web_research), "detectors": [], "provenance": None, "web_research": web_research, "citations": web_research.get("citations", []), } ) result["custom_feedback"] = build_custom_feedback( "text post", final_score, result["warnings"], result["positive_signals"], [], None, web_research, ) return result
def enhance_video_result(result: Dict[str, Any], frame_results: List[Dict[str, Any]], filename: str) -> Dict[str, Any]: settings = get_settings() if not settings.enable_enhanced_analysis: return _with_local_mode(result)
frame_probabilities = [ highest_synthetic_probability(frame.get("detectors", [])) for frame in frame_results if frame.get("detectors") ] frame_probabilities = [probability for probability in frame_probabilities if probability is not None] detector_probability = max(frame_probabilities) if frame_probabilities else None detectors = [ { "name": "sampled_frame_ai_detector_summary", "status": "completed" if detector_probability is not None else "unavailable", "label": _probability_label(detector_probability), "score": detector_probability, "synthetic_probability": detector_probability, "details": { "frames_with_detector_signals": len(frame_probabilities), "note": "Video evidence is aggregated from sampled frames.", }, } ] frame_notes = [ warning for frame in frame_results[:3] for warning in frame.get("warnings", [])[:2] ] web_research = research_video_context(filename, frame_notes) base_score = float(result.get("truth_score", 50)) detector_truth = 50.0 if detector_probability is None else 100.0 - detector_probability * 100.0 web_score = float(web_research["score"]) final_score = clamp_score(base_score * 0.58 + detector_truth * 0.28 + web_score * 0.14) warnings = list(result.get("warnings", [])) positives = list(result.get("positive_signals", [])) if detector_probability is not None and detector_probability >= 0.70: warnings.append("One or more sampled frames had high synthetic-image detector signals.") if web_research["matches_found"] > 0: positives.append("Automated indexed web research found possible video context leads.") elif web_research["status"] == "no_results": warnings.append("Automated indexed web research did not find corroborating context for this video.")
risk_level, verdict = get_risk_level(final_score) evidence = dict(result.get("evidence", {})) evidence.update( { "sampled_frame_ai_generation_score": round(100.0 - detector_truth, 2), "web_corroboration_score": round(web_score, 2), "overall_risk_score": float(100 - final_score), } ) result.update( { "truth_score": final_score, "risk_level": risk_level, "verdict": verdict, "summary": summarize_result("video", final_score, warnings, positives), "warnings": unique_messages(warnings), "positive_signals": unique_messages(positives), "evidence": evidence, "analysis_mode": _analysis_mode(web_research), "confidence": _confidence(detectors, None, web_research), "detectors": detectors, "provenance": None, "web_research": web_research, "citations": web_research.get("citations", []), } ) result["custom_feedback"] = build_custom_feedback( "video", final_score, result["warnings"], result["positive_signals"], detectors, None, web_research, ) return result
def _with_local_mode(result: Dict[str, Any]) -> Dict[str, Any]: result.setdefault("analysis_mode", "local_heuristic") result.setdefault("confidence", 0.55) result.setdefault("detectors", []) result.setdefault("provenance", None) result.setdefault("web_research", None) result.setdefault("citations", []) result.setdefault( "custom_feedback", { "headline": "Local heuristic analysis only", "explanation": "Enhanced analysis is disabled, so this report uses local heuristic signals only.", "evidence_notes": result.get("warnings", [])[:3], "next_steps": result.get("recommendations", [])[:3], }, ) return result
def _weighted_score(values: Dict[str, float], weights: Dict[str, float]) -> float: total = 0.0 weight_total = 0.0 for key, weight in weights.items(): total += max(0.0, min(100.0, float(values.get(key, 50.0)))) * weight weight_total += weight if weight_total <= 0: return 50.0 return total / weight_total
def _analysis_mode(web_research: Dict[str, Any] | None) -> str: if web_research and web_research.get("status") in {"completed", "no_results", "error"}: return "enhanced_free_hybrid" return "enhanced_free_local"
def _confidence( detectors: List[Dict[str, Any]], provenance: Dict[str, Any] | None, web_research: Dict[str, Any] | None,) -> float: confidence = 0.45 if completed_model_count(detectors) > 0: confidence += 0.18 elif any(detector.get("status") == "completed" for detector in detectors): confidence += 0.08 if provenance and provenance.get("status") in {"verified", "no_manifest"}: confidence += 0.10 if web_research and web_research.get("status") in {"completed", "no_results"}: confidence += 0.15 return round(max(0.2, min(0.9, confidence)), 2)
def _probability_label(probability: float | None) -> str | None: if probability is None: return None if probability >= 0.65: return "sampled_frames_likely_synthetic" if probability <= 0.30: return "sampled_frames_lower_synthetic_signal" return "sampled_frames_uncertain"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137from __future__ import annotations
import jsonimport urllib.requestfrom typing import Any, Dict, List
from analyzers.config import get_settings
def build_custom_feedback( content_label: str, score: int, warnings: List[str], positives: List[str], detectors: List[Dict[str, Any]], provenance: Dict[str, Any] | None, web_research: Dict[str, Any] | None,) -> Dict[str, Any]: deterministic = _deterministic_feedback( content_label=content_label, score=score, warnings=warnings, positives=positives, detectors=detectors, provenance=provenance, web_research=web_research, ) local_feedback = _try_local_reasoning_feedback(deterministic, content_label) return local_feedback or deterministic
def _deterministic_feedback( content_label: str, score: int, warnings: List[str], positives: List[str], detectors: List[Dict[str, Any]], provenance: Dict[str, Any] | None, web_research: Dict[str, Any] | None,) -> Dict[str, Any]: detector_note = _detector_note(detectors) provenance_note = provenance["summary"] if provenance else "No provenance check was available." web_note = web_research["summary"] if web_research else "No web research was available." if score < 40: headline = f"High-risk {content_label} signals found" elif score < 60: headline = f"Several {content_label} signals need verification" elif score < 80: headline = f"Mixed {content_label} evidence" else: headline = f"Mostly reassuring {content_label} signals"
strongest_risks = warnings[:3] or ["No major warning signal was isolated by the current checks."] strongest_positive = positives[:2] or ["No strong positive authenticity signal was available."] explanation = ( f"The score is based on detector signals, provenance checks, indexed web research, and local forensic checks. " f"{detector_note} {provenance_note} {web_note}" ) next_steps = [ "Open the cited sources or run a manual reverse image search if the claim matters.", "Look for the earliest uploader, official source, or original context before sharing.", ] if web_research and web_research.get("status") == "not_configured": next_steps.insert(0, "Add a free Brave Search API key to enable automated indexed web research.") return { "headline": headline, "explanation": explanation, "evidence_notes": [*strongest_risks, *strongest_positive], "next_steps": next_steps[:4], }
def _detector_note(detectors: List[Dict[str, Any]]) -> str: probabilities = [ float(detector["synthetic_probability"]) for detector in detectors if isinstance(detector.get("synthetic_probability"), (int, float)) ] if not probabilities: return "No AI detector probability was available." probability = max(probabilities) if probability >= 0.75: return f"The strongest AI detector signal estimates about {probability:.0%} synthetic likelihood." if probability >= 0.45: return f"The strongest AI detector signal is uncertain at about {probability:.0%} synthetic likelihood." return f"The strongest AI detector signal estimates about {probability:.0%} synthetic likelihood."
def _try_local_reasoning_feedback(base_feedback: Dict[str, Any], content_label: str) -> Dict[str, Any] | None: settings = get_settings() if not settings.local_reasoning_base_url: return None endpoint = f"{settings.local_reasoning_base_url}/v1/chat/completions" payload = { "model": "local-model", "messages": [ { "role": "system", "content": ( "You write concise media verification feedback. Use only the provided evidence. " "Do not claim certainty. Return JSON with headline, explanation, evidence_notes, next_steps." ), }, { "role": "user", "content": json.dumps({"content_label": content_label, "base_feedback": base_feedback}), }, ], "temperature": 0.2, } try: request = urllib.request.Request( endpoint, data=json.dumps(payload).encode("utf-8"), headers={"Content-Type": "application/json"}, method="POST", ) with urllib.request.urlopen(request, timeout=8) as response: parsed = json.loads(response.read().decode("utf-8", errors="replace")) content = parsed["choices"][0]["message"]["content"] generated = json.loads(content) if isinstance(generated, dict) and "headline" in generated and "explanation" in generated: return { "headline": str(generated.get("headline") or base_feedback["headline"])[:160], "explanation": str(generated.get("explanation") or base_feedback["explanation"])[:900], "evidence_notes": _string_list(generated.get("evidence_notes"))[:5] or base_feedback["evidence_notes"], "next_steps": _string_list(generated.get("next_steps"))[:4] or base_feedback["next_steps"], } except Exception: return None return None
def _string_list(value: Any) -> List[str]: if not isinstance(value, list): return [] return [str(item) for item in value if str(item).strip()]8 unmodified lines91011121314141 unmodified lines1561571581591601611626 unmodified lines1691701711721731748 unmodified linesimport numpy as npfrom PIL import Image, ImageStat, UnidentifiedImageErrorfrom analyzers.metadata import extract_exif_metadata, has_camera_make_or_model, metadata_scorefrom analyzers.scoring import (DISCLAIMER,141 unmodified linesif content_bytes is not None:technical_details["file_size_bytes"] = len(content_bytes)return {"content_type": "image" if content_label == "image" else "video_frame","truth_score": final_score,"risk_level": risk_level,6 unmodified lines"technical_details": technical_details,"disclaimer": DISCLAIMER,}def _has_reasonable_dimensions(width: int, height: int) -> bool:8 unmodified lines9101112131415141 unmodified lines1571581591601611621636 unmodified lines1701711721731741751761771781791801811828 unmodified linesimport numpy as npfrom PIL import Image, ImageStat, UnidentifiedImageErrorfrom analyzers.enhanced import enhance_image_resultfrom analyzers.metadata import extract_exif_metadata, has_camera_make_or_model, metadata_scorefrom analyzers.scoring import (DISCLAIMER,141 unmodified linesif content_bytes is not None:technical_details["file_size_bytes"] = len(content_bytes)result = {"content_type": "image" if content_label == "image" else "video_frame","truth_score": final_score,"risk_level": risk_level,6 unmodified lines"technical_details": technical_details,"disclaimer": DISCLAIMER,}return enhance_image_result(result=result,image=image,filename=filename,content_bytes=content_bytes,content_label=content_label,)def _has_reasonable_dimensions(width: int, height: int) -> bool:
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147from __future__ import annotations
import jsonimport shutilimport subprocessimport tempfilefrom pathlib import Pathfrom typing import Any, Dict
def verify_image_provenance(data: bytes | None, filename: str) -> Dict[str, Any]: if not data: return { "status": "unavailable", "score": 50.0, "summary": "No original file bytes were available for content credential checks.", "details": {}, }
c2pa_result = _try_c2pa_python(data) if c2pa_result is not None: return c2pa_result
tool_path = shutil.which("c2patool") if not tool_path: return { "status": "tool_unavailable", "score": 45.0, "summary": "No C2PA verifier is installed, so content credentials could not be checked.", "details": {"checked_with": "c2pa-python or c2patool", "filename": filename}, }
suffix = Path(filename).suffix or ".image" temp_path = "" try: with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as temp_file: temp_file.write(data) temp_path = temp_file.name
completed = subprocess.run( [tool_path, temp_path, "--json"], check=False, capture_output=True, text=True, timeout=12, ) output = completed.stdout.strip() parsed = _safe_json_loads(output) if completed.returncode == 0 and parsed: manifest_count = _count_manifest_like_items(parsed) if manifest_count > 0: return { "status": "verified", "score": 88.0, "summary": "C2PA content credentials were found and parsed.", "details": { "checked_with": "c2patool", "manifest_count": manifest_count, "metadata_keys": sorted(parsed.keys())[:12] if isinstance(parsed, dict) else [], }, } return { "status": "no_manifest", "score": 42.0, "summary": "The file was checked, but no C2PA content credentials were found.", "details": {"checked_with": "c2patool"}, } return { "status": "no_manifest", "score": 42.0, "summary": "The file did not expose verifiable C2PA content credentials.", "details": { "checked_with": "c2patool", "return_code": completed.returncode, "stderr": completed.stderr.strip()[:300], }, } except Exception as exc: return { "status": "error", "score": 45.0, "summary": "The C2PA verification step could not complete safely.", "details": {"error": str(exc)[:300], "checked_with": "c2patool"}, } finally: if temp_path: try: Path(temp_path).unlink(missing_ok=True) except Exception: pass
def _try_c2pa_python(data: bytes) -> Dict[str, Any] | None: try: import c2pa # type: ignore except Exception: return None
try: reader = getattr(c2pa, "Reader", None) if reader is None: return { "status": "tool_unavailable", "score": 45.0, "summary": "The c2pa-python package is present, but its reader API was not available.", "details": {"checked_with": "c2pa-python"}, } result = reader.from_bytes(data) if hasattr(reader, "from_bytes") else None manifest = getattr(result, "manifest_store", None) or getattr(result, "manifest", None) if manifest: return { "status": "verified", "score": 88.0, "summary": "C2PA content credentials were found and parsed.", "details": {"checked_with": "c2pa-python"}, } return { "status": "no_manifest", "score": 42.0, "summary": "The file was checked, but no C2PA content credentials were found.", "details": {"checked_with": "c2pa-python"}, } except Exception: return None
def _safe_json_loads(raw: str) -> Any: if not raw: return None try: return json.loads(raw) except json.JSONDecodeError: return None
def _count_manifest_like_items(value: Any) -> int: if isinstance(value, dict): count = 0 for key, nested in value.items(): lowered = str(key).lower() if "manifest" in lowered or "claim" in lowered: count += 1 count += _count_manifest_like_items(nested) return count if isinstance(value, list): return sum(_count_manifest_like_items(item) for item in value) return 02 unmodified lines345678151 unmodified lines16016116216316416516612 unmodified lines1791801811821831842 unmodified linesimport refrom typing import Any, Dict, Listfrom analyzers.scoring import (DISCLAIMER,TEXT_RECOMMENDATIONS,151 unmodified lines"heuristic_note": "Text scoring uses explainable language heuristics and does not prove whether a claim is true or false.",}return {"content_type": "text","truth_score": final_score,"risk_level": risk_level,12 unmodified lines"technical_details": technical_details,"disclaimer": DISCLAIMER,}def _matches_any(text: str, patterns: List[str]) -> bool:2 unmodified lines3456789151 unmodified lines16116216316416516616712 unmodified lines1801811821831841851862 unmodified linesimport refrom typing import Any, Dict, Listfrom analyzers.enhanced import enhance_text_resultfrom analyzers.scoring import (DISCLAIMER,TEXT_RECOMMENDATIONS,151 unmodified lines"heuristic_note": "Text scoring uses explainable language heuristics and does not prove whether a claim is true or false.",}result = {"content_type": "text","truth_score": final_score,"risk_level": risk_level,12 unmodified lines"technical_details": technical_details,"disclaimer": DISCLAIMER,}return enhance_text_result(result, cleaned)def _matches_any(text: str, patterns: List[str]) -> bool:
4 unmodified lines567891076 unmodified lines8788899091929330 unmodified lines1241251261271281294 unmodified linesimport cv2import numpy as npfrom analyzers.image_analyzer import analyze_frame_arrayfrom analyzers.scoring import (DISCLAIMER,76 unmodified linesavg_visual_score = float(np.mean([result["evidence"]["visual_consistency_score"] for result in frame_results]))metadata_score = 82.0 if frame_count > 0 and fps > 0 and width > 0 and height > 0 else 35.0return {"content_type": "video","truth_score": final_score,"risk_level": risk_level,30 unmodified lines},"disclaimer": DISCLAIMER,}finally:capture.release()4 unmodified lines56789101176 unmodified lines8889909192939430 unmodified lines1251261271281291301314 unmodified linesimport cv2import numpy as npfrom analyzers.enhanced import enhance_video_resultfrom analyzers.image_analyzer import analyze_frame_arrayfrom analyzers.scoring import (DISCLAIMER,76 unmodified linesavg_visual_score = float(np.mean([result["evidence"]["visual_consistency_score"] for result in frame_results]))metadata_score = 82.0 if frame_count > 0 and fps > 0 and width > 0 and height > 0 else 35.0result = {"content_type": "video","truth_score": final_score,"risk_level": risk_level,30 unmodified lines},"disclaimer": DISCLAIMER,}return enhance_video_result(result, frame_results, filename)finally:capture.release()
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266from __future__ import annotations
import jsonimport reimport timeimport urllib.errorimport urllib.parseimport urllib.requestfrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any, Dict, Iterable, List
from analyzers.config import EnhancedSettings, get_settings
BRAVE_WEB_ENDPOINT = "https://api.search.brave.com/res/v1/web/search"BRAVE_IMAGE_ENDPOINT = "https://api.search.brave.com/res/v1/images/search"
def research_image_context(filename: str, visible_text: str = "") -> Dict[str, Any]: settings = get_settings() queries = _image_queries(filename, visible_text, settings.web_research_per_scan_limit) return _run_research(queries, settings, search_kind="image")
def research_text_claims(text: str) -> Dict[str, Any]: settings = get_settings() queries = _text_queries(text, settings.web_research_per_scan_limit) return _run_research(queries, settings, search_kind="web")
def research_video_context(filename: str, frame_notes: Iterable[str]) -> Dict[str, Any]: settings = get_settings() joined_notes = " ".join(note for note in frame_notes if note) queries = _image_queries(filename, joined_notes, settings.web_research_per_scan_limit) return _run_research(queries, settings, search_kind="web")
def _run_research(queries: List[str], settings: EnhancedSettings, search_kind: str) -> Dict[str, Any]: if not settings.brave_search_api_key: return { "status": "not_configured", "provider": "brave_search", "score": 50.0, "queries": queries, "matches_found": 0, "summary": "Web research was skipped because BRAVE_SEARCH_API_KEY is not configured.", "citations": [], "details": {"free_provider": True, "search_kind": search_kind}, } if settings.web_research_per_scan_limit <= 0: return { "status": "quota_disabled", "provider": "brave_search", "score": 50.0, "queries": queries, "matches_found": 0, "summary": "Web research is disabled by the per-scan request limit.", "citations": [], "details": {"search_kind": search_kind}, } if not queries: return { "status": "no_query", "provider": "brave_search", "score": 48.0, "queries": [], "matches_found": 0, "summary": "There was not enough searchable context to run automated web research.", "citations": [], "details": {"search_kind": search_kind}, }
quota = _QuotaCounter(settings.monthly_counter_path, settings.web_research_monthly_limit) citations: List[Dict[str, Any]] = [] errors: List[str] = [] consumed = 0
for query in queries[: settings.web_research_per_scan_limit]: if not quota.can_consume(): return { "status": "quota_exceeded", "provider": "brave_search", "score": 50.0, "queries": queries[:consumed], "matches_found": len(citations), "summary": "The free monthly web research limit has been reached.", "citations": citations, "details": {"monthly_limit": settings.web_research_monthly_limit, "errors": errors}, } quota.consume() consumed += 1 endpoint = BRAVE_IMAGE_ENDPOINT if search_kind == "image" else BRAVE_WEB_ENDPOINT response = _brave_get(endpoint, settings.brave_search_api_key, query) if response["status"] != "ok": errors.append(response["error"]) continue citations.extend(_extract_citations(response["data"], search_kind))
citations = _dedupe_citations(citations)[:5] if citations: return { "status": "completed", "provider": "brave_search", "score": 68.0, "queries": queries[:consumed], "matches_found": len(citations), "summary": "Free indexed web/image search found possible context or source leads.", "citations": citations, "details": {"free_provider": True, "errors": errors, "search_kind": search_kind}, } if errors: return { "status": "error", "provider": "brave_search", "score": 50.0, "queries": queries[:consumed], "matches_found": 0, "summary": "Web research could not complete successfully.", "citations": [], "details": {"errors": errors[:3], "search_kind": search_kind}, } return { "status": "no_results", "provider": "brave_search", "score": 38.0, "queries": queries[:consumed], "matches_found": 0, "summary": "No corroborating indexed web results were found from the generated search queries.", "citations": [], "details": {"search_kind": search_kind}, }
def _brave_get(endpoint: str, api_key: str, query: str) -> Dict[str, Any]: params = urllib.parse.urlencode({"q": query, "count": 5, "safesearch": "moderate"}) request = urllib.request.Request( f"{endpoint}?{params}", headers={ "Accept": "application/json", "X-Subscription-Token": api_key, "User-Agent": "TruthShieldAI/1.0", }, ) try: with urllib.request.urlopen(request, timeout=8) as response: payload = response.read().decode("utf-8", errors="replace") return {"status": "ok", "data": json.loads(payload)} except urllib.error.HTTPError as exc: return {"status": "error", "error": f"Brave Search returned HTTP {exc.code}."} except Exception as exc: return {"status": "error", "error": str(exc)[:220]}
def _extract_citations(data: Dict[str, Any], search_kind: str) -> List[Dict[str, Any]]: if search_kind == "image": results = data.get("results") or [] else: results = (data.get("web") or {}).get("results") or [] citations: List[Dict[str, Any]] = [] for item in results: url = item.get("url") or item.get("properties", {}).get("url") title = item.get("title") or item.get("page_title") or "Search result" if not url: continue citations.append( { "title": _clean_text(str(title))[:140] or "Search result", "url": str(url), "source": _domain(str(url)), "snippet": _clean_text(str(item.get("description") or item.get("page_fetched") or ""))[:260] or None, } ) return citations
def _image_queries(filename: str, visible_text: str, limit: int) -> List[str]: tokens = _meaningful_tokens(f"{Path(filename).stem} {visible_text}") if tokens: return [" ".join(tokens[:8])][: max(1, limit)] return ["uploaded image source verification"][: max(1, limit)]
def _text_queries(text: str, limit: int) -> List[str]: sentences = re.split(r"(?<=[.!?])\s+", text.strip()) candidates = [_clean_text(sentence) for sentence in sentences if len(sentence.split()) >= 4] if not candidates: candidates = [_clean_text(text)] return [candidate[:180] for candidate in candidates[: max(1, limit)] if candidate]
def _meaningful_tokens(text: str) -> List[str]: stop_words = { "image", "photo", "picture", "upload", "uploaded", "screenshot", "chatgpt", "generated", "copy", "scan", "truthshield", } words = re.findall(r"[A-Za-z0-9][A-Za-z0-9_-]{2,}", text) result: List[str] = [] for word in words: lowered = word.lower() if lowered in stop_words or lowered in result: continue result.append(lowered) return result
def _clean_text(text: str) -> str: return re.sub(r"\s+", " ", text).strip()
def _domain(url: str) -> str: parsed = urllib.parse.urlparse(url) return parsed.netloc.removeprefix("www.")
def _dedupe_citations(citations: List[Dict[str, Any]]) -> List[Dict[str, Any]]: seen = set() unique: List[Dict[str, Any]] = [] for citation in citations: url = citation.get("url") if not url or url in seen: continue seen.add(url) unique.append(citation) return unique
class _QuotaCounter: def __init__(self, path: Path, monthly_limit: int) -> None: self.path = path self.monthly_limit = monthly_limit self.month_key = datetime.now(timezone.utc).strftime("%Y-%m")
def can_consume(self) -> bool: if self.monthly_limit <= 0: return False data = self._read() return int(data.get(self.month_key, 0)) < self.monthly_limit
def consume(self) -> None: data = self._read() data[self.month_key] = int(data.get(self.month_key, 0)) + 1 try: self.path.parent.mkdir(parents=True, exist_ok=True) self.path.write_text(json.dumps(data), encoding="utf-8") except Exception: pass
def _read(self) -> Dict[str, int]: try: raw = self.path.read_text(encoding="utf-8") parsed = json.loads(raw) if isinstance(parsed, dict): return {str(key): int(value) for key, value in parsed.items()} except Exception: pass return {}1234520 unmodified lines26272829303132333435363738394041from __future__ import annotationsfrom fastapi import FastAPI, File, HTTPException, UploadFilefrom fastapi.middleware.cors import CORSMiddleware20 unmodified linesversion="1.0.0",)app.add_middleware(CORSMiddleware,allow_origins=["http://localhost:5173","http://127.0.0.1:5173","http://localhost:5174","http://127.0.0.1:5174","http://localhost:3000","http://127.0.0.1:3000",],allow_credentials=True,allow_methods=["*"],allow_headers=["*"],123456720 unmodified lines282930313233343536373839404142434445464748495051525354555657from __future__ import annotationsimport osfrom fastapi import FastAPI, File, HTTPException, UploadFilefrom fastapi.middleware.cors import CORSMiddleware20 unmodified linesversion="1.0.0",)LOCAL_FRONTEND_ORIGINS = ["http://localhost:5173","http://127.0.0.1:5173","http://localhost:5174","http://127.0.0.1:5174","http://localhost:3000","http://127.0.0.1:3000",]def get_allowed_origins() -> list[str]:configured_origins = os.getenv("FRONTEND_ORIGINS", "")deployed_origins = [origin.strip().rstrip("/")for origin in configured_origins.split(",")if origin.strip()]return [*LOCAL_FRONTEND_ORIGINS, *deployed_origins]app.add_middleware(CORSMiddleware,allow_origins=get_allowed_origins(),allow_origin_regex=os.getenv("FRONTEND_ORIGIN_REGEX", r"https://.*\.pages\.dev"),allow_credentials=True,allow_methods=["*"],allow_headers=["*"],
16 unmodified lines1718192021226 unmodified lines29303132333416 unmodified lineswarnings: List[str]class AnalysisResponse(BaseModel):content_type: ContentTypetruth_score: int = Field(..., ge=0, le=100)6 unmodified linesevidence: Dict[str, float]technical_details: Dict[str, Any]disclaimer: strclass VideoAnalysisResponse(AnalysisResponse):16 unmodified lines17181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636 unmodified lines7071727374757677787980818216 unmodified lineswarnings: List[str]class DetectorResult(BaseModel):name: strstatus: strlabel: Optional[str] = Nonescore: Optional[float] = Nonesynthetic_probability: Optional[float] = Nonedetails: Dict[str, Any] = Field(default_factory=dict)class ProvenanceResult(BaseModel):status: strscore: float = Field(..., ge=0, le=100)summary: strdetails: Dict[str, Any] = Field(default_factory=dict)class Citation(BaseModel):title: strurl: strsource: Optional[str] = Nonesnippet: Optional[str] = Noneclass WebResearchResult(BaseModel):status: strprovider: strscore: float = Field(..., ge=0, le=100)queries: List[str] = Field(default_factory=list)matches_found: int = 0summary: strcitations: List[Citation] = Field(default_factory=list)details: Dict[str, Any] = Field(default_factory=dict)class CustomFeedback(BaseModel):headline: strexplanation: strevidence_notes: List[str] = Field(default_factory=list)next_steps: List[str] = Field(default_factory=list)class AnalysisResponse(BaseModel):content_type: ContentTypetruth_score: int = Field(..., ge=0, le=100)6 unmodified linesevidence: Dict[str, float]technical_details: Dict[str, Any]disclaimer: stranalysis_mode: str = "local_heuristic"confidence: float = Field(0.55, ge=0, le=1)detectors: List[DetectorResult] = Field(default_factory=list)provenance: Optional[ProvenanceResult] = Noneweb_research: Optional[WebResearchResult] = Nonecitations: List[Citation] = Field(default_factory=list)custom_feedback: Optional[CustomFeedback] = Noneclass VideoAnalysisResponse(AnalysisResponse):
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140from __future__ import annotations
import osimport unittestfrom unittest.mock import patch
import numpy as npfrom PIL import Image
from analyzers.enhanced import enhance_image_result, enhance_video_resultfrom analyzers.image_analyzer import analyze_frame_array, analyze_image_bytesfrom analyzers.provenance import verify_image_provenancefrom analyzers.text_analyzer import analyze_textfrom analyzers.web_research import research_text_claimsfrom models.schemas import AnalysisResponse, VideoAnalysisResponse
class EnhancedAnalysisTests(unittest.TestCase): def test_high_ai_probability_recalibrates_generated_image_lower(self) -> None: image = Image.new("RGB", (900, 600), color=(90, 140, 70)) base_result = { "content_type": "image", "truth_score": 74, "risk_level": "Medium Trust", "verdict": "Needs light verification", "summary": "Baseline heuristic report.", "warnings": ["No readable EXIF metadata was found."], "positive_signals": ["Image dimensions are within a reasonable range."], "recommendations": ["Verify before sharing."], "evidence": { "metadata_score": 35.0, "visual_consistency_score": 98.0, "compression_score": 60.0, "source_score": 50.0, "overall_risk_score": 26.0, }, "technical_details": { "filename": "ChatGPT Image.png", "detected_format": "PNG", "metadata_fields_found": [], "entropy": 6.2, "blur_laplacian_variance": 120.0, "compression_consistency": {"is_inconsistent": False}, }, "disclaimer": "Test disclaimer.", } detectors = [ { "name": "mock_detector", "status": "completed", "label": "fake", "score": 0.94, "synthetic_probability": 0.94, "details": {}, } ] provenance = { "status": "no_manifest", "score": 42.0, "summary": "No C2PA content credentials were found.", "details": {}, } web = { "status": "no_results", "provider": "brave_search", "score": 38.0, "queries": ["world cup free kick"], "matches_found": 0, "summary": "No corroborating indexed web results were found.", "citations": [], "details": {}, }
with patch("analyzers.enhanced.run_image_detectors", return_value=detectors), patch( "analyzers.enhanced.verify_image_provenance", return_value=provenance ), patch("analyzers.enhanced.research_image_context", return_value=web): enhanced = enhance_image_result(base_result, image, "ChatGPT Image.png", b"image-bytes", "image")
self.assertLess(enhanced["truth_score"], 50) self.assertIn("ai_generation_score", enhanced["evidence"]) self.assertTrue(enhanced["custom_feedback"]["headline"]) AnalysisResponse(**enhanced)
def test_web_research_skips_without_brave_key(self) -> None: with patch.dict(os.environ, {"BRAVE_SEARCH_API_KEY": ""}, clear=False): result = research_text_claims("A test claim that should not call the network.") self.assertEqual(result["status"], "not_configured") self.assertEqual(result["provider"], "brave_search") self.assertEqual(result["score"], 50.0)
def test_provenance_fallback_when_tools_absent(self) -> None: with patch("analyzers.provenance._try_c2pa_python", return_value=None), patch( "analyzers.provenance.shutil.which", return_value=None ): result = verify_image_provenance(b"not-really-an-image", "sample.png") self.assertEqual(result["status"], "tool_unavailable") self.assertLess(result["score"], 50)
def test_image_and_text_schema_compatibility(self) -> None: with patch.dict(os.environ, {"ENABLE_LOCAL_AI_MODELS": "false", "BRAVE_SEARCH_API_KEY": ""}, clear=False): image = Image.new("RGB", (512, 512), color=(120, 80, 160)) import io
buffer = io.BytesIO() image.save(buffer, format="PNG") image_result = analyze_image_bytes(buffer.getvalue(), "sample.png") text_result = analyze_text("According to Reuters, a city council vote happened in 2026.")
AnalysisResponse(**image_result) AnalysisResponse(**text_result) self.assertIn("custom_feedback", image_result) self.assertIn("web_research", text_result)
def test_video_frame_and_video_schema_compatibility(self) -> None: with patch.dict(os.environ, {"ENABLE_LOCAL_AI_MODELS": "false", "BRAVE_SEARCH_API_KEY": ""}, clear=False): frame = np.zeros((480, 640, 3), dtype=np.uint8) frame_result = analyze_frame_array(frame, "unit-test-frame") video_result = { "content_type": "video", "truth_score": 62, "risk_level": "Medium Trust", "verdict": "Needs light verification", "summary": "Video baseline.", "warnings": [], "positive_signals": ["Basic video metadata could be read."], "recommendations": ["Verify before sharing."], "evidence": {"frame_analysis_score": 62.0, "overall_risk_score": 38.0}, "frames_analyzed": 1, "suspicious_frames": [], "technical_details": {"filename": "sample.mp4"}, "disclaimer": "Test disclaimer.", } enhanced_video = enhance_video_result(video_result, [frame_result], "sample.mp4")
self.assertEqual(frame_result["content_type"], "video_frame") VideoAnalysisResponse(**enhanced_video)
if __name__ == "__main__": unittest.main()1VITE_API_BASE_URL=https://<hf-user>-truthshield-ai-backend.hf.space1/* /index.html 200123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200import { BadgeCheck, Bot, ExternalLink, FileSearch, Fingerprint, Sparkles } from "lucide-react";import type { AnalysisResult, Citation, DetectorResult } from "../lib/types";
interface EnhancedInsightsProps { result: AnalysisResult;}
function percent(value?: number | null): string { if (typeof value !== "number" || Number.isNaN(value)) return "n/a"; return `${Math.round(value * 100)}%`;}
function score(value?: number | null): string { if (typeof value !== "number" || Number.isNaN(value)) return "n/a"; return `${Math.round(value)}/100`;}
function statusTone(status: string): string { const lowered = status.toLowerCase(); if (["verified", "completed"].includes(lowered)) return "border-emerald-300/25 bg-emerald-300/10 text-emerald-50"; if (["no_results", "no_manifest", "not_configured", "tool_unavailable", "skipped"].includes(lowered)) { return "border-yellow-300/25 bg-yellow-300/10 text-yellow-50"; } return "border-orange-300/25 bg-orange-300/10 text-orange-50";}
function readableStatus(status: string): string { return status.replace(/_/g, " ");}
function detectorSummary(detector: DetectorResult): string { if (typeof detector.synthetic_probability === "number") { return `${percent(detector.synthetic_probability)} synthetic likelihood`; } if (typeof detector.score === "number") { return score(detector.score); } return readableStatus(detector.status);}
function CitationList({ citations }: { citations: Citation[] }) { if (citations.length === 0) { return <p className="text-sm leading-6 text-white/55">No citations returned for this scan.</p>; } return ( <div className="grid gap-3"> {citations.slice(0, 5).map((citation) => ( <a key={citation.url} href={citation.url} target="_blank" rel="noreferrer" className="rounded-lg border border-white/10 bg-white/5 p-3 text-sm text-white/75 transition hover:border-cyan-300/30 hover:text-white" > <div className="flex items-start justify-between gap-3"> <span className="font-bold text-white">{citation.title}</span> <ExternalLink className="mt-1 h-4 w-4 shrink-0 text-cyan-200" /> </div> {citation.source && <div className="mt-1 text-xs uppercase text-cyan-100/70">{citation.source}</div>} {citation.snippet && <p className="mt-2 leading-6 text-white/60">{citation.snippet}</p>} </a> ))} </div> );}
export default function EnhancedInsights({ result }: EnhancedInsightsProps) { const detectors = result.detectors ?? []; const citations = result.citations ?? result.web_research?.citations ?? []; const confidence = typeof result.confidence === "number" ? Math.round(result.confidence * 100) : null;
return ( <div className="mt-4 grid gap-4 lg:grid-cols-2"> {result.custom_feedback && ( <section className="panel lg:col-span-2"> <div className="mb-4 flex items-center gap-2"> <Sparkles className="h-5 w-5 text-cyan-300" /> <h3 className="text-base font-bold text-white">Custom Feedback</h3> </div> <h4 className="text-lg font-black text-white">{result.custom_feedback.headline}</h4> <p className="mt-3 text-sm leading-7 text-white/70">{result.custom_feedback.explanation}</p> <div className="mt-4 grid gap-3 md:grid-cols-2"> <div className="rounded-lg border border-white/10 bg-white/5 p-3"> <div className="mb-2 text-xs font-bold uppercase text-white/45">Evidence Notes</div> <ul className="space-y-2 text-sm leading-6 text-white/70"> {result.custom_feedback.evidence_notes.map((note) => ( <li key={note}>{note}</li> ))} </ul> </div> <div className="rounded-lg border border-white/10 bg-white/5 p-3"> <div className="mb-2 text-xs font-bold uppercase text-white/45">Next Steps</div> <ul className="space-y-2 text-sm leading-6 text-white/70"> {result.custom_feedback.next_steps.map((step) => ( <li key={step}>{step}</li> ))} </ul> </div> </div> </section> )}
<section className="panel"> <div className="mb-4 flex items-center gap-2"> <Bot className="h-5 w-5 text-violet-200" /> <h3 className="text-base font-bold text-white">Detector Opinions</h3> </div> {detectors.length > 0 ? ( <div className="grid gap-3"> {detectors.map((detector) => ( <div key={`${detector.name}-${detector.status}`} className={`rounded-lg border p-3 ${statusTone(detector.status)}`}> <div className="flex items-start justify-between gap-3"> <div> <div className="break-words text-sm font-bold">{detector.name}</div> {detector.label && <div className="mt-1 text-xs uppercase opacity-70">{detector.label.replace(/_/g, " ")}</div>} </div> <span className="shrink-0 rounded-full border border-white/10 bg-black/20 px-2 py-1 text-xs font-bold uppercase"> {readableStatus(detector.status)} </span> </div> <div className="mt-3 font-mono text-sm">{detectorSummary(detector)}</div> </div> ))} </div> ) : ( <p className="rounded-lg border border-white/10 bg-white/5 p-3 text-sm text-white/60">No detector results were returned.</p> )} </section>
<section className="panel"> <div className="mb-4 flex items-center gap-2"> <Fingerprint className="h-5 w-5 text-emerald-200" /> <h3 className="text-base font-bold text-white">Provenance</h3> </div> {result.provenance ? ( <div className={`rounded-lg border p-3 ${statusTone(result.provenance.status)}`}> <div className="flex items-center justify-between gap-3"> <span className="text-sm font-bold capitalize">{readableStatus(result.provenance.status)}</span> <span className="font-mono text-sm">{score(result.provenance.score)}</span> </div> <p className="mt-3 text-sm leading-6 opacity-80">{result.provenance.summary}</p> </div> ) : ( <p className="rounded-lg border border-white/10 bg-white/5 p-3 text-sm text-white/60"> Provenance checks are not available for this content type. </p> )} </section>
<section className="panel lg:col-span-2"> <div className="mb-4 flex flex-col gap-3 md:flex-row md:items-center md:justify-between"> <div className="flex items-center gap-2"> <FileSearch className="h-5 w-5 text-sky-200" /> <h3 className="text-base font-bold text-white">Web Research</h3> </div> <div className="flex flex-wrap gap-2 text-xs font-bold uppercase"> <span className="rounded-full border border-white/10 bg-white/5 px-3 py-1 text-white/55"> {result.analysis_mode ?? "local heuristic"} </span> {confidence !== null && ( <span className="rounded-full border border-cyan-300/20 bg-cyan-300/10 px-3 py-1 text-cyan-50"> {confidence}% confidence </span> )} </div> </div> {result.web_research ? ( <div className="grid gap-4"> <div className={`rounded-lg border p-3 ${statusTone(result.web_research.status)}`}> <div className="flex flex-wrap items-center justify-between gap-3"> <span className="text-sm font-bold capitalize">{readableStatus(result.web_research.status)}</span> <span className="font-mono text-sm">{score(result.web_research.score)}</span> </div> <p className="mt-3 text-sm leading-6 opacity-80">{result.web_research.summary}</p> {result.web_research.queries.length > 0 && ( <div className="mt-3 flex flex-wrap gap-2"> {result.web_research.queries.map((query) => ( <span key={query} className="rounded-full border border-white/10 bg-black/20 px-3 py-1 text-xs text-white/70"> {query} </span> ))} </div> )} </div> <CitationList citations={citations} /> <div className="flex items-start gap-2 rounded-lg border border-cyan-300/15 bg-cyan-300/10 p-3 text-sm leading-6 text-cyan-50/75"> <BadgeCheck className="mt-1 h-4 w-4 shrink-0 text-cyan-200" /> <span> Free web research uses indexed web/image search and generated queries. It is not an unlimited exact reverse image search across the entire internet. </span> </div> </div> ) : ( <p className="rounded-lg border border-white/10 bg-white/5 p-3 text-sm text-white/60">No web research was returned.</p> )} </section> </div> );}1234572 unmodified lines787980818283import { FileWarning, ScanLine } from "lucide-react";import type { AnalysisResult } from "../lib/types";import EvidenceBreakdown from "./EvidenceBreakdown";import RecommendationList from "./RecommendationList";import ScoreGauge from "./ScoreGauge";72 unmodified lines</section>)}<div className="mt-4 rounded-lg border border-white/10 bg-white/5 p-4 text-sm leading-6 text-white/70"><strong className="text-white">Disclaimer: </strong>{result.disclaimer}12345672 unmodified lines7980818283848586import { FileWarning, ScanLine } from "lucide-react";import type { AnalysisResult } from "../lib/types";import EnhancedInsights from "./EnhancedInsights";import EvidenceBreakdown from "./EvidenceBreakdown";import RecommendationList from "./RecommendationList";import ScoreGauge from "./ScoreGauge";72 unmodified lines</section>)}<EnhancedInsights result={result} /><div className="mt-4 rounded-lg border border-white/10 bg-white/5 p-4 text-sm leading-6 text-white/70"><strong className="text-white">Disclaimer: </strong>{result.disclaimer}
3 unmodified lines45678913 unmodified lines2324252627283 unmodified linesexport type Evidence = Record<string, number>;export interface SuspiciousFrame {frame_index: number;timestamp_seconds?: number | null;13 unmodified linesevidence: Evidence;technical_details: Record<string, unknown>;disclaimer: string;frames_analyzed?: number;suspicious_frames?: SuspiciousFrame[];}3 unmodified lines456789101112131415161718192021222324252627282930313233343536373839404142434445464748495013 unmodified lines646566676869707172737475763 unmodified linesexport type Evidence = Record<string, number>;export interface DetectorResult {name: string;status: string;label?: string | null;score?: number | null;synthetic_probability?: number | null;details?: Record<string, unknown>;}export interface ProvenanceResult {status: string;score: number;summary: string;details?: Record<string, unknown>;}export interface Citation {title: string;url: string;source?: string | null;snippet?: string | null;}export interface WebResearchResult {status: string;provider: string;score: number;queries: string[];matches_found: number;summary: string;citations: Citation[];details?: Record<string, unknown>;}export interface CustomFeedback {headline: string;explanation: string;evidence_notes: string[];next_steps: string[];}export interface SuspiciousFrame {frame_index: number;timestamp_seconds?: number | null;13 unmodified linesevidence: Evidence;technical_details: Record<string, unknown>;disclaimer: string;analysis_mode?: string;confidence?: number;detectors?: DetectorResult[];provenance?: ProvenanceResult | null;web_research?: WebResearchResult | null;citations?: Citation[];custom_feedback?: CustomFeedback | null;frames_analyzed?: number;suspicious_frames?: SuspiciousFrame[];}
12345{ "name": "truthshield-ai-frontend", "pages_build_output_dir": "./dist", "compatibility_date": "2026-06-27"}DEPLOYMENT.mdAdded+103
README.md+39
backend/.dockerignoreAdded+7
backend/.env.exampleAdded+18
backend/DockerfileAdded+19
backend/README.mdAdded+44
backend/analyzers/ai_detectors.pyAdded+197
backend/analyzers/config.pyAdded+61
backend/analyzers/enhanced.pyAdded+303
backend/analyzers/feedback.pyAdded+137
backend/analyzers/image_analyzer.py+9-1
backend/analyzers/provenance.pyAdded+147
backend/analyzers/text_analyzer.py+3-1
backend/analyzers/video_analyzer.py+3-1
backend/analyzers/web_research.pyAdded+266
backend/main.py+24-8
backend/models/schemas.py+48
backend/tests/test_enhanced_analysis.pyAdded+140
frontend/.env.exampleAdded+1
frontend/public/_redirectsAdded+1
frontend/src/components/EnhancedInsights.tsxAdded+200
frontend/src/components/ResultCard.tsx+3
frontend/src/lib/types.ts+48
frontend/wrangler.jsoncAdded+5