Manar55 commited on
Commit
7c8c4fc
·
verified ·
1 Parent(s): df96bb0

Deploy 59dbd9a

Browse files
app.py CHANGED
@@ -654,7 +654,7 @@ _LETTER_SYNC = r"""
654
 
655
 
656
  def _with_status(html):
657
- extra = '<script src="/ts-viewer.js"></script><script src="/ts-gps.js"></script>' + _STATUS_WIDGET + _PLATE_PICKER + _LETTER_SYNC
658
  i = html.lower().rfind("</body>")
659
  return html[:i] + extra + html[i:] if i != -1 else html + extra
660
 
@@ -973,6 +973,13 @@ def gps_endpoint():
973
  pass
974
 
975
 
 
 
 
 
 
 
 
976
  @app.route("/ts-gps.js")
977
  def ts_gps_js():
978
  path = os.path.join(app.root_path, "templates", "ts-gps.js")
 
654
 
655
 
656
  def _with_status(html):
657
+ extra = '<script src="/ts-viewer.js"></script><script src="/ts-gps.js"></script><script src="/ts-ela.js"></script>' + _STATUS_WIDGET + _PLATE_PICKER + _LETTER_SYNC
658
  i = html.lower().rfind("</body>")
659
  return html[:i] + extra + html[i:] if i != -1 else html + extra
660
 
 
973
  pass
974
 
975
 
976
+ @app.route("/ts-ela.js")
977
+ def ts_ela_js():
978
+ path = os.path.join(app.root_path, "templates", "ts-ela.js")
979
+ with open(path, "r", encoding="utf-8") as f:
980
+ return f.read(), 200, {"Content-Type": "application/javascript; charset=utf-8", "Cache-Control": "no-cache"}
981
+
982
+
983
  @app.route("/ts-gps.js")
984
  def ts_gps_js():
985
  path = os.path.join(app.root_path, "templates", "ts-gps.js")
templates/enhance.html CHANGED
@@ -145,7 +145,7 @@ button:disabled{opacity:.45;cursor:default}
145
  <span id="pickCount">0/4</span>
146
  <span class="persp-btns" style="display:inline-flex"><button id="pickUndo" data-i18n="undo">تراجع</button><button id="pickCancel" data-i18n="cancel">إلغاء</button></span></div>
147
  <input type="range" id="cmpRange" min="0" max="100" value="50" dir="ltr">
148
- <div class="btns"><button id="zoomBtn" data-i18n="zoom">تكبير</button><button id="loupeBtn" data-i18n="loupe">المجهر</button><button id="another" data-i18n="another">ملف آخر</button><button id="backVideo" style="display:none" data-i18n="backVideo">العودة إلى الفيديو</button></div>
149
  <div class="meta" id="meta"></div>
150
  </div>
151
  </section>
@@ -153,6 +153,7 @@ button:disabled{opacity:.45;cursor:default}
153
 
154
  <script src="/ts-viewer.js"></script>
155
  <script src="/ts-gps.js"></script>
 
156
  <script>
157
 
158
  // ---------------- Language (follows the main app: ?lang=ar|en) ----------------
@@ -369,6 +370,8 @@ $('cmpRange').oninput=e=>setCmp(e.target.value);
369
  // zoom viewer + magnifier (enlarges the spot under the finger without changing the image)
370
  let loupe=null;
371
  $('zoomBtn').onclick=()=>{ if(window.tsZoom) window.tsZoom($('after').src); };
 
 
372
  $('loupeBtn').onclick=()=>{
373
  if(!window.tsLoupe) return;
374
  if(!loupe) loupe=window.tsLoupe($('cmp'),$('after'),3);
 
145
  <span id="pickCount">0/4</span>
146
  <span class="persp-btns" style="display:inline-flex"><button id="pickUndo" data-i18n="undo">تراجع</button><button id="pickCancel" data-i18n="cancel">إلغاء</button></span></div>
147
  <input type="range" id="cmpRange" min="0" max="100" value="50" dir="ltr">
148
+ <div class="btns"><button id="zoomBtn" data-i18n="zoom">تكبير</button><button id="elaBtn">ELA</button><button id="loupeBtn" data-i18n="loupe">المجهر</button><button id="another" data-i18n="another">ملف آخر</button><button id="backVideo" style="display:none" data-i18n="backVideo">العودة إلى الفيديو</button></div>
149
  <div class="meta" id="meta"></div>
150
  </div>
151
  </section>
 
153
 
154
  <script src="/ts-viewer.js"></script>
155
  <script src="/ts-gps.js"></script>
156
+ <script src="/ts-ela.js"></script>
157
  <script>
158
 
159
  // ---------------- Language (follows the main app: ?lang=ar|en) ----------------
 
370
  // zoom viewer + magnifier (enlarges the spot under the finger without changing the image)
371
  let loupe=null;
372
  $('zoomBtn').onclick=()=>{ if(window.tsZoom) window.tsZoom($('after').src); };
373
+ // ELA on the ORIGINAL picture (the enhanced one would only show the filters)
374
+ $('elaBtn').onclick=()=>{ if(window.tsEla) window.tsEla($('before').src); };
375
  $('loupeBtn').onclick=()=>{
376
  if(!window.tsLoupe) return;
377
  if(!loupe) loupe=window.tsLoupe($('cmp'),$('after'),3);
templates/forensics.html CHANGED
@@ -130,6 +130,7 @@ input[type=range]{width:100%}
130
  </main>
131
  <script src="/ts-viewer.js"></script>
132
  <script src="/ts-gps.js"></script>
 
133
  <script>
134
  const P=new URLSearchParams(location.search);
135
  const LANG=P.get('lang')==='en'?'en':'ar';
@@ -145,7 +146,7 @@ const T={
145
  findings:'النتائج',maps:'الخرائط',zoomHint:'اضغط على الخريطة لتكبيرها',original:'الصورة الأصلية',
146
  details:'تفاصيل الضغط',quality:'جودة الحفظ التقديرية',stdTables:'جداول المكتبة القياسية',yes:'نعم',no:'لا',
147
  dqScore:'مؤشر الضغط المزدوج',format:'الصيغة',size:'الأبعاد',thumb:'الصورة المصغّرة داخل الملف',current:'الصورة الحالية',
148
- similarity:'التطابق',another:'صورة أخرى',
149
  gTitle:'منحنى أشباح JPEG',gHelp:'يُعاد حفظ الصورة بكل الجودات من 50 إلى 100 ويُقاس الفرق. الانخفاض الأعمق (أخضر) هو جودة آخر حفظ وهو متوقع؛ وأي انخفاض واضح آخر بجودة أقل (أحمر) يعني أن الصورة حُفظت قبل ذلك بتلك الجودة. الحفظ السابق بجودة أعلى من الأخيرة لا يظهر.',
150
  gWhole:'الصورة كاملة',gRegion:'المنطقة المحددة',gAxisQ:'الجودة',gLast:q=>`آخر حفظ ≈ ${q}`,gNoLast:'لم يتضح آخر حفظ',gPrev:q=>`حفظ سابق ≈ ${q}`,gNoPrev:'لا يظهر حفظ سابق',
151
  gMapTitle:'خريطة الأشباح',gMapHelp:'حرّك الشريط لاختيار الجودة. المناطق الحمراء فيها «شبح» عند هذه الجودة: إذا غطّى الصورة كلها فهي إعادة حفظ، وإذا ظهر على منطقة واحدة فقط فقد تكون ملصوقة من مصدر آخر.',
@@ -185,7 +186,7 @@ const T={
185
  findings:'Findings',maps:'Maps',zoomHint:'Tap a map to zoom',original:'Original image',
186
  details:'Compression details',quality:'Estimated save quality',stdTables:'Standard library tables',yes:'Yes',no:'No',
187
  dqScore:'Double-compression indicator',format:'Format',size:'Dimensions',thumb:'Thumbnail stored in the file',current:'Current picture',
188
- similarity:'Similarity',another:'Another image',
189
  gTitle:'JPEG ghost plot',gHelp:'The image is re-saved at every quality from 50 to 100 and the difference measured. The deepest dip (green) is the last save quality and is expected; another clear dip at a lower quality (red) means it was saved before at that quality. An earlier save at a higher quality does not show.',
190
  gWhole:'Whole image',gRegion:'Selected region',gAxisQ:'Quality',gLast:q=>`last save ≈ ${q}`,gNoLast:'last save unclear',gPrev:q=>`earlier save ≈ ${q}`,gNoPrev:'no earlier save visible',
191
  gMapTitle:'Ghost map',gMapHelp:'Move the slider to choose a quality. Red areas have a ghost at that quality: across the whole image it is a re-save; on one area only, that area may have been pasted from another source.',
@@ -282,7 +283,7 @@ function renderJ(d,url){
282
  let h=`<div class="card"><div class="verdict ${v[0]}"><div><b>${v[1]}</b></div></div></div>`;
283
  h+=`<div class="card"><h2>${T.findings}</h2>`+d.findings.map(f=>`<div class="f"><i style="background:${COL[f.level]}"></i><div>${esc(LANG==='en'?f.en:f.ar)}</div></div>`).join('')+`</div>`;
284
  h+=`<div class="card"><h2>${T.maps}</h2><div class="mut" style="margin-bottom:10px">${T.zoomHint}</div><div class="grid">`;
285
- h+=`<div class="map"><h3>${T.original}</h3><img src="${url}" data-z="${url}"></div>`;
286
  d.maps.forEach(m=>{h+=`<div class="map"><h3>${esc(LANG==='en'?m.en:m.ar)}</h3><img src="${m.image}" data-z="${m.image}"><div class="mut" style="margin-top:6px">${esc(LANG==='en'?m.help_en:m.help_ar)}</div></div>`;});
287
  h+=`</div></div>`;
288
  if(d.platform){
@@ -323,6 +324,7 @@ function renderJ(d,url){
323
  h+=`<div class="note">${T.noteJ}</div>`+againBtn();
324
  $('jOut').innerHTML=h; bindAgain();
325
  $('jOut').querySelectorAll('img[data-z]').forEach(i=>i.onclick=()=>window.tsZoom&&window.tsZoom(i.dataset.z));
 
326
  }
327
 
328
  // ---------- JPEG ghost plot ----------
 
130
  </main>
131
  <script src="/ts-viewer.js"></script>
132
  <script src="/ts-gps.js"></script>
133
+ <script src="/ts-ela.js"></script>
134
  <script>
135
  const P=new URLSearchParams(location.search);
136
  const LANG=P.get('lang')==='en'?'en':'ar';
 
146
  findings:'النتائج',maps:'الخرائط',zoomHint:'اضغط على الخريطة لتكبيرها',original:'الصورة الأصلية',
147
  details:'تفاصيل الضغط',quality:'جودة الحفظ التقديرية',stdTables:'جداول المكتبة القياسية',yes:'نعم',no:'لا',
148
  dqScore:'مؤشر الضغط المزدوج',format:'الصيغة',size:'الأبعاد',thumb:'الصورة المصغّرة داخل الملف',current:'الصورة الحالية',
149
+ similarity:'التطابق',another:'صورة أخرى',elaBtn:'تحليل مستوى الخطأ (ELA)',
150
  gTitle:'منحنى أشباح JPEG',gHelp:'يُعاد حفظ الصورة بكل الجودات من 50 إلى 100 ويُقاس الفرق. الانخفاض الأعمق (أخضر) هو جودة آخر حفظ وهو متوقع؛ وأي انخفاض واضح آخر بجودة أقل (أحمر) يعني أن الصورة حُفظت قبل ذلك بتلك الجودة. الحفظ السابق بجودة أعلى من الأخيرة لا يظهر.',
151
  gWhole:'الصورة كاملة',gRegion:'المنطقة المحددة',gAxisQ:'الجودة',gLast:q=>`آخر حفظ ≈ ${q}`,gNoLast:'لم يتضح آخر حفظ',gPrev:q=>`حفظ سابق ≈ ${q}`,gNoPrev:'لا يظهر حفظ سابق',
152
  gMapTitle:'خريطة الأشباح',gMapHelp:'حرّك الشريط لاختيار الجودة. المناطق الحمراء فيها «شبح» عند هذه الجودة: إذا غطّى الصورة كلها فهي إعادة حفظ، وإذا ظهر على منطقة واحدة فقط فقد تكون ملصوقة من مصدر آخر.',
 
186
  findings:'Findings',maps:'Maps',zoomHint:'Tap a map to zoom',original:'Original image',
187
  details:'Compression details',quality:'Estimated save quality',stdTables:'Standard library tables',yes:'Yes',no:'No',
188
  dqScore:'Double-compression indicator',format:'Format',size:'Dimensions',thumb:'Thumbnail stored in the file',current:'Current picture',
189
+ similarity:'Similarity',another:'Another image',elaBtn:'Error Level Analysis (ELA)',
190
  gTitle:'JPEG ghost plot',gHelp:'The image is re-saved at every quality from 50 to 100 and the difference measured. The deepest dip (green) is the last save quality and is expected; another clear dip at a lower quality (red) means it was saved before at that quality. An earlier save at a higher quality does not show.',
191
  gWhole:'Whole image',gRegion:'Selected region',gAxisQ:'Quality',gLast:q=>`last save ≈ ${q}`,gNoLast:'last save unclear',gPrev:q=>`earlier save ≈ ${q}`,gNoPrev:'no earlier save visible',
192
  gMapTitle:'Ghost map',gMapHelp:'Move the slider to choose a quality. Red areas have a ghost at that quality: across the whole image it is a re-save; on one area only, that area may have been pasted from another source.',
 
283
  let h=`<div class="card"><div class="verdict ${v[0]}"><div><b>${v[1]}</b></div></div></div>`;
284
  h+=`<div class="card"><h2>${T.findings}</h2>`+d.findings.map(f=>`<div class="f"><i style="background:${COL[f.level]}"></i><div>${esc(LANG==='en'?f.en:f.ar)}</div></div>`).join('')+`</div>`;
285
  h+=`<div class="card"><h2>${T.maps}</h2><div class="mut" style="margin-bottom:10px">${T.zoomHint}</div><div class="grid">`;
286
+ h+=`<div class="map"><h3>${T.original}</h3><img src="${url}" data-z="${url}"><button class="btn sec" style="margin-top:8px;width:100%" data-ela="${url}">${T.elaBtn}</button></div>`;
287
  d.maps.forEach(m=>{h+=`<div class="map"><h3>${esc(LANG==='en'?m.en:m.ar)}</h3><img src="${m.image}" data-z="${m.image}"><div class="mut" style="margin-top:6px">${esc(LANG==='en'?m.help_en:m.help_ar)}</div></div>`;});
288
  h+=`</div></div>`;
289
  if(d.platform){
 
324
  h+=`<div class="note">${T.noteJ}</div>`+againBtn();
325
  $('jOut').innerHTML=h; bindAgain();
326
  $('jOut').querySelectorAll('img[data-z]').forEach(i=>i.onclick=()=>window.tsZoom&&window.tsZoom(i.dataset.z));
327
+ $('jOut').querySelectorAll('[data-ela]').forEach(b=>b.onclick=()=>window.tsEla&&window.tsEla(b.dataset.ela));
328
  }
329
 
330
  // ---------- JPEG ghost plot ----------
templates/truescan.html CHANGED
@@ -1224,7 +1224,25 @@ function TrueScan() {
1224
  {mediaMode === "video" ? (lang === "ar" ? "فيديو جديد" : "New video") : t.reset}
1225
  </button>
1226
  )}
 
 
 
 
 
 
 
 
 
 
 
 
 
1227
  </div>
 
 
 
 
 
1228
  </div>
1229
  </div>
1230
  )}
@@ -2351,6 +2369,11 @@ function PlatePage({ theme, dark, lang, C }) {
2351
  color: theme.text, border: `1px solid ${theme.border}`, display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 6 }}>
2352
  <ZoomIcon size={15} /> {isAr ? "تكبير الصورة" : "Zoom image"}
2353
  </button>
 
 
 
 
 
2354
  <button className="ts-btn ts-focus" onClick={toggleLoupe}
2355
  style={{ flex: 1, padding: "9px 12px", borderRadius: 9, fontSize: 13, fontWeight: 700,
2356
  background: loupeOn ? C.primary : theme.cardAlt, color: loupeOn ? "#fff" : theme.text,
 
1224
  {mediaMode === "video" ? (lang === "ar" ? "فيديو جديد" : "New video") : t.reset}
1225
  </button>
1226
  )}
1227
+ <button className="ts-btn ts-focus" title="ELA"
1228
+ onClick={() => {
1229
+ if (!window.tsEla) return;
1230
+ if (mediaMode === "video") {
1231
+ const v = document.getElementById("ts-video-preview");
1232
+ const fr = v && window.tsVideoFrame ? window.tsVideoFrame(v) : null;
1233
+ if (fr) window.tsEla(fr);
1234
+ } else window.tsEla(file.url);
1235
+ }}
1236
+ style={{ background: theme.cardAlt, color: theme.text, border: `1px solid ${theme.border}`,
1237
+ padding: "12px 16px", borderRadius: 10, fontWeight: 700, fontSize: 14, flexShrink: 0 }}>
1238
+ ELA
1239
+ </button>
1240
  </div>
1241
+ {mediaMode === "video" && (
1242
+ <div style={{ gridColumn: "1 / -1", fontSize: 11.5, color: theme.subtext }}>
1243
+ {lang === "ar" ? "في الفيديو يُطبَّق ELA على اللقطة المعروضة حاليًا في المشغّل." : "For video, ELA runs on the frame currently shown in the player."}
1244
+ </div>
1245
+ )}
1246
  </div>
1247
  </div>
1248
  )}
 
2369
  color: theme.text, border: `1px solid ${theme.border}`, display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 6 }}>
2370
  <ZoomIcon size={15} /> {isAr ? "تكبير الصورة" : "Zoom image"}
2371
  </button>
2372
+ <button className="ts-btn ts-focus" onClick={() => window.tsEla && window.tsEla(file.url)}
2373
+ style={{ flex: 1, padding: "9px 12px", borderRadius: 9, fontSize: 13, fontWeight: 700, background: theme.cardAlt,
2374
+ color: theme.text, border: `1px solid ${theme.border}`, display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 6 }}>
2375
+ ELA
2376
+ </button>
2377
  <button className="ts-btn ts-focus" onClick={toggleLoupe}
2378
  style={{ flex: 1, padding: "9px 12px", borderRadius: 9, fontSize: 13, fontWeight: 700,
2379
  background: loupeOn ? C.primary : theme.cardAlt, color: loupeOn ? "#fff" : theme.text,
templates/ts-ela.js ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Error Level Analysis viewer, shared by every section.
2
+ window.tsEla(src) opens a full-screen panel: the picture is re-saved as
3
+ JPEG at a chosen quality (60-100) and compared with itself.
4
+ ELA - per-pixel difference, amplified
5
+ MSE - mean squared error per 8x8 block (heat map)
6
+ Areas edited after the last save usually stand out with an error level
7
+ different from similar surfaces around them. Runs entirely in the
8
+ browser; nothing is uploaded. */
9
+ (function () {
10
+ function en() { return document.documentElement.lang === 'en'; }
11
+ function T(ar, e) { return en() ? e : ar; }
12
+ var MAX = 2048;
13
+
14
+ function jet(v) { // 0..1 -> [r,g,b]
15
+ var r = Math.max(0, Math.min(1, 1.5 - Math.abs(4 * v - 3)));
16
+ var g = Math.max(0, Math.min(1, 1.5 - Math.abs(4 * v - 2)));
17
+ var b = Math.max(0, Math.min(1, 1.5 - Math.abs(4 * v - 1)));
18
+ return [r * 255, g * 255, b * 255];
19
+ }
20
+
21
+ window.tsEla = function (src) {
22
+ var ov = document.createElement('div');
23
+ ov.dir = en() ? 'ltr' : 'rtl';
24
+ ov.style.cssText = 'position:fixed;inset:0;z-index:100000;background:rgba(2,6,16,.97);color:#e6eeff;display:flex;flex-direction:column;' +
25
+ 'font:13.5px system-ui,Segoe UI,Tahoma,sans-serif;overflow:auto';
26
+ var btn = 'background:#1e293b;color:#e2e8f0;border:1px solid #334155;border-radius:10px;padding:8px 14px;font:inherit;font-weight:700;cursor:pointer';
27
+ ov.innerHTML =
28
+ '<div style="display:flex;align-items:center;justify-content:space-between;gap:10px;padding:12px 14px;border-bottom:1px solid #1e2b45">' +
29
+ '<div style="font-weight:800;font-size:15px">' + T('تحليل مستوى الخطأ (ELA)', 'Error Level Analysis (ELA)') + '</div>' +
30
+ '<button data-a="close" style="' + btn + '">' + T('إغلاق', 'Close') + '</button></div>' +
31
+ '<div style="padding:12px 14px;display:flex;flex-direction:column;gap:10px;max-width:1000px;width:100%;margin:0 auto;box-sizing:border-box">' +
32
+ '<div style="display:flex;gap:8px;flex-wrap:wrap">' +
33
+ '<button data-m="ela" style="' + btn + '">ELA</button><button data-m="mse" style="' + btn + '">MSE</button>' +
34
+ '<button data-a="overlay" style="' + btn + '">' + T('فوق الصورة', 'Over image') + '</button>' +
35
+ '<button data-a="zoom" style="' + btn + '">' + T('تكبير', 'Zoom') + '</button></div>' +
36
+ '<label style="display:block">' + T('جودة إعادة الحفظ', 'Re-save quality') + ': <b data-v="q"></b>' +
37
+ '<input data-s="q" type="range" min="60" max="100" step="1" value="90" style="width:100%"></label>' +
38
+ '<label style="display:block">' + T('شدة الإبراز', 'Intensity') + ': <b data-v="g"></b>' +
39
+ '<input data-s="g" type="range" min="1" max="10" step="1" value="5" style="width:100%"></label>' +
40
+ '<div style="position:relative"><canvas data-c style="width:100%;border-radius:10px;background:#000;display:block"></canvas>' +
41
+ '<div data-busy style="position:absolute;inset:0;display:none;align-items:center;justify-content:center;background:rgba(0,0,0,.35);border-radius:10px">' +
42
+ T('جارٍ الحساب…', 'Computing…') + '</div></div>' +
43
+ '<div style="font-size:12.5px;line-height:1.8;opacity:.85">' +
44
+ T('كيف تقرئينها: الأسطح المتشابهة (سماء، جدار، جلد) يجب أن يكون مستوى خطئها متقاربًا. المنطقة الأكثر أو الأقل إضاءة من محيطها المشابه قد تكون عُدِّلت بعد آخر حفظ. الحواف والنصوص والتفاصيل الدقيقة تظهر فاتحة بطبيعتها. جرّبي أكثر من جودة: المنطقة المعدّلة تبقى مختلفة عند معظم الجودات، ويقترب الأصل من السواد عند جودة آخر حفظ.',
45
+ 'How to read it: similar surfaces (sky, wall, skin) should show similar error levels. An area brighter or darker than similar surroundings may have been edited after the last save. Edges, text and fine detail are naturally bright. Try several qualities: an edited area stays different at most of them, while the original goes dark near the last save quality.') +
46
+ '</div><div style="font-size:11.5px;opacity:.6">' +
47
+ T('يُحسب داخل المتصفح بالكامل، ولا تُرفع الصورة. ELA مؤشر يُقرأ مع الفحوص الأخرى وليس دليلًا بمفرده.',
48
+ 'Computed entirely in the browser; the image is not uploaded. ELA is an indicator to read with the other checks, not proof on its own.') +
49
+ '</div></div>';
50
+ document.body.appendChild(ov);
51
+ var q = ov.querySelector('[data-s="q"]'), g = ov.querySelector('[data-s="g"]'), cv = ov.querySelector('[data-c]'),
52
+ busy = ov.querySelector('[data-busy]'), qv = ov.querySelector('[data-v="q"]'), gv = ov.querySelector('[data-v="g"]');
53
+ var mode = 'ela', overlay = false, base = null, W = 0, H = 0, timer = null, job = 0;
54
+
55
+ function paintButtons() {
56
+ ov.querySelectorAll('[data-m]').forEach(function (b) {
57
+ var on = b.getAttribute('data-m') === mode;
58
+ b.style.background = on ? '#2563eb' : '#1e293b'; b.style.borderColor = on ? '#2563eb' : '#334155';
59
+ });
60
+ var o = ov.querySelector('[data-a="overlay"]');
61
+ o.style.background = overlay ? '#2563eb' : '#1e293b'; o.style.borderColor = overlay ? '#2563eb' : '#334155';
62
+ }
63
+
64
+ function compute() {
65
+ if (!base) return;
66
+ var my = ++job;
67
+ busy.style.display = 'flex';
68
+ qv.textContent = q.value; gv.textContent = g.value;
69
+ var c0 = document.createElement('canvas'); c0.width = W; c0.height = H;
70
+ c0.getContext('2d').putImageData(base, 0, 0);
71
+ c0.toBlob(function (blob) {
72
+ var url = URL.createObjectURL(blob), im = new Image();
73
+ im.onload = function () {
74
+ if (my !== job) { URL.revokeObjectURL(url); return; }
75
+ var c1 = document.createElement('canvas'); c1.width = W; c1.height = H;
76
+ var x1 = c1.getContext('2d'); x1.drawImage(im, 0, 0);
77
+ var re = x1.getImageData(0, 0, W, H).data, a = base.data;
78
+ URL.revokeObjectURL(url);
79
+ cv.width = W; cv.height = H;
80
+ var ctx = cv.getContext('2d'), out = ctx.createImageData(W, H), o = out.data, gain = +g.value;
81
+ if (mode === 'ela') {
82
+ // auto-scale: the 99.5th percentile of the difference maps to full
83
+ // brightness at the middle intensity setting
84
+ var hist = new Uint32Array(256), cnt = 0;
85
+ for (var h = 0; h < a.length; h += 16) {
86
+ var dm = Math.max(Math.abs(a[h] - re[h]), Math.abs(a[h + 1] - re[h + 1]), Math.abs(a[h + 2] - re[h + 2]));
87
+ hist[Math.min(255, dm)]++; cnt++;
88
+ }
89
+ var acc = 0, p995 = 1;
90
+ for (var t = 0; t < 256; t++) { acc += hist[t]; if (acc >= cnt * 0.995) { p995 = Math.max(1, t); break; } }
91
+ var scale = (255 / p995) * (gain / 5);
92
+ for (var i = 0; i < a.length; i += 4) {
93
+ var r = Math.min(255, Math.abs(a[i] - re[i]) * scale), gg = Math.min(255, Math.abs(a[i + 1] - re[i + 1]) * scale),
94
+ b = Math.min(255, Math.abs(a[i + 2] - re[i + 2]) * scale);
95
+ if (overlay) {
96
+ var l = (a[i] * .299 + a[i + 1] * .587 + a[i + 2] * .114) * 0.45;
97
+ o[i] = Math.min(255, l + r); o[i + 1] = Math.min(255, l + gg); o[i + 2] = Math.min(255, l + b);
98
+ } else { o[i] = r; o[i + 1] = gg; o[i + 2] = b; }
99
+ o[i + 3] = 255;
100
+ }
101
+ } else {
102
+ var bw = Math.floor(W / 8), bh = Math.floor(H / 8), mse = new Float32Array(bw * bh), vals = [];
103
+ for (var by = 0; by < bh; by++) for (var bx = 0; bx < bw; bx++) {
104
+ var s = 0;
105
+ for (var yy = 0; yy < 8; yy++) for (var xx = 0; xx < 8; xx++) {
106
+ var p = ((by * 8 + yy) * W + bx * 8 + xx) * 4;
107
+ var d0 = a[p] - re[p], d1 = a[p + 1] - re[p + 1], d2 = a[p + 2] - re[p + 2];
108
+ s += (d0 * d0 + d1 * d1 + d2 * d2) / 3;
109
+ }
110
+ mse[by * bw + bx] = s / 64; vals.push(s / 64);
111
+ }
112
+ vals.sort(function (x, y) { return x - y; });
113
+ var top = vals[Math.floor(vals.length * 0.995)] || 1, lim = top / (gain / 5);
114
+ for (var k = 0; k < a.length; k += 4) {
115
+ var px = (k / 4) % W, py = Math.floor(k / 4 / W), bi = Math.min(bh - 1, py >> 3) * bw + Math.min(bw - 1, px >> 3);
116
+ var v = Math.min(1, mse[bi] / lim), c = jet(v);
117
+ if (overlay) {
118
+ var lum = (a[k] * .299 + a[k + 1] * .587 + a[k + 2] * .114), al = 0.25 + 0.6 * v;
119
+ o[k] = lum * (1 - al) + c[0] * al; o[k + 1] = lum * (1 - al) + c[1] * al; o[k + 2] = lum * (1 - al) + c[2] * al;
120
+ } else { o[k] = c[0]; o[k + 1] = c[1]; o[k + 2] = c[2]; }
121
+ o[k + 3] = 255;
122
+ }
123
+ }
124
+ ctx.putImageData(out, 0, 0);
125
+ busy.style.display = 'none';
126
+ };
127
+ im.src = url;
128
+ }, 'image/jpeg', (+q.value) / 100);
129
+ }
130
+ function later() { clearTimeout(timer); timer = setTimeout(compute, 120); }
131
+
132
+ var img = new Image();
133
+ img.crossOrigin = 'anonymous';
134
+ img.onload = function () {
135
+ var s = Math.min(1, MAX / Math.max(img.naturalWidth, img.naturalHeight));
136
+ W = Math.round(img.naturalWidth * s); H = Math.round(img.naturalHeight * s);
137
+ var c = document.createElement('canvas'); c.width = W; c.height = H;
138
+ var x = c.getContext('2d'); x.drawImage(img, 0, 0, W, H);
139
+ base = x.getImageData(0, 0, W, H);
140
+ compute();
141
+ };
142
+ img.src = src;
143
+ paintButtons();
144
+ q.oninput = later; g.oninput = later;
145
+ ov.addEventListener('click', function (e) {
146
+ var b = e.target.closest('button'); if (!b) return;
147
+ if (b.hasAttribute('data-m')) { mode = b.getAttribute('data-m'); paintButtons(); compute(); return; }
148
+ var a = b.getAttribute('data-a');
149
+ if (a === 'close') ov.remove();
150
+ else if (a === 'overlay') { overlay = !overlay; paintButtons(); compute(); }
151
+ else if (a === 'zoom' && window.tsZoom) window.tsZoom(cv.toDataURL('image/png'));
152
+ });
153
+ };
154
+
155
+ // Current frame of a <video> as an image URL (for ELA on video).
156
+ window.tsVideoFrame = function (video) {
157
+ try {
158
+ var c = document.createElement('canvas'); c.width = video.videoWidth; c.height = video.videoHeight;
159
+ c.getContext('2d').drawImage(video, 0, 0);
160
+ return c.toDataURL('image/png');
161
+ } catch (e) { return null; }
162
+ };
163
+ })();