Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
1284 lines (1133 loc) · 51.1 KB
/
Copy pathapp.js
File metadata and controls
1284 lines (1133 loc) · 51.1 KB
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
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
let appConfig = { local: false, local_default_host: "127.0.0.1:5000" };
async function loadConfig() {
try {
const res = await fetch("config.json", { cache: "no-store" });
if (res.ok) appConfig = { ...appConfig, ...(await res.json()) };
} catch (e) {
}
applyConnectMode();
}
function applyConnectMode() {
const input = document.getElementById("connectInput");
const title = document.getElementById("gateTitle");
const sub = document.getElementById("gateSub");
const hint = document.getElementById("gateHint");
if (appConfig.local) {
title.textContent = "Connect to your local sandbox";
sub.textContent = "Detection happens on this machine. Start the app, then enter the address it's running on below — usually the default already works.";
input.placeholder = appConfig.local_default_host || "127.0.0.1:5000";
if (!input.value) input.value = appConfig.local_default_host || "127.0.0.1:5000";
hint.innerHTML = 'App not running yet? <a href="#/integration">See setup →</a>';
} else {
title.textContent = "Pair this tab";
sub.textContent = "Nothing gets analyzed on a server we run. Detection happens on your own machine — download the app, click Start, and paste the connection code it shows below.";
input.placeholder = "paste connection code or full URL — e.g. 8f2a-91cd or https://…";
hint.textContent = "Don't have the app yet? Grab it in step 1.";
}
}
const ROUTES = ["/", "/docs", "/integration"];
function restorePath() {
const params = new URLSearchParams(location.search);
const redirect = params.get("redirect");
if (redirect) {
history.replaceState(null, "", redirect);
}
}
restorePath();
function currentPath() {
if (location.hash.startsWith("#/")) return location.hash.slice(1);
const p = location.pathname.replace(/^\/censor/, "");
if (p.startsWith("/u/")) return p;
return "/";
}
function pairCodeFromPath(path) {
const m = path.match(/^\/u\/(.+)$/);
return m ? decodeURIComponent(m[1]) : null;
}
function render() {
const path = currentPath();
const base = path.startsWith("/u/") ? "/" : path;
document.querySelectorAll(".view").forEach(v => v.classList.toggle("active", v.dataset.view === base));
document.querySelectorAll("#navLinks a").forEach(a => a.classList.toggle("active", a.dataset.route === base));
const code = pairCodeFromPath(path);
if (code && !connection.base) {
document.getElementById("connectInput").value = code;
attemptConnect(code, { silent: false });
}
}
window.addEventListener("hashchange", render);
window.addEventListener("popstate", render);
function setupDocsNav() {
const links = document.querySelectorAll("#docsNav a[data-target]");
const sections = Array.from(document.querySelectorAll(".doc-section"));
links.forEach(a => {
a.addEventListener("click", (e) => {
e.preventDefault();
const target = document.getElementById(a.dataset.target);
if (target) target.scrollIntoView({ behavior: "smooth", block: "start" });
links.forEach(x => x.classList.remove("active"));
a.classList.add("active");
});
});
if (sections.length && "IntersectionObserver" in window) {
const observer = new IntersectionObserver((entries) => {
const visible = entries.filter(entry => entry.isIntersecting).sort((a, b) => b.intersectionRatio - a.intersectionRatio)[0];
if (!visible) return;
const activeTarget = visible.target.id;
links.forEach(link => link.classList.toggle("active", link.dataset.target === activeTarget));
}, { rootMargin: "-20% 0px -62% 0px", threshold: [0.2, 0.4, 0.6] });
sections.forEach(section => observer.observe(section));
}
}
setupDocsNav();
const connection = { base: null };
const NGROK_HEADER = { "ngrok-skip-browser-warning": "true" };
function decodeConnectionInput(raw) {
raw = raw.trim();
if (!raw) return null;
if (appConfig.local) {
if (/^https?:\/\//i.test(raw)) return raw.replace(/\/+$/, "");
if (/^[\w.-]+(:\d+)?$/.test(raw)) return "http://" + raw.replace(/\/+$/, "");
return null;
}
if (/^https?:\/\//i.test(raw)) return raw.replace(/\/+$/, "");
try {
const padded = raw.replace(/-/g, "+").replace(/_/g, "/");
const decoded = atob(padded + "===".slice((padded.length + 3) % 4));
if (/^https?:\/\//i.test(decoded)) return decoded.replace(/\/+$/, "");
} catch (e) { /* not base64 */ }
return null;
}
const gateEl = document.getElementById("gate");
const appEl = document.getElementById("app");
const nodeSandbox = document.getElementById("nodeSandbox");
const pairLink = document.getElementById("pairLink");
const gateError = document.getElementById("gateError");
const connectBtn = document.getElementById("connectBtn");
const navStatus = document.getElementById("navStatus");
const navStatusText = document.getElementById("navStatusText");
document.getElementById("connectForm").addEventListener("submit", (e) => {
e.preventDefault();
attemptConnect(document.getElementById("connectInput").value);
});
async function attemptConnect(raw, opts = {}) {
const target = decodeConnectionInput(raw);
gateError.textContent = "";
if (!target) {
gateError.textContent = "That doesn't look like a valid code or URL — copy it fresh from the app.";
return;
}
connectBtn.disabled = true;
connectBtn.textContent = "Pairing…";
pairLink.classList.add("connecting");
nodeSandbox.classList.add("pulsing");
try {
const res = await fetch(target + "/health", { headers: NGROK_HEADER });
if (!res.ok) throw new Error("sandbox responded with " + res.status);
const data = await res.json();
if (data.status !== "ok") throw new Error("unexpected response from sandbox");
connection.base = target;
localStorage.setItem("censor_last_connection", raw.trim());
onConnected(target);
} catch (err) {
pairLink.classList.remove("connecting");
nodeSandbox.classList.remove("pulsing");
gateError.textContent = "Couldn't reach that sandbox (" + err.message + "). Is the app still running?";
} finally {
connectBtn.disabled = false;
connectBtn.textContent = "Pair";
}
}
function onConnected(target) {
pairLink.classList.remove("connecting");
pairLink.classList.add("linked");
nodeSandbox.classList.remove("pulsing");
nodeSandbox.classList.add("linked");
navStatus.classList.add("live");
navStatusText.textContent = "sandbox connected";
document.getElementById("connectedTo").textContent = shortenUrl(target);
setTimeout(() => {
gateEl.style.display = "none";
appEl.style.display = "block";
if (typeof syncPreviewHeight === "function") syncPreviewHeight();
}, 350);
}
function shortenUrl(url) {
try {
const u = new URL(url);
return u.hostname;
} catch (e) { return url; }
}
(function offerLastConnection() {
const last = localStorage.getItem("censor_last_connection");
if (last) document.getElementById("connectInput").value = last;
})();
const DOWNLOAD_URL = "downloads/CensorSandbox-Setup.exe";
const downloadAppBtn = document.getElementById("downloadAppBtn");
const downloadIdle = document.getElementById("downloadIdle");
const downloadPreparing = document.getElementById("downloadPreparing");
const downloadDone = document.getElementById("downloadDone");
const walkthroughPanel = document.getElementById("walkthroughPanel");
function trackEvent(name, data) {
try { console.debug("[censor:track]", name, data || {}); } catch (e) { /* noop */ }
}
if (downloadAppBtn) {
downloadAppBtn.addEventListener("click", () => {
trackEvent("download_click", { url: downloadAppBtn.getAttribute("href") });
downloadIdle.style.display = "none";
downloadPreparing.style.display = "block";
setTimeout(() => {
downloadPreparing.style.display = "none";
downloadDone.style.display = "block";
walkthroughPanel.style.display = "block";
walkthroughPanel.scrollIntoView({ behavior: "smooth", block: "nearest" });
}, 900);
});
}
const GENITAL_ANUS_CLASSES = ["FEMALE_GENITALIA_EXPOSED", "MALE_GENITALIA_EXPOSED", "ANUS_EXPOSED"];
const BREAST_CLASSES = ["FEMALE_BREAST_EXPOSED", "MALE_BREAST_EXPOSED"];
const BUTTOCKS_CLASSES = ["BUTTOCKS_EXPOSED"];
const FEET_CLASSES = ["FEET_EXPOSED"];
const FACE_CLASSES = ["FACE_FEMALE", "FACE_MALE"];
const BELLY_CLASSES = ["BELLY_EXPOSED"];
const ARMPITS_CLASSES = ["ARMPITS_EXPOSED"];
function apiUrl(path) { return connection.base + path; }
const fileInput = document.getElementById("fileInput");
const dropLabel = document.getElementById("dropLabel");
const previewPanel = document.getElementById("previewPanel");
const previewBrowseBtn = document.getElementById("previewBrowseBtn");
const analyzeBtn = document.getElementById("analyzeBtn");
const analyzeLabel = document.getElementById("analyzeLabel");
const resetBtn = document.getElementById("resetBtn");
const statusMsg = document.getElementById("statusMsg");
const canvasWrap = document.getElementById("canvasWrap");
const canvasPlaceholder = document.getElementById("canvasPlaceholder");
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
const videoQueuePanel = document.getElementById("videoQueuePanel");
const videoQueueList = document.getElementById("videoQueueList");
const videoQueueBody = document.getElementById("videoQueueBody");
const toggleQueueBtn = document.getElementById("toggleQueueBtn");
const tabQueueBtn = document.getElementById("tabQueueBtn");
const tabSavedBtn = document.getElementById("tabSavedBtn");
const savedList = document.getElementById("savedList");
const saveResultBtn = document.getElementById("saveResultBtn");
const logEmpty = document.getElementById("logEmpty");
const logList = document.getElementById("logList");
const logCount = document.getElementById("logCount");
const logCardBody = document.getElementById("logCardBody");
const toggleAdvancedBtn = document.getElementById("toggleAdvancedBtn");
const showAllToggle = document.getElementById("showAllToggle");
const showAllWrap = document.getElementById("showAllWrap");
const preBlurToggle = document.getElementById("preBlurToggle");
const censorGenitals = document.getElementById("censorGenitals");
const censorBreasts = document.getElementById("censorBreasts");
const censorButtocks = document.getElementById("censorButtocks");
const censorFeet = document.getElementById("censorFeet");
const censorFace = document.getElementById("censorFace");
const censorBelly = document.getElementById("censorBelly");
const censorArmpits = document.getElementById("censorArmpits");
const styleRadios = document.querySelectorAll('input[name="style"]');
const solidColorWrap = document.getElementById("solidColorWrap");
const solidColorInput = document.getElementById("solidColorInput");
const solidSwatchPreview = document.getElementById("solidSwatchPreview");
const samplingWrap = document.getElementById("samplingWrap");
const sampleEvery = document.getElementById("sampleEvery");
const sampleValueLabel = document.getElementById("sampleValueLabel");
const videoWrap = document.getElementById("videoWrap");
const previewVideo = document.getElementById("previewVideo");
const previewVideoLabel = document.getElementById("previewVideoLabel");
const downloadResultBtn = document.getElementById("downloadResultBtn");
const copyResultBtn = document.getElementById("copyResultBtn");
let currentImage = null;
let currentFile = null;
let lastResult = null;
let mode = null;
sampleEvery.addEventListener("input", () => {
sampleValueLabel.textContent = sampleEvery.value === "1" ? "every frame" : `every ${sampleEvery.value} frames`;
});
function setDropState(active) {
previewPanel.classList.toggle("drag", active);
}
function collectDroppedFiles(event) {
const dt = event.dataTransfer;
let files = [];
if (dt.files && dt.files.length) files = Array.from(dt.files);
else if (dt.items && dt.items.length) for (const item of dt.items) { if (item.kind === "file") { const f = item.getAsFile(); if (f) files.push(f); } }
return files;
}
["dragover", "drop"].forEach(evt => window.addEventListener(evt, (e) => e.preventDefault()));
["dragenter", "dragover"].forEach(evt => previewPanel.addEventListener(evt, (e) => { e.preventDefault(); e.stopPropagation(); setDropState(true); }));
["dragleave", "dragend"].forEach(evt => previewPanel.addEventListener(evt, (e) => { e.preventDefault(); e.stopPropagation(); setDropState(false); }));
previewPanel.addEventListener("drop", (e) => {
e.preventDefault(); e.stopPropagation();
setDropState(false);
const files = collectDroppedFiles(e);
if (!files.length) { setStatus("That drop didn't contain an actual file. Try dragging from your file explorer, or click to choose instead.", "error"); return; }
loadFiles(files);
});
previewBrowseBtn.addEventListener("click", (e) => { e.stopPropagation(); fileInput.click(); });
previewPanel.addEventListener("click", (e) => {
if (e.target.closest(".preview-toolbar") || e.target.closest(".btn")) return;
if (!currentFile && !currentImage && !previewVideo.dataset.currentUrl) fileInput.click();
});
fileInput.addEventListener("change", (e) => { if (e.target.files.length) loadFiles(Array.from(e.target.files)); fileInput.value = ""; });
previewVideo.addEventListener('loadeddata', () => updateSaveAvailability());
previewVideo.addEventListener('emptied', () => updateSaveAvailability());
function showImageUI() {
mode = "image";
hideVideoPreview();
canvasWrap.style.display = "flex";
canvasPlaceholder.style.display = "none";
showAllWrap.style.display = "flex";
logCard.style.display = "block";
}
const logCard = document.getElementById("logCard");
const frameModalOverlay = document.getElementById("frameModalOverlay");
const frameModalFileName = document.getElementById("frameModalFileName");
const frameModalInput = document.getElementById("frameModalInput");
const frameStepDown = document.getElementById("frameStepDown");
const frameStepUp = document.getElementById("frameStepUp");
const frameModalPresets = document.getElementById("frameModalPresets");
const frameModalCancel = document.getElementById("frameModalCancel");
const frameModalConfirm = document.getElementById("frameModalConfirm");
function markActivePreset(val) {
frameModalPresets.querySelectorAll(".preset-chip").forEach(chip => {
chip.classList.toggle("active", Number(chip.dataset.val) === Number(val));
});
}
function askFrameRate(fileName, defaultVal) {
return new Promise((resolve) => {
frameModalFileName.textContent = `Run detection every how many frames for "${fileName}"?`;
frameModalInput.value = defaultVal;
markActivePreset(defaultVal);
frameModalOverlay.style.display = "flex";
frameModalInput.focus();
frameModalInput.select();
function cleanup() {
frameModalOverlay.style.display = "none";
frameModalOverlay.removeEventListener("click", onOverlayClick);
frameModalConfirm.removeEventListener("click", onConfirm);
frameModalCancel.removeEventListener("click", onCancel);
frameStepUp.removeEventListener("click", onStepUp);
frameStepDown.removeEventListener("click", onStepDown);
frameModalPresets.removeEventListener("click", onPresetClick);
frameModalInput.removeEventListener("keydown", onKeydown);
document.removeEventListener("keydown", onEscape);
}
function currentValue() {
const parsed = parseInt(frameModalInput.value, 10);
return Number.isFinite(parsed) && parsed > 0 ? parsed : defaultVal;
}
function onConfirm() { const v = currentValue(); cleanup(); resolve(v); }
function onCancel() { cleanup(); resolve(null); }
function onOverlayClick(e) { if (e.target === frameModalOverlay) onCancel(); }
function onStepUp() { frameModalInput.value = currentValue() + 1; markActivePreset(-1); }
function onStepDown() { frameModalInput.value = Math.max(1, currentValue() - 1); markActivePreset(-1); }
function onPresetClick(e) {
const chip = e.target.closest(".preset-chip");
if (!chip) return;
frameModalInput.value = chip.dataset.val;
markActivePreset(chip.dataset.val);
}
function onKeydown(e) { if (e.key === "Enter") onConfirm(); }
function onEscape(e) { if (e.key === "Escape") onCancel(); }
frameModalOverlay.addEventListener("click", onOverlayClick);
frameModalConfirm.addEventListener("click", onConfirm);
frameModalCancel.addEventListener("click", onCancel);
frameStepUp.addEventListener("click", onStepUp);
frameStepDown.addEventListener("click", onStepDown);
frameModalPresets.addEventListener("click", onPresetClick);
frameModalInput.addEventListener("keydown", onKeydown);
document.addEventListener("keydown", onEscape);
frameModalInput.addEventListener("input", () => markActivePreset(-1));
});
}
function loadFiles(files) {
const videoFiles = files.filter(f => f.type && f.type.startsWith("video/"));
const imageFiles = files.filter(f => !f.type || f.type.startsWith("image/"));
const otherFiles = files.filter(f => f.type && !f.type.startsWith("video/") && !f.type.startsWith("image/"));
if (otherFiles.length) setStatus(`Skipped ${otherFiles.length} file(s) — only images and mp4 video are supported.`, "error");
const badVideos = videoFiles.filter(f => f.type !== "video/mp4");
const goodVideos = videoFiles.filter(f => f.type === "video/mp4");
if (badVideos.length) setStatus("Only mp4 video is supported for now (skipped non-mp4 video file(s)).", "error");
goodVideos.forEach(f => addVideoJob(f));
if (imageFiles.length) {
if (imageFiles.length > 1) setStatus(`Loaded the first of ${imageFiles.length} images — images are handled one at a time; drop videos to batch-process multiple at once.`, "info");
loadImageFile(imageFiles[0]);
}
}
function loadImageFile(file) {
currentFile = file;
const img = new Image();
img.onload = () => {
currentImage = img;
lastResult = null;
showImageUI();
applyPreBlurState();
setAnalyzeEnabled(true);
setResultActionsEnabled(false);
setStatus(
preBlurToggle.checked
? `Loaded ${file.name} (${img.width}×${img.height}) — blurred until scanned. Click "Analyze & censor" when ready.`
: `Loaded ${file.name} (${img.width}×${img.height}).`,
"info"
);
clearLog();
};
img.onerror = () => setStatus("Could not read that file as an image.", "error");
img.src = URL.createObjectURL(file);
}
function drawImageOnly(img) {
canvas.width = img.width;
canvas.height = img.height;
canvas.style.maxWidth = "100%";
canvas.style.maxHeight = "100%";
canvas.style.objectFit = "contain";
canvasWrap.style.height = "100%";
canvasWrap.style.display = "flex";
canvasWrap.style.alignItems = "center";
canvasWrap.style.justifyContent = "center";
canvasWrap.style.overflow = "hidden";
ctx.drawImage(img, 0, 0);
canvasPlaceholder.style.display = "none";
}
function applyPreBlurState() {
drawImageOnly(currentImage);
if (preBlurToggle.checked) {
ctx.save();
ctx.filter = "blur(26px)";
ctx.drawImage(currentImage, 0, 0, canvas.width, canvas.height);
ctx.restore();
}
}
preBlurToggle.addEventListener("change", () => {
if (currentImage && mode === "image" && !lastResult) applyPreBlurState();
});
function setStatus(msg, cls) {
statusMsg.textContent = msg;
statusMsg.className = "status-line " + (cls || "");
}
function setAnalyzeEnabled(enabled) {
analyzeBtn.disabled = !enabled;
}
function setResultActionsEnabled(enabled) {
downloadResultBtn.disabled = !enabled;
copyResultBtn.disabled = !enabled;
}
function setAnalyzing(isAnalyzing, label) {
if (isAnalyzing) {
analyzeBtn.disabled = true;
analyzeLabel.textContent = label || "Scanning…";
} else {
analyzeLabel.textContent = "Analyze & censor";
setAnalyzeEnabled(!!currentFile);
}
}
analyzeBtn.addEventListener("click", async () => { if (currentFile) await analyzeImage(); });
const MAX_DETECT_DIM = 1600;
function prepareDetectUpload(img, file) {
return new Promise((resolve) => {
const maxSide = Math.max(img.width, img.height);
if (maxSide <= MAX_DETECT_DIM) {
resolve({ blob: file, scale: 1 });
return;
}
const factor = MAX_DETECT_DIM / maxSide;
const w = Math.max(1, Math.round(img.width * factor));
const h = Math.max(1, Math.round(img.height * factor));
const off = document.createElement("canvas");
off.width = w; off.height = h;
off.getContext("2d").drawImage(img, 0, 0, w, h);
off.toBlob((blob) => {
if (!blob) { resolve({ blob: file, scale: 1 }); return; }
resolve({ blob, scale: maxSide / Math.max(w, h) });
}, "image/jpeg", 0.87);
});
}
async function analyzeImage() {
setStatus("Analyzing…", "info");
setAnalyzing(true, "Scanning image…");
try {
const { blob, scale } = await prepareDetectUpload(currentImage, currentFile);
const formData = new FormData();
formData.append("image", blob, currentFile.name || "photo.jpg");
const res = await fetch(apiUrl("/detect"), { method: "POST", body: formData, headers: NGROK_HEADER });
if (!res.ok) { const err = await res.json().catch(() => ({})); throw new Error(err.error || `Server returned ${res.status}`); }
const data = await res.json();
if (scale !== 1) data.all_detections.forEach(d => { d.box = d.box.map(v => v * scale); });
lastResult = data;
renderResult(data);
setResultActionsEnabled(true);
updateSaveAvailability();
} catch (err) {
setStatus("Error: " + err.message + " — is your sandbox still paired?", "error");
} finally {
setAnalyzing(false);
}
}
const STATUS_LABELS = {
queued: "Queued…",
decoding: "Decoding video frames",
queued_for_gpu: "Waiting for a GPU slot",
detecting: "Running detection",
censoring: "Applying censor to frames",
writing: "Writing frames",
encoding: "Encoding final mp4",
};
let jobCounter = 0;
async function addVideoJob(file) {
const localId = "job" + (++jobCounter);
const defaultSample = sampleEvery.value;
const answer = await askFrameRate(file.name, defaultSample);
if (answer === null) { setStatus(`Skipped "${file.name}" — cancelled.`, "info"); return; }
const sampleEveryVal = answer;
const style = currentStyle();
const solidColor = solidColorInput.value;
const categories = collectCategories().join(",");
videoQueuePanel.style.display = "block";
const card = document.createElement("div");
card.className = "queue-card";
card.dataset.localId = localId;
card.innerHTML = `
<div style="display:flex; justify-content:space-between; gap:8px;">
<span class="queue-name" title="${file.name}">${file.name}</span>
<span class="muted-tag" data-role="count"></span>
</div>
<div data-role="progressWrap">
<div class="status-line info" data-role="label" style="margin-top:8px">Queued… (every ${sampleEveryVal} frames)</div>
<div class="progress-bar"><div class="progress-fill" style="width:0%" data-role="bar"></div></div>
</div>
<button data-role="changeBtn" class="btn btn-accent btn-block" style="display:none; margin-top:10px;">Change</button>
<div class="status-line error" data-role="errorMsg" style="display:none"></div>
`;
videoQueueList.prepend(card);
const els = {
label: card.querySelector('[data-role="label"]'),
count: card.querySelector('[data-role="count"]'),
bar: card.querySelector('[data-role="bar"]'),
progressWrap: card.querySelector('[data-role="progressWrap"]'),
changeBtn: card.querySelector('[data-role="changeBtn"]'),
errorMsg: card.querySelector('[data-role="errorMsg"]'),
};
runVideoJob(file, style, sampleEveryVal, categories, els, localId, card, solidColor);
}
function collectCategories() {
const cats = [];
if (censorGenitals.checked) cats.push("genitals");
if (censorBreasts.checked) cats.push("breasts");
if (censorButtocks.checked) cats.push("buttocks");
if (censorFeet.checked) cats.push("feet");
if (censorFace.checked) cats.push("face");
if (censorBelly.checked) cats.push("belly");
if (censorArmpits.checked) cats.push("armpits");
return cats;
}
function updateJobProgressUI(els, status, current, total) {
els.label.textContent = STATUS_LABELS[status] || status;
if (total > 1) { els.count.textContent = `${current} / ${total} frames`; els.bar.style.width = Math.min(100, Math.round((current / total) * 100)) + "%"; }
else if (current > 0) { els.count.textContent = `${current} frames so far`; els.bar.style.width = "100%"; }
else { els.count.textContent = ""; els.bar.style.width = "0%"; }
}
async function runVideoJob(file, style, sampleEveryVal, categories, els, localId, cardEl, solidColor) {
const formData = new FormData();
formData.append("video", file);
formData.append("sample_every", sampleEveryVal);
formData.append("style", style);
formData.append("censor_style", style);
formData.append("style_name", style.replace("-", "_"));
formData.append("categories", categories);
formData.append("solid_color", solidColor || "#000000");
try {
const startRes = await fetch(apiUrl("/start_video_job"), { method: "POST", body: formData, headers: NGROK_HEADER });
if (!startRes.ok) { const err = await startRes.json().catch(() => ({})); throw new Error(err.error || `Server returned ${startRes.status}`); }
const { job_id } = await startRes.json();
let done = false;
while (!done) {
await new Promise(r => setTimeout(r, 500));
const progRes = await fetch(apiUrl(`/video_progress/${job_id}`), { headers: NGROK_HEADER });
if (!progRes.ok) throw new Error("lost track of the processing job");
const prog = await progRes.json();
if (prog.status === "error") throw new Error(prog.error || "processing failed");
updateJobProgressUI(els, prog.status, prog.current, prog.total);
if (prog.status === "done") done = true;
}
const resultRes = await fetch(apiUrl(`/video_result/${job_id}`), { headers: NGROK_HEADER });
if (!resultRes.ok) { const err = await resultRes.json().catch(() => ({})); throw new Error(err.error || `Server returned ${resultRes.status}`); }
const blob = await resultRes.blob();
const url = URL.createObjectURL(blob);
els.progressWrap.style.display = "none";
els.changeBtn.style.display = "block";
cardEl.classList.add("done");
const job = { localId, name: file.name, url, cardEl };
els.changeBtn.addEventListener("click", () => selectVideoJob(job));
const saveBtn = document.createElement("button");
saveBtn.className = "btn btn-ghost";
saveBtn.style.padding = "8px";
saveBtn.textContent = "Save";
saveBtn.addEventListener("click", async () => {
try {
const res = await fetch(url);
const b = await res.blob();
await saveBlobToCache(b, file.name);
setStatus(`Saved "${file.name}" to Saved items.`, "ok");
updateSavedList();
} catch (e) { setStatus("Save failed: " + e.message, "error"); }
});
cardEl.appendChild(saveBtn);
} catch (err) {
els.label.textContent = "Failed";
els.errorMsg.textContent = err.message + " — is your sandbox still paired?";
els.errorMsg.style.display = "block";
}
}
async function saveBlobToCache(blob, filename) {
try {
const cache = await caches.open('censor-saved');
const id = Date.now() + '-' + (filename || 'item');
const req = new Request('https://censor.local/saved/' + id);
const headers = new Headers({ 'Content-Type': blob.type, 'X-Filename': filename });
const resp = new Response(blob, { headers });
await cache.put(req, resp);
return id;
} catch (e) { throw e; }
}
async function updateSavedList() {
try {
savedList.innerHTML = '';
const cache = await caches.open('censor-saved');
const keys = await cache.keys();
if (!keys.length) {
savedList.innerHTML = '<div class="step-fine">No saved items yet.</div>';
return;
}
for (const req of keys.reverse()) {
const res = await cache.match(req);
if (!res) continue;
const blob = await res.blob();
const fname = res.headers.get('X-Filename') || req.url.split('/').pop();
const url = URL.createObjectURL(blob);
const item = document.createElement('div');
item.className = 'queue-card';
item.style.display = 'flex';
item.style.gap = '8px';
item.style.alignItems = 'center';
item.innerHTML = `<div style="flex:1; min-width:0"><div style="font-weight:600;">${fname}</div></div>`;
const loadBtn = document.createElement('button'); loadBtn.className = 'btn btn-ghost'; loadBtn.textContent = 'Open';
loadBtn.addEventListener('click', () => {
if (blob.type.startsWith('image/')) {
loadSavedImage(blob, fname);
} else if (blob.type.startsWith('video/')) {
const job = { localId: 'saved-'+Date.now(), name: fname, url };
selectVideoJob(job);
}
});
const dlBtn = document.createElement('button'); dlBtn.className = 'btn btn-ghost'; dlBtn.textContent = 'Download';
dlBtn.addEventListener('click', () => {
const a = document.createElement('a'); a.href = url; a.download = fname; document.body.appendChild(a); a.click(); a.remove();
});
const delBtn = document.createElement('button'); delBtn.className = 'btn btn-ghost'; delBtn.textContent = 'Delete';
delBtn.addEventListener('click', async () => { await cache.delete(req); updateSavedList(); });
item.appendChild(loadBtn); item.appendChild(dlBtn); item.appendChild(delBtn);
savedList.appendChild(item);
}
} catch (e) { console.error(e); }
}
function loadSavedImage(blob, filename) {
const img = new Image();
img.onload = () => {
currentImage = img; currentFile = null; lastResult = null; showImageUI(); drawImageOnly(img); setResultActionsEnabled(true); setStatus(`Opened saved image ${filename}`, 'ok');
updateSaveAvailability();
};
img.src = URL.createObjectURL(blob);
}
if (toggleQueueBtn) toggleQueueBtn.addEventListener('click', () => {
const collapsed = videoQueueBody.style.display === 'none';
videoQueueBody.style.display = collapsed ? 'flex' : 'none';
toggleQueueBtn.textContent = collapsed ? '▾' : '▸';
});
if (tabQueueBtn && tabSavedBtn) {
tabQueueBtn.addEventListener('click', () => { videoQueueList.style.display = ''; savedList.style.display = 'none'; });
tabSavedBtn.addEventListener('click', () => { videoQueueList.style.display = 'none'; savedList.style.display = ''; updateSavedList(); });
}
if (saveResultBtn) {
saveResultBtn.addEventListener('click', async () => {
try {
if (mode === 'image' && canvas) {
canvas.toBlob(async (blob) => { if (!blob) return; const name = (currentFile && currentFile.name) ? currentFile.name.replace(/\.[^.]+$/, '') + '-censored.png' : 'censored.png'; await saveBlobToCache(blob, name); setStatus('Saved image to Saved items.', 'ok'); updateSavedList(); });
} else if (mode === 'video' && previewVideo && previewVideo.dataset.currentUrl) {
const res = await fetch(previewVideo.dataset.currentUrl || previewVideo.src);
const b = await res.blob();
await saveBlobToCache(b, previewVideoLabel.textContent || 'video.mp4');
setStatus('Saved video to Saved items.', 'ok'); updateSavedList();
}
} catch (e) { setStatus('Save failed: ' + e.message, 'error'); }
});
}
function updateSaveAvailability() {
if (!saveResultBtn) return;
saveResultBtn.disabled = !( (mode === 'image' && lastResult) || (mode === 'video' && previewVideo && (previewVideo.dataset.currentUrl || previewVideo.src)) );
}
function hideVideoPreview() { videoWrap.style.display = "none"; previewVideo.pause(); }
function selectVideoJob(job) {
mode = "video";
canvasWrap.style.display = "none";
canvasPlaceholder.style.display = "none";
showAllWrap.style.display = "none";
logCard.style.display = "none";
setResultActionsEnabled(false);
videoWrap.style.display = "flex";
videoWrap.style.alignItems = "center";
videoWrap.style.justifyContent = "center";
videoWrap.style.overflow = "hidden";
previewVideo.style.maxWidth = "100%";
previewVideo.style.maxHeight = "100%";
previewVideo.style.objectFit = "contain";
previewVideoLabel.textContent = job.name;
if (previewVideo.dataset.currentUrl !== job.url) {
previewVideo.pause(); previewVideo.autoplay = false;
previewVideo.src = job.url; previewVideo.dataset.currentUrl = job.url; previewVideo.load();
}
document.querySelectorAll('#videoQueueList [data-local-id]').forEach(el => el.style.outline = el.dataset.localId === job.localId ? `2px solid var(--accent)` : "none");
setStatus(`Showing "${job.name}" in the preview.`, "ok");
updateSaveAvailability();
}
function activeClasses() {
const classes = [];
if (censorGenitals.checked) classes.push(...GENITAL_ANUS_CLASSES);
if (censorBreasts.checked) classes.push(...BREAST_CLASSES);
if (censorButtocks.checked) classes.push(...BUTTOCKS_CLASSES);
if (censorFeet.checked) classes.push(...FEET_CLASSES);
if (censorFace.checked) classes.push(...FACE_CLASSES);
if (censorBelly.checked) classes.push(...BELLY_CLASSES);
if (censorArmpits.checked) classes.push(...ARMPITS_CLASSES);
return classes;
}
function currentStyle() {
const el = document.querySelector('input[name="style"]:checked');
return el ? el.value : "blur";
}
function updateSwatchSelection() {
styleRadios.forEach(radio => {
const swatch = radio.closest(".swatch");
if (swatch) swatch.classList.toggle("is-selected", radio.checked);
});
}
function applyStyleToRegion(rawStyle, box) {
const s = (rawStyle || "").toLowerCase().trim().replace(/_/g, "-");
if (s.includes("pixel")) return pixelateRegion(box);
if (s.includes("frost")) return frostedRegion(box);
if (s === "smudge") return smudgeRegion(box, solidColorInput.value);
if (s === "cover") return coverRegion(box, solidColorInput.value);
if (s === "box" || s === "black-box" || s === "blackbox") return blackBoxRegion(box);
if (s.includes("solid")) return solidFillRegion(box, solidColorInput.value);
if (s === "outline") return outlineRegion(box);
if (s === "glitch") return glitchRegion(box);
if (s === "rainbow") return rainbowRegion(box);
if (s === "dots") return dotsRegion(box);
if (s === "scanline") return scanlineRegion(box);
if (s === "negative") return negativeRegion(box);
if (s === "emboss") return embossRegion(box);
if (s === "soft-blur" || s === "soft") return blurRegion(box, 12);
return blurRegion(box);
}
function renderResult(data) {
drawImageOnly(currentImage);
const wanted = activeClasses();
const boxesToCensor = data.all_detections.filter(d => wanted.includes(d.class));
const style = currentStyle();
boxesToCensor.forEach(det => applyStyleToRegion(style, det.box));
if (showAllToggle.checked) data.all_detections.forEach(det => drawBoxOutline(det.box, det.class, boxesToCensor.includes(det)));
setStatus(boxesToCensor.length === 0 ? "No selected regions detected — nothing to censor." : `Detected & censored ${boxesToCensor.length} region(s).`, "ok");
populateLog(data, boxesToCensor);
}
function clampBox([x, y, w, h]) {
x = Math.max(0, Math.floor(x)); y = Math.max(0, Math.floor(y));
w = Math.min(Math.ceil(w), canvas.width - x); h = Math.min(Math.ceil(h), canvas.height - y);
return [x, y, w, h];
}
function blackBoxRegion(box) { const [x, y, w, h] = clampBox(box); if (w <= 0 || h <= 0) return; ctx.fillStyle = "#000"; ctx.fillRect(x, y, w, h); }
function solidFillRegion(box, color) { const [x, y, w, h] = clampBox(box); if (w <= 0 || h <= 0) return; ctx.fillStyle = color || "#000000"; ctx.fillRect(x, y, w, h); }
function blurRegion(box, radius = 18) {
const [x, y, w, h] = clampBox(box); if (w <= 0 || h <= 0) return;
const pad = radius * 2;
const sx = Math.max(0, x - pad), sy = Math.max(0, y - pad);
const ex = Math.min(canvas.width, x + w + pad), ey = Math.min(canvas.height, y + h + pad);
const sw = ex - sx, sh = ey - sy;
const off = document.createElement("canvas"); off.width = sw; off.height = sh;
const offCtx = off.getContext("2d");
offCtx.filter = `blur(${radius}px)`;
offCtx.drawImage(currentImage, sx, sy, sw, sh, 0, 0, sw, sh);
ctx.drawImage(off, x - sx, y - sy, w, h, x, y, w, h);
}
function pixelateRegion(box) {
const [x, y, w, h] = clampBox(box); if (w <= 0 || h <= 0) return;
const blockSize = Math.max(6, Math.round(Math.min(w, h) / 9));
const smallW = Math.max(1, Math.round(w / blockSize));
const smallH = Math.max(1, Math.round(h / blockSize));
const off = document.createElement("canvas");
off.width = smallW; off.height = smallH;
off.getContext("2d").drawImage(currentImage, x, y, w, h, 0, 0, smallW, smallH);
ctx.save();
ctx.imageSmoothingEnabled = false;
ctx.drawImage(off, 0, 0, smallW, smallH, x, y, w, h);
ctx.restore();
}
function frostedRegion(box) {
const [x, y, w, h] = clampBox(box); if (w <= 0 || h <= 0) return;
blurRegion(box, 32);
ctx.save();
ctx.fillStyle = "rgba(233, 236, 242, 0.32)";
ctx.fillRect(x, y, w, h);
ctx.restore();
}
function smudgeRegion(box, color) {
const [x, y, w, h] = clampBox(box); if (w <= 0 || h <= 0) return;
const off = document.createElement("canvas");
off.width = w; off.height = h;
const offCtx = off.getContext("2d");
offCtx.filter = "blur(2px)";
offCtx.drawImage(currentImage, x, y, w, h, 0, 0, w, h);
offCtx.filter = "none";
ctx.clearRect(x, y, w, h);
ctx.drawImage(off, 0, 0, w, h, x, y, w, h);
ctx.save();
ctx.globalAlpha = 0.3;
ctx.fillStyle = color || "#0b0d14";
ctx.fillRect(x, y, w, h);
ctx.restore();
}
function coverRegion(box, color) {
const [x, y, w, h] = clampBox(box); if (w <= 0 || h <= 0) return;
ctx.save();
ctx.fillStyle = color || "#0b0d14";
ctx.globalAlpha = 0.82;
ctx.fillRect(x, y, w, h);
ctx.globalAlpha = 1;
ctx.strokeStyle = "rgba(255,255,255,0.14)";
ctx.lineWidth = 1;
ctx.strokeRect(x + 0.5, y + 0.5, w - 1, h - 1);
ctx.restore();
}
function outlineRegion(box) {
const [x, y, w, h] = clampBox(box); if (w <= 0 || h <= 0) return;
ctx.save();
ctx.strokeStyle = "rgba(75, 216, 201, 0.95)";
ctx.lineWidth = 3;
ctx.setLineDash([7, 6]);
ctx.strokeRect(x, y, w, h);
ctx.restore();
}
function glitchRegion(box) {
const [x, y, w, h] = clampBox(box); if (w <= 0 || h <= 0) return;
const slices = 5;
for (let i = 0; i < slices; i++) {
const sliceHeight = Math.max(4, Math.round(h / slices));
const sy = y + i * sliceHeight;
const dy = sy + (i % 2 === 0 ? 2 : -2);
const sw = w;
const sh = Math.min(sliceHeight, y + h - sy);
const off = document.createElement('canvas');
off.width = sw;
off.height = sh;
const offCtx = off.getContext('2d');
offCtx.drawImage(currentImage, x, sy, sw, sh, 0, 0, sw, sh);
offCtx.globalCompositeOperation = 'source-atop';
offCtx.fillStyle = i % 2 === 0 ? 'rgba(239,93,111,0.18)' : 'rgba(75,216,201,0.18)';
offCtx.fillRect(0, 0, sw, sh);
ctx.drawImage(off, x + (i % 2 === 0 ? 4 : -4), dy, sw, sh);
}
ctx.save();
ctx.strokeStyle = 'rgba(255,255,255,0.15)';
ctx.lineWidth = 2;
ctx.strokeRect(x + 1, y + 1, w - 2, h - 2);
ctx.restore();
}
function rainbowRegion(box) {
const [x, y, w, h] = clampBox(box); if (w <= 0 || h <= 0) return;
const grd = ctx.createLinearGradient(x, y, x + w, y + h);
grd.addColorStop(0, '#ff4d6d');
grd.addColorStop(0.2, '#f7d03f');
grd.addColorStop(0.4, '#4ad9ff');
grd.addColorStop(0.6, '#7c6bff');
grd.addColorStop(0.8, '#84ff7c');
grd.addColorStop(1, '#ff4d6d');
ctx.save();
ctx.fillStyle = grd;
ctx.fillRect(x, y, w, h);
ctx.globalCompositeOperation = 'overlay';
ctx.drawImage(currentImage, x, y, w, h, x, y, w, h);
ctx.restore();
}
function dotsRegion(box) {
const [x, y, w, h] = clampBox(box); if (w <= 0 || h <= 0) return;
ctx.save();
ctx.fillStyle = '#121b2a';
ctx.fillRect(x, y, w, h);
ctx.fillStyle = 'rgba(75,216,201,0.82)';
const step = Math.max(7, Math.round(Math.min(w, h) / 10));
for (let py = y; py < y + h; py += step) {
for (let px = x; px < x + w; px += step) {
ctx.beginPath();
ctx.arc(px + step * 0.45, py + step * 0.45, step * 0.22, 0, Math.PI * 2);
ctx.fill();
}
}
ctx.restore();