File size: 24,285 Bytes
c3e4914
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f7cc3fc
c3e4914
 
 
 
 
 
 
 
 
 
af9f47e
c3e4914
 
 
 
f7cc3fc
c3e4914
 
 
f7cc3fc
 
c3e4914
 
 
 
 
059253d
c3e4914
 
 
af9f47e
c552794
af9f47e
 
 
 
 
 
c3e4914
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
059253d
c3e4914
059253d
 
 
 
 
 
 
 
 
 
c3e4914
 
 
 
 
af9f47e
 
 
 
c3e4914
059253d
c3e4914
 
 
 
f4000d9
c3e4914
 
 
 
 
 
 
059253d
c3e4914
059253d
 
 
 
 
 
 
 
 
 
c3e4914
 
 
 
 
af9f47e
 
 
 
c3e4914
059253d
c3e4914
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
af9f47e
 
 
 
c3e4914
 
 
 
 
 
 
 
059253d
c3e4914
af9f47e
c3e4914
059253d
 
 
c3e4914
 
af9f47e
c3e4914
059253d
 
 
c3e4914
 
 
059253d
 
 
c3e4914
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
af9f47e
 
 
 
 
c552794
c3e4914
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
419e73d
c3e4914
 
 
 
 
 
 
 
 
 
059253d
 
c3e4914
 
059253d
c3e4914
059253d
 
 
c3e4914
059253d
 
 
c3e4914
 
 
 
 
 
 
af9f47e
 
 
 
 
 
 
c552794
af9f47e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c552794
af9f47e
 
059253d
c3e4914
 
 
 
 
 
