Spaces:
Sleeping
Sleeping
File size: 11,020 Bytes
e7d800d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 | // Media forensics: decides how likely an image / video frame is AI-generated or manipulated.
//
// Honest by design. No detector is reliable on its own (independent tests in 2026 show
// commercial classifiers missing a large share of heavily edited images), so we combine
// independent signals and report each one, never a bare "fake/real":
// 1. Provenance — C2PA / Content Credentials manifest, IPTC "trainedAlgorithmicMedia",
// generator names written into EXIF/XMP by AI tools. (strong when present)
// 2. Classifiers — Hive / Sightengine, only when their API keys are configured.
// 3. Claude vision forensic read — visual artefacts, physics, text, hands, lighting.
// Every number shown to a user comes from one of these; nothing is invented.
import Anthropic from '@anthropic-ai/sdk';
const MODEL = process.env.VERIFY_MODEL || 'claude-opus-5-5';
let client = null;
function claude() {
if (!process.env.ANTHROPIC_API_KEY) return null;
if (!client) client = new Anthropic();
return client;
}
// Generator fingerprints that AI tools write into metadata (EXIF Software, XMP CreatorTool,
// PNG tEXt "parameters", C2PA claim_generator...). Lower-cased substring match.
const GENERATORS = [
'midjourney', 'dall-e', 'dall·e', 'openai', 'chatgpt', 'stable diffusion', 'stablediffusion',
'comfyui', 'automatic1111', 'invokeai', 'novelai', 'firefly', 'imagen', 'gemini', 'nano banana',
'flux', 'black forest labs', 'leonardo.ai', 'ideogram', 'runway', 'sora', 'kling', 'pika',
'luma', 'veo', 'hailuo', 'seedance', 'seedream', 'higgsfield', 'grok', 'aurora', 'krea',
'playground', 'recraft', 'synthid',
];
/** Scan raw bytes for provenance + generator markers. Pure, no network. */
export function scanMetadata(buf) {
// Metadata lives in the first/last chunks (JPEG APP segments, PNG text chunks, MP4 moov/uuid).
const head = buf.subarray(0, Math.min(buf.length, 512 * 1024));
const tail = buf.length > 512 * 1024 ? buf.subarray(buf.length - 256 * 1024) : Buffer.alloc(0);
const text = (head.toString('latin1') + '\n' + tail.toString('latin1'));
const lower = text.toLowerCase();
const signals = [];
const c2pa = /c2pa|jumbf|contentauth|cai\.manifest/i.test(text);
if (c2pa) signals.push({ kind: 'provenance', label: 'C2PA Content Credentials manifest present', weight: 0 });
// IPTC Digital Source Type — the standard field AI tools and C2PA use to declare AI output.
const dst = lower.match(/digitalsourcetype[^a-z]{0,40}([a-z/:._-]*(trainedalgorithmicmedia|compositesynthetic|algorithmicmedia|compositewithtrainedalgorithmicmedia)[a-z]*)/);
let declaredAI = false;
if (dst || /trainedalgorithmicmedia/.test(lower)) {
declaredAI = true;
signals.push({ kind: 'provenance', label: 'IPTC DigitalSourceType declares AI-generated media (trainedAlgorithmicMedia)', weight: 0.95 });
}
if (/c2pa\.ai_generat|"c2pa\.created".{0,200}trainedalgorithmic|ai_generative_training/.test(lower)) {
declaredAI = true;
signals.push({ kind: 'provenance', label: 'C2PA action marks the asset as AI-created', weight: 0.95 });
}
// Only search printable text runs (like `strings`) with word boundaries — compressed pixel
// data otherwise "contains" short names such as "veo" or "flux" by pure chance.
const strs = (lower.match(/[\x20-\x7e\u00b7]{6,}/g) || []).join('\n');
const hits = [...new Set(GENERATORS.filter(g => new RegExp(`(^|[^a-z0-9])${g.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}([^a-z]|$)`).test(strs)))];
if (hits.length) {
signals.push({ kind: 'metadata', label: `AI generator named in file metadata: ${hits.slice(0, 5).join(', ')}`, weight: 0.85 });
}
// Stable-Diffusion style PNG "parameters" chunk (prompt + sampler settings).
if (/negative prompt:|sampler:\s|cfg scale:|steps:\s*\d+,/i.test(text)) {
signals.push({ kind: 'metadata', label: 'Diffusion prompt/sampler parameters embedded in the file', weight: 0.9 });
}
const hasCamera = /(canon|nikon|sony|fujifilm|olympus|panasonic|leica|apple|samsung|google pixel|iphone)/i.test(head.toString('latin1').slice(0, 64 * 1024));
if (hasCamera && !hits.length && !declaredAI) {
signals.push({ kind: 'metadata', label: 'Camera make/model present in EXIF (weak evidence — easily copied)', weight: -0.15 });
}
if (!c2pa && !signals.some(x => x.weight > 0)) {
signals.push({ kind: 'metadata', label: 'No provenance metadata (most social platforms strip it — neutral)', weight: 0 });
}
return { c2pa, declaredAI, generators: hits, signals };
}
/** Optional commercial classifier: Hive (HIVE_API_KEY). Returns probability 0..1 or null. */
async function hive(buf, mime) {
const key = process.env.HIVE_API_KEY;
if (!key) return null;
try {
const fd = new FormData();
fd.append('media', new Blob([buf], { type: mime }), 'upload');
const r = await fetch('https://api.thehive.ai/api/v2/task/sync', {
method: 'POST', headers: { authorization: `Token ${key}` }, body: fd,
signal: AbortSignal.timeout(30000),
});
if (!r.ok) return { error: `Hive HTTP ${r.status}` };
const j = await r.json();
const classes = j?.status?.[0]?.response?.output?.[0]?.classes || [];
const ai = classes.find(c => c.class === 'ai_generated');
return ai ? { provider: 'Hive', p: ai.score } : { error: 'Hive: no ai_generated class' };
} catch (e) { return { error: `Hive: ${e.message}` }; }
}
/** Optional commercial classifier: Sightengine (SIGHTENGINE_USER + SIGHTENGINE_SECRET). */
async function sightengine(buf, mime) {
const user = process.env.SIGHTENGINE_USER, secret = process.env.SIGHTENGINE_SECRET;
if (!user || !secret) return null;
try {
const fd = new FormData();
fd.append('media', new Blob([buf], { type: mime }), 'upload');
fd.append('models', 'genai');
fd.append('api_user', user); fd.append('api_secret', secret);
const r = await fetch('https://api.sightengine.com/1.0/check.json', {
method: 'POST', body: fd, signal: AbortSignal.timeout(30000),
});
const j = await r.json();
const p = j?.type?.ai_generated;
return typeof p === 'number' ? { provider: 'Sightengine', p } : { error: `Sightengine: ${j?.error?.message || 'no score'}` };
} catch (e) { return { error: `Sightengine: ${e.message}` }; }
}
const VISION_SCHEMA = {
type: 'object',
additionalProperties: false,
required: ['ai_probability', 'manipulation_probability', 'verdict', 'artifacts', 'summary_en', 'summary_ja'],
properties: {
ai_probability: { type: 'number', description: '0..1 likelihood the image is wholly AI-generated' },
manipulation_probability: { type: 'number', description: '0..1 likelihood a real photo was edited/face-swapped' },
verdict: { type: 'string', enum: ['likely_ai', 'possibly_ai', 'likely_authentic', 'inconclusive'] },
artifacts: { type: 'array', items: { type: 'string' }, description: 'specific visual evidence observed' },
summary_en: { type: 'string' },
summary_ja: { type: 'string' },
},
};
const VISION_PROMPT = `You are a media-forensics analyst. Examine this image for evidence that it is AI-generated or manipulated (deepfake / face swap / composite).
Look for concrete evidence only: anatomy (hands, teeth, ears, eyes/pupils), text and signage legibility, repeated or melting textures, inconsistent lighting and shadows, reflections, physically impossible geometry, over-smooth skin, background warping near edges, watermark remnants of AI tools, compression patterns inconsistent with the scene.
Be calibrated: most real phone photos have none of these. Absence of evidence is not proof of authenticity — use "inconclusive" when you cannot tell. Never claim certainty. List each artefact you actually see; do not list things you did not see.`;
/** Claude vision forensic read. */
async function visionRead(buf, mime) {
const c = claude();
if (!c) return { error: 'ANTHROPIC_API_KEY not set — vision analysis skipped' };
const media = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'].includes(mime) ? mime : 'image/jpeg';
try {
const res = await c.beta.messages.create({
model: MODEL,
max_tokens: 4000,
betas: ['server-side-fallback-2026-07-01'],
fallbacks: 'default',
output_config: { effort: 'medium', format: { type: 'json_schema', schema: VISION_SCHEMA } },
messages: [{
role: 'user',
content: [
{ type: 'image', source: { type: 'base64', media_type: media, data: buf.toString('base64') } },
{ type: 'text', text: VISION_PROMPT },
],
}],
});
if (res.stop_reason === 'refusal') return { error: 'model declined to analyse this image' };
const t = res.content.find(b => b.type === 'text');
const j = JSON.parse(t?.text || '{}');
const clamp = v => Math.max(0, Math.min(1, Number(v) || 0));
j.ai_probability = clamp(j.ai_probability);
j.manipulation_probability = clamp(j.manipulation_probability);
return j;
} catch (e) {
if (e instanceof Anthropic.RateLimitError) return { error: 'Claude rate-limited — retry shortly' };
if (e instanceof Anthropic.APIError) return { error: `Claude API ${e.status}: ${e.message}` };
return { error: `vision: ${e.message}` };
}
}
/**
* Fuse the signals into one score with an explicit, inspectable rule:
* - a provenance declaration of AI output dominates (it is the file saying so itself);
* - otherwise average the available model probabilities (classifiers + Claude);
* - metadata hints nudge, never decide.
*/
export function fuse(meta, classifiers, vision) {
const probs = [];
for (const c of classifiers) if (c && typeof c.p === 'number') probs.push(c.p);
if (vision && typeof vision.ai_probability === 'number') {
probs.push(Math.max(vision.ai_probability, vision.manipulation_probability * 0.9));
}
let score = probs.length ? probs.reduce((a, b) => a + b, 0) / probs.length : 0.5;
const strong = meta.signals.filter(s => s.weight >= 0.85);
if (meta.declaredAI) score = Math.max(score, 0.97);
else if (strong.length) score = Math.max(score, 0.85);
const nudge = meta.signals.filter(s => s.weight < 0).reduce((a, s) => a + s.weight, 0);
score = Math.max(0, Math.min(1, score + nudge * (meta.declaredAI ? 0 : 0.5)));
const evidence = probs.length + strong.length;
let label;
if (evidence === 0) label = 'inconclusive';
else if (score >= 0.8) label = 'likely_ai';
else if (score >= 0.55) label = 'possibly_ai';
else if (score <= 0.3) label = 'likely_authentic';
else label = 'inconclusive';
return { score: Math.round(score * 100) / 100, label, evidence_sources: evidence };
}
/** Analyse one still image buffer. */
export async function analyseImage(buf, mime) {
const meta = scanMetadata(buf);
const [h, s, v] = await Promise.all([hive(buf, mime), sightengine(buf, mime), visionRead(buf, mime)]);
const classifiers = [h, s].filter(Boolean);
return { meta, classifiers, vision: v, result: fuse(meta, classifiers, v.error ? null : v) };
}
|