059253d
c3e4914
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
af9f47e
c3e4914
059253d
c3e4914
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Deepfake detector</title>
  <link rel="preconnect" href="https://fonts.googleapis.com" />
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet" />
  <script src="https://cdn.tailwindcss.com"></script>
  <style>
    html, body { font-family: 'Inter', system-ui, -apple-system, sans-serif; }
    body { background: #f8fafc; color: #0f172a; }
    .arc-fg { transition: stroke-dashoffset 900ms cubic-bezier(0.22, 1, 0.36, 1); }
    .drop-active { border-color: #1d4ed8; background-color: #eff6ff; }
    .fade-in { animation: fadeIn 350ms ease-out both; }
    @keyframes fadeIn {
      from { opacity: 0; transform: translateY(6px); }
      to { opacity: 1; transform: translateY(0); }
    }
  </style>
</head>
<body class="min-h-screen">
  <div class="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
    <header class="flex items-center justify-between">
      <div class="flex items-center gap-2">
        <div class="w-9 h-9 rounded-lg bg-blue-600 flex items-center justify-center text-white font-bold">OF</div>
        <span class="font-bold text-lg" data-i18n="title">Deepfake detector</span>
      </div>
      <div class="inline-flex items-center rounded-full border border-gray-200 bg-white p-1 text-sm">
        <button id="lang-en" class="px-3 py-1 rounded-full font-semibold">EN</button>
        <button id="lang-fr" class="px-3 py-1 rounded-full font-semibold">FR</button>
      </div>
    </header>

    <main class="mt-10 sm:mt-16">
      <section class="text-center max-w-2xl mx-auto">
        <h1 class="text-4xl sm:text-5xl font-extrabold tracking-tight" data-i18n="title">Deepfake detector</h1>
        <p class="mt-4 text-gray-600 text-lg" data-i18n="subtitle">Upload an image or short video to check if it's AI-generated.</p>
      </section>

      <section id="card-root" class="mt-10">
        <!-- Upload zone -->
        <div id="upload-card" class="bg-white rounded-2xl border border-gray-200 p-6 sm:p-10 shadow-sm">
          <label id="dropzone" for="file-input"
            class="block border-2 border-dashed border-gray-300 rounded-xl p-10 text-center cursor-pointer hover:border-blue-400 transition-colors">
            <input id="file-input" type="file" class="hidden"
                   accept="image/jpeg,image/png,image/webp,video/mp4,video/quicktime,video/webm" />
            <div id="upload-prompt">
              <div class="mx-auto w-12 h-12 rounded-full bg-blue-50 flex items-center justify-center mb-4">
                <svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6 text-blue-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                  <path stroke-linecap="round" stroke-linejoin="round" d="M4 16v2a2 2 0 002 2h12a2 2 0 002-2v-2M12 12V4m0 0l-4 4m4-4l4 4"/>
                </svg>
              </div>
              <div class="text-base font-semibold text-gray-900" data-i18n="upload_cta">Choose a file or drag and drop</div>
              <div class="text-sm text-gray-500 mt-1" data-i18n="upload_hint">JPG, PNG, MP4 up to 100 MB</div>
            </div>
            <div id="preview" class="hidden">
              <div id="preview-media" class="mx-auto mb-4 max-h-64 flex justify-center"></div>
              <div id="preview-filename" class="text-sm font-medium text-gray-900 truncate"></div>
              <div id="preview-size" class="text-xs text-gray-500 mt-1"></div>
            </div>
          </label>

          <div id="error-banner" class="hidden mt-4 rounded-lg bg-red-50 border border-red-200 text-red-700 px-4 py-3 text-sm"></div>

          <div class="mt-6 flex flex-col sm:flex-row gap-3 justify-center">
            <button id="analyze-btn" disabled
                    class="px-6 py-3 rounded-xl bg-blue-600 text-white font-semibold disabled:bg-gray-300 disabled:cursor-not-allowed hover:bg-blue-700 transition-colors">
              <span data-i18n="analyze">Analyze</span>
            </button>
            <button id="reset-btn" class="hidden px-6 py-3 rounded-xl border border-gray-300 text-gray-700 font-semibold hover:bg-gray-50">
              <span data-i18n="clear">Clear</span>
            </button>
          </div>
        </div>

        <!-- Loading -->
        <div id="loading-card" class="hidden bg-white rounded-2xl border border-gray-200 p-10 shadow-sm text-center">
          <div class="mx-auto w-12 h-12 border-4 border-blue-200 border-t-blue-600 rounded-full animate-spin"></div>
          <div id="loading-text" class="mt-5 text-gray-700 font-medium" data-i18n="analyzing">Analyzing...</div>
        </div>

        <!-- Result -->
        <div id="result-card" class="hidden bg-white rounded-2xl border border-gray-200 p-6 sm:p-10 shadow-sm fade-in">
          <div class="flex items-start justify-between flex-wrap gap-2">
            <div>
              <div class="text-sm font-semibold text-gray-900 flex items-center gap-1.5">
                <span data-i18n="ai_score">AI-generated score</span>
                <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                  <path stroke-linecap="round" stroke-linejoin="round" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
                </svg>
              </div>
              <button id="how-link" class="mt-1 text-sm text-gray-500 underline decoration-gray-300 hover:text-gray-700">
                <span data-i18n="how_calculated">How is this calculated?</span>
              </button>
            </div>
          </div>

          <div class="mt-8 grid grid-cols-1 lg:grid-cols-3 gap-8 items-center">
            <div class="flex flex-col items-center">
              <div class="relative w-48 h-48 sm:w-56 sm:h-56">
                <svg viewBox="0 0 200 200" class="w-full h-full -rotate-90">
                  <circle cx="100" cy="100" r="80" fill="none" stroke="#e5e7eb" stroke-width="14" stroke-linecap="round"/>
                  <circle id="arc-fg" cx="100" cy="100" r="80" fill="none" stroke="#dc2626" stroke-width="14" stroke-linecap="round"
                          stroke-dasharray="502.65" stroke-dashoffset="502.65" class="arc-fg"/>
                </svg>
                <div class="absolute inset-0 flex flex-col items-center justify-center">
                  <div class="text-xs uppercase tracking-wider text-gray-500 font-semibold" data-i18n="ai_label">AI-generated</div>
                  <div id="score-pct" class="text-4xl sm:text-5xl font-extrabold mt-1 text-gray-900">--%</div>
                </div>
              </div>
            </div>

            <div>
              <div id="verdict-text" class="text-3xl sm:text-4xl font-extrabold leading-tight"></div>
              <div id="advice-text" class="mt-3 text-lg sm:text-xl font-semibold text-gray-900"></div>
              <div id="frames-info" class="mt-4 text-sm text-gray-500"></div>
            </div>

            <div id="preview-pane" style="display: none;" class="flex-col items-center">
              <div id="preview-wrap" class="relative inline-block">
                <img id="result-image" class="max-h-64 max-w-full rounded-lg block bg-gray-50" alt="" />
                <svg id="result-overlay" class="absolute top-0 left-0 w-full h-full pointer-events-none" preserveAspectRatio="none"></svg>
              </div>
              <div id="preview-status" class="mt-3 text-xs text-gray-500 text-center"></div>
            </div>
          </div>

          <div class="mt-8 flex justify-center">
            <button id="analyze-another-btn"
                    class="px-6 py-3 rounded-xl border border-gray-300 text-gray-700 font-semibold hover:bg-gray-50">
              <span data-i18n="analyze_another">Analyze another file</span>
            </button>
          </div>
        </div>
      </section>

      <footer class="mt-16 text-center text-xs text-gray-400">
        <span data-i18n="privacy_note">Files are processed in memory and not stored.</span>
      </footer>
    </main>
  </div>

  <!-- Modal -->
  <div id="modal-backdrop" class="hidden fixed inset-0 bg-black/40 z-40"></div>
  <div id="modal" class="hidden fixed inset-0 z-50 flex items-center justify-center p-4">
    <div class="bg-white rounded-2xl max-w-lg w-full p-6 shadow-xl">
      <h2 id="modal-title" class="text-xl font-bold" data-i18n="how_calculated_title">How the score is computed</h2>
      <p id="modal-body" class="mt-3 text-gray-700 leading-relaxed" data-i18n="how_calculated_body"></p>
      <div class="mt-5 text-right">
        <button id="modal-close" class="px-4 py-2 rounded-lg bg-blue-600 text-white font-semibold hover:bg-blue-700">
          <span data-i18n="close">Close</span>
        </button>
      </div>
    </div>
  </div>

  <script>
    const I18N = {
      en: {
        title: "Deepfake detector",
        subtitle: "Upload an image or short video to check if it's AI-generated.",
        upload_cta: "Choose a file or drag and drop",
        upload_hint: "JPG, PNG, MP4 up to 100 MB",
        analyze: "Analyze",
        clear: "Clear",
        analyzing: "Analyzing...",
        analyzing_video: "Sampling frames and running the model...",
        ai_score: "AI-generated score",
        how_calculated: "How is this calculated?",
        ai_label: "AI-generated",
        verdict_ai_image: "This image is likely AI-generated,",
        verdict_ai_video: "This video is likely AI-generated,",
        verdict_uncertain_image: "We're uncertain about this image,",
        verdict_uncertain_video: "We're uncertain about this video,",
        verdict_real_image: "This image is likely authentic,",
        verdict_real_video: "This video is likely authentic,",
        advice_ai: "you should not share it with your network.",
        advice_uncertain: "verify it from trusted sources before sharing.",
        advice_real: "but always cross-check important content.",
        analyze_another: "Analyze another file",
        error_generic: "Something went wrong. Please try again.",
        error_size: "File is too large.",
        error_type: "Unsupported file type.",
        frames_info: "Averaged over {n} frames.",
        preview_cropped_one: "Focused on 1 region (screenshot detected)",
        preview_cropped_many: "Focused on {n} regions (scores averaged)",
        preview_full: "Full image analyzed",
        preview_text_only: "Text-only screenshot — score softened",
        how_calculated_title: "How the score is computed",
        how_calculated_body: "We use a Swin Transformer V2 model fine-tuned to distinguish real photographs from AI-generated images. For videos, we sample 5 frames evenly across the duration and average the model's confidence. The score shown is the model's estimated probability that the content was generated by AI.",
        close: "Close",
        privacy_note: "Files are processed in memory and not stored.",
      },
      fr: {
        title: "Détecteur d'hypertrucage",
        subtitle: "Téléversez une image ou une courte vidéo pour vérifier si elle est générée par IA.",
        upload_cta: "Choisissez un fichier ou glissez-déposez",
        upload_hint: "JPG, PNG, MP4 jusqu'à 100 Mo",
        analyze: "Analyser",
        clear: "Effacer",
        analyzing: "Analyse en cours...",
        analyzing_video: "Échantillonnage des images et exécution du modèle...",
        ai_score: "Score d'IA générée",
        how_calculated: "Comment est-ce calculé ?",
        ai_label: "IA générée",
        verdict_ai_image: "Cette image est probablement générée par IA,",
        verdict_ai_video: "Cette vidéo est probablement générée par IA,",
        verdict_uncertain_image: "Nous ne sommes pas certains pour cette image,",
        verdict_uncertain_video: "Nous ne sommes pas certains pour cette vidéo,",
        verdict_real_image: "Cette image est probablement authentique,",
        verdict_real_video: "Cette vidéo est probablement authentique,",
        advice_ai: "vous ne devriez pas la partager avec votre réseau.",
        advice_uncertain: "vérifiez auprès de sources fiables avant de partager.",
        advice_real: "vérifiez tout de même les contenus importants.",
        analyze_another: "Analyser un autre fichier",
        error_generic: "Une erreur est survenue. Veuillez réessayer.",
        error_size: "Le fichier est trop volumineux.",
        error_type: "Type de fichier non pris en charge.",
        frames_info: "Moyenne sur {n} images.",
        preview_cropped_one: "Focus sur 1 zone (capture d'écran détectée)",
        preview_cropped_many: "Focus sur {n} zones (scores moyennés)",
        preview_full: "Image entière analysée",
        preview_text_only: "Capture texte uniquement — score atténué",
        how_calculated_title: "Comment le score est calculé",
        how_calculated_body: "Nous utilisons un modèle Swin Transformer V2 entraîné pour distinguer les vraies photographies des images générées par IA. Pour les vidéos, nous échantillonnons 5 images réparties uniformément sur la durée et faisons la moyenne de la confiance du modèle. Le score affiché correspond à la probabilité estimée que le contenu ait été généré par IA.",
        close: "Fermer",
        privacy_note: "Les fichiers sont traités en mémoire et ne sont pas conservés.",
      },
    };

    const CIRCUMFERENCE = 2 * Math.PI * 80;

    const state = {
      lang: localStorage.getItem("lang") || (navigator.language.startsWith("fr") ? "fr" : "en"),
      file: null,
      result: null,
      loading: false,
      error: null,
    };

    const $ = (id) => document.getElementById(id);

    function t() {
      return I18N[state.lang];
    }

    function applyI18n() {
      document.documentElement.lang = state.lang;
      document.querySelectorAll("[data-i18n]").forEach((el) => {
        const key = el.getAttribute("data-i18n");
        if (t()[key] != null) el.textContent = t()[key];
      });
      $("lang-en").className = "px-3 py-1 rounded-full font-semibold " +
        (state.lang === "en" ? "bg-blue-600 text-white" : "text-gray-600");
      $("lang-fr").className = "px-3 py-1 rounded-full font-semibold " +
        (state.lang === "fr" ? "bg-blue-600 text-white" : "text-gray-600");
      if (state.result) {
        renderResultText();
        renderPreviewOverlay();
      }
    }

    function setLang(lang) {
      state.lang = lang;
      localStorage.setItem("lang", lang);
      applyI18n();
    }

    function getVerdict(aiScore, mediaType) {
      const T = t();
      if (aiScore >= 0.60) {
        return {
          verdict: mediaType === "video" ? T.verdict_ai_video : T.verdict_ai_image,
          advice: T.advice_ai,
          tone: "ai",
        };
      }
      if (aiScore >= 0.30) {
        return {
          verdict: mediaType === "video" ? T.verdict_uncertain_video : T.verdict_uncertain_image,
          advice: T.advice_uncertain,
          tone: "uncertain",
        };
      }
      return {
        verdict: mediaType === "video" ? T.verdict_real_video : T.verdict_real_image,
        advice: T.advice_real,
        tone: "real",
      };
    }

    function showPreview(file) {
      const previewMedia = $("preview-media");
      previewMedia.innerHTML = "";
      if (file.type.startsWith("image/")) {
        const img = document.createElement("img");
        img.src = URL.createObjectURL(file);
        img.className = "max-h-64 rounded-lg object-contain";
        img.onload = () => URL.revokeObjectURL(img.src);
        previewMedia.appendChild(img);
      } else {
        const video = document.createElement("video");
        video.src = URL.createObjectURL(file);
        video.className = "max-h-64 rounded-lg";
        video.muted = true;
        video.playsInline = true;
        video.preload = "metadata";
        previewMedia.appendChild(video);
      }
      $("upload-prompt").classList.add("hidden");
      $("preview").classList.remove("hidden");
      $("preview-filename").textContent = file.name;
      $("preview-size").textContent = `${(file.size / (1024 * 1024)).toFixed(2)} MB`;
      $("analyze-btn").disabled = false;
      $("reset-btn").classList.remove("hidden");
    }

    function resetUpload() {
      state.file = null;
      state.error = null;
      $("file-input").value = "";
      $("upload-prompt").classList.remove("hidden");
      $("preview").classList.add("hidden");
      $("analyze-btn").disabled = true;
      $("reset-btn").classList.add("hidden");
      $("error-banner").classList.add("hidden");
      const resultImg = $("result-image");
      if (resultImg.src) {
        try { URL.revokeObjectURL(resultImg.src); } catch (_) {}
        resultImg.removeAttribute("src");
      }
      $("preview-pane").style.display = "none";
    }

    function showError(msg) {
      const banner = $("error-banner");
      banner.textContent = msg;
      banner.classList.remove("hidden");
    }

    function setFile(file) {
      $("error-banner").classList.add("hidden");
      if (!file) return;
      const isImage = file.type.startsWith("image/");
      const isVideo = file.type.startsWith("video/");
      if (!isImage && !isVideo) {
        showError(t().error_type);
        return;
      }
      const maxMB = isVideo ? 300 : 50;
      if (file.size / (1024 * 1024) > maxMB) {
        showError(t().error_size);
        return;
      }
      state.file = file;
      showPreview(file);
    }

    function renderResultText() {
      if (!state.result) return;
      const score = state.result.p_fake;
      const v = getVerdict(score, state.result.media_type);
      $("verdict-text").textContent = v.verdict;
      $("advice-text").textContent = v.advice;
      $("score-pct").textContent = `${Math.round(score * 100)}%`;
      const tones = {
        ai: "#dc2626",
        uncertain: "#d97706",
        real: "#16a34a",
      };
      const color = tones[v.tone];
      $("arc-fg").setAttribute("stroke", color);
      $("verdict-text").style.color = color;
      if (state.result.media_type === "video") {
        $("frames-info").textContent = t().frames_info.replace("{n}", state.result.n_frames);
      } else {
        $("frames-info").textContent = "";
      }
    }

    function renderPreviewOverlay() {
      const pane = $("preview-pane");
      const img = $("result-image");
      const overlay = $("result-overlay");
      const statusEl = $("preview-status");

      if (!state.result || state.result.media_type !== "image" || !state.file) {
        pane.style.display = "none";
        return;
      }

      if (img.src) {
        try { URL.revokeObjectURL(img.src); } catch (_) {}
      }
      img.src = URL.createObjectURL(state.file);

      img.onload = () => {
        const [iw, ih] = state.result.image_size || [img.naturalWidth, img.naturalHeight];
        overlay.setAttribute("viewBox", `0 0 ${iw} ${ih}`);

        // Clear previous rects.
        while (overlay.firstChild) overlay.removeChild(overlay.firstChild);

        const boxes = state.result.crop_box || [];
        const sw = Math.max(iw, ih) * 0.012;  // thick stroke, ~1.2% of larger dim
        for (const box of boxes) {
          const [x, y, w, h] = box;
          const rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
          rect.setAttribute("x", x);
          rect.setAttribute("y", y);
          rect.setAttribute("width", w);
          rect.setAttribute("height", h);
          rect.setAttribute("fill", "none");
          rect.setAttribute("stroke", "#ef4444");
          rect.setAttribute("stroke-width", sw);
          rect.setAttribute("rx", sw * 0.5);
          overlay.appendChild(rect);
        }
      };

      const T = t();
      const status = state.result.preprocess_status;
      let label = "";
      if (status === "cropped") {
        const n = state.result.n_crops || 1;
        label = n === 1
          ? T.preview_cropped_one
          : T.preview_cropped_many.replace("{n}", n);
      } else if (status === "text_only") {
        label = T.preview_text_only;
      } else {
        label = T.preview_full;
      }
      statusEl.textContent = label;
      pane.style.display = "flex";
    }

    function animateArc(fraction) {
      const arc = $("arc-fg");
      arc.style.transition = "none";
      arc.setAttribute("stroke-dashoffset", CIRCUMFERENCE);
      requestAnimationFrame(() => {
        requestAnimationFrame(() => {
          arc.style.transition = "";
          const target = CIRCUMFERENCE * (1 - Math.max(0, Math.min(1, fraction)));
          arc.setAttribute("stroke-dashoffset", target);
        });
      });
    }

    function showCard(name) {
      ["upload-card", "loading-card", "result-card"].forEach((id) => {
        $(id).classList.toggle("hidden", id !== name);
      });
    }

    async function analyze() {
      if (!state.file) return;
      state.loading = true;
      state.error = null;
      const isVideo = state.file.type.startsWith("video/");
      $("loading-text").textContent = isVideo ? t().analyzing_video : t().analyzing;
      showCard("loading-card");

      const form = new FormData();
      form.append("file", state.file);

      try {
        const res = await fetch("/api/predict", { method: "POST", body: form });
        if (!res.ok) {
          let detail = t().error_generic;
          if (res.status === 413) detail = t().error_size;
          else if (res.status === 415) detail = t().error_type;
          else {
            const body = await res.json().catch(() => ({}));
            if (body.detail) detail = body.detail;
          }
          throw new Error(detail);
        }
        state.result = await res.json();
        renderResultText();
        renderPreviewOverlay();
        showCard("result-card");
        animateArc(state.result.p_fake);
      } catch (e) {
        showError(e.message);
        showCard("upload-card");
      } finally {
        state.loading = false;
      }
    }

    function openModal() {
      $("modal").classList.remove("hidden");
      $("modal").classList.add("flex");
      $("modal-backdrop").classList.remove("hidden");
    }
    function closeModal() {
      $("modal").classList.add("hidden");
      $("modal").classList.remove("flex");
      $("modal-backdrop").classList.add("hidden");
    }

    function init() {
      applyI18n();

      $("lang-en").addEventListener("click", () => setLang("en"));
      $("lang-fr").addEventListener("click", () => setLang("fr"));

      const fileInput = $("file-input");
      fileInput.addEventListener("change", (e) => {
        const f = e.target.files && e.target.files[0];
        if (f) setFile(f);
      });

      const dz = $("dropzone");
      ["dragenter", "dragover"].forEach((evt) => {
        dz.addEventListener(evt, (e) => {
          e.preventDefault();
          e.stopPropagation();
          dz.classList.add("drop-active");
        });
      });
      ["dragleave", "drop"].forEach((evt) => {
        dz.addEventListener(evt, (e) => {
          e.preventDefault();
          e.stopPropagation();
          dz.classList.remove("drop-active");
        });
      });
      dz.addEventListener("drop", (e) => {
        const f = e.dataTransfer.files && e.dataTransfer.files[0];
        if (f) setFile(f);
      });

      $("analyze-btn").addEventListener("click", analyze);
      $("reset-btn").addEventListener("click", (e) => {
        e.preventDefault();
        e.stopPropagation();
        resetUpload();
      });
      $("analyze-another-btn").addEventListener("click", () => {
        state.result = null;
        resetUpload();
        showCard("upload-card");
      });

      $("how-link").addEventListener("click", openModal);
      $("modal-close").addEventListener("click", closeModal);
      $("modal-backdrop").addEventListener("click", closeModal);
      document.addEventListener("keydown", (e) => {
        if (e.key === "Escape") closeModal();
      });
    }

    init();
  </script>
</body>
</html>