Manar55 commited on
Commit
7ea6fd3
·
verified ·
1 Parent(s): ec53ebe

Deploy 70eeb92

Browse files
app.py CHANGED
@@ -843,6 +843,14 @@ def jpeg_forensics_endpoint():
843
  out["platform"] = platform_id.identify(data, f.filename or "")
844
  except Exception as e:
845
  print(f"[platform] failed: {e}", flush=True)
 
 
 
 
 
 
 
 
846
  return jsonify(out)
847
  except Exception as e:
848
  import traceback
@@ -869,6 +877,7 @@ def _add_learned_map(out, data):
869
  rel = r["reliability"]
870
  score = r["score"]
871
  out["learned"] = {"available": True, "score": round(score, 3)}
 
872
  out["maps"].insert(0, {"key": "learned", "ar": "خريطة التلاعب (نموذج مدرّب)", "en": "Manipulation map (trained model)",
873
  "help_ar": "الألوان الدافئة مناطق يرجّح النموذج أنها معدّلة أو ملصوقة.",
874
  "help_en": "Warm colours are areas the model considers edited or pasted.",
 
843
  out["platform"] = platform_id.identify(data, f.filename or "")
844
  except Exception as e:
845
  print(f"[platform] failed: {e}", flush=True)
846
+ try:
847
+ import evidence
848
+ evidence.build(out, data)
849
+ except Exception as e:
850
+ import traceback
851
+ traceback.print_exc()
852
+ print(f"[evidence] failed: {e}", flush=True)
853
+ out.pop("_raw", None)
854
  return jsonify(out)
855
  except Exception as e:
856
  import traceback
 
877
  rel = r["reliability"]
878
  score = r["score"]
879
  out["learned"] = {"available": True, "score": round(score, 3)}
880
+ out.setdefault("_raw", {})["learned"] = {"map": heat, "score": float(score), "oriented": True}
881
  out["maps"].insert(0, {"key": "learned", "ar": "خريطة التلاعب (نموذج مدرّب)", "en": "Manipulation map (trained model)",
882
  "help_ar": "الألوان الدافئة مناطق يرجّح النموذج أنها معدّلة أو ملصوقة.",
883
  "help_en": "Warm colours are areas the model considers edited or pasted.",
route/evidence.py ADDED
@@ -0,0 +1,384 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Evidence builder for the tampering tab.
3
+
4
+ Turns every check into one evidence item with:
5
+ - what was found (with the measured numbers),
6
+ - why it is (or is not) an indicator,
7
+ - the method, its published reference, and the equivalent filter name in
8
+ Amped Authenticate (for independent verification - TruScan does NOT run
9
+ Amped software; the names only tell an examiner which tool reproduces
10
+ the same analysis),
11
+ - the method's known limits,
12
+ - its weight and contribution to the final opinion.
13
+
14
+ Two separate questions are answered, because mixing them misleads:
15
+ 1. Content integrity - was part of the picture altered? (weighted score)
16
+ 2. Processing history - is this the original camera file, or was it
17
+ re-saved / cropped / passed through a program or platform? Re-saving is
18
+ NOT tampering; it is reported separately.
19
+
20
+ Weights are fixed and documented below; they are re-tuned only from
21
+ evaluations that passed review.
22
+ """
23
+ import io
24
+
25
+ import numpy as np
26
+ from PIL import Image
27
+
28
+ import jpeg_advanced as J
29
+ import jpeg_forensics as JF
30
+
31
+ # Content-integrity weights (sum is normalised over the checks that apply).
32
+ WEIGHTS = {"learned": 0.30, "adjpeg": 0.15, "nadjpeg": 0.10, "thumbnail": 0.15, "ghost_local": 0.10, "dq_local": 0.05}
33
+ HIGH, MEDIUM = 0.50, 0.28
34
+ MIN_COVER = 0.45
35
+
36
+ _ORIENT = {2: Image.FLIP_LEFT_RIGHT, 3: Image.ROTATE_180, 4: Image.FLIP_TOP_BOTTOM, 5: Image.TRANSPOSE,
37
+ 6: Image.ROTATE_270, 7: Image.TRANSVERSE, 8: Image.ROTATE_90}
38
+
39
+ REF = {
40
+ "learned": "Guillaro, Cozzolino, Sud, Dufour & Verdoliva, “TruFor: Leveraging all-round clues for trustworthy image forgery detection and localization”, CVPR 2023.",
41
+ "adjpeg": "Lin, He, Tang & Tang, “Fast, automatic and fine-grained tampered JPEG image detection via DCT coefficient analysis”, Pattern Recognition 42(11), 2009; Bianchi & Piva, “Image forgery localization via block-grained analysis of JPEG artifacts”, IEEE TIFS 7(3), 2012.",
42
+ "nadjpeg": "Bianchi & Piva, “Image forgery localization via block-grained analysis of JPEG artifacts”, IEEE TIFS 7(3), 2012; Li, Yuan & Yu, “Passive detection of doctored JPEG image via block artifact grid extraction”, Signal Processing 89(9), 2009.",
43
+ "ghost": "Farid, “Exposing digital forgeries from JPEG ghosts”, IEEE TIFS 4(1), 2009.",
44
+ "dct": "Lukáš & Fridrich, “Estimation of primary quantization matrix in double compressed JPEG images”, DFRWS 2003; Popescu & Farid, “Statistical tools for digital forensics”, IH 2004.",
45
+ "thumbnail": "Kee & Farid, “Digital image authentication from thumbnails”, SPIE Electronic Imaging 2010.",
46
+ "qt": "Farid, “Digital image ballistics from JPEG quantization”, Dartmouth TR2006-583; Kee, Johnson & Farid, “Digital image authentication from JPEG headers”, IEEE TIFS 6(3), 2011.",
47
+ "grid": "Li, Yuan & Yu, “Passive detection of doctored JPEG image via block artifact grid extraction”, Signal Processing 89(9), 2009.",
48
+ "platform": "Giudice, Paratore, Moltisanti & Battiato, “A classification engine for image ballistics of social data”, ICIAP 2017; Moltisanti, Paratore, Battiato & Saravo, “Image manipulation on Facebook for forensics evidence”, ICIAP 2015.",
49
+ "hash": "NIST FIPS 180-4 (SHA-256); RFC 1321 (MD5). ISO/IEC 27037:2012 — preservation of digital evidence.",
50
+ "fusion": "Fontani, Bianchi, De Rosa, Piva & Barni, “A framework for decision fusion in image forensics based on Dempster–Shafer theory of evidence”, IEEE TIFS 8(4), 2013.",
51
+ }
52
+
53
+
54
+ def _orient(m, o):
55
+ """Stored-orientation map -> display orientation (EXIF)."""
56
+ if o not in _ORIENT or m is None:
57
+ return m
58
+ return np.asarray(Image.fromarray(m.astype(np.float32), mode="F").transpose(_ORIENT[o]))
59
+
60
+
61
+ def _item(key, group, name, amped, ref, result, found, why, limits, suspicion=None, measures=None, map_key=None):
62
+ return {"key": key, "group": group, "name_ar": name[0], "name_en": name[1], "amped": amped, "reference": ref,
63
+ "result": result, "suspicion": None if suspicion is None else round(float(suspicion), 3),
64
+ "weight": WEIGHTS.get(key), "found_ar": found[0], "found_en": found[1], "why_ar": why[0], "why_en": why[1],
65
+ "limits_ar": limits[0], "limits_en": limits[1], "measures": measures or [], "map": map_key}
66
+
67
+
68
+ def _main_region(hot, min_frac=0.008, max_frac=0.45):
69
+ comps = [c for c in J.components(hot, min_frac) if c["area"] <= max_frac]
70
+ return comps[0] if comps else None
71
+
72
+
73
+ def _iou(a, b):
74
+ ix = max(0, min(a[2], b[2]) - max(a[0], b[0]))
75
+ iy = max(0, min(a[3], b[3]) - max(a[1], b[1]))
76
+ inter = ix * iy
77
+ ua = (a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter
78
+ return inter / ua if ua > 0 else 0.0
79
+
80
+
81
+ def build(out, data):
82
+ raw = out.get("_raw", {})
83
+ img = Image.open(io.BytesIO(data))
84
+ try:
85
+ orient = int(img.getexif().get(274, 1) or 1)
86
+ except Exception:
87
+ orient = 1
88
+ from PIL import ImageOps
89
+ rgb_disp = np.asarray(ImageOps.exif_transpose(img).convert("RGB"))
90
+ is_jpeg = (img.format or "").upper() == "JPEG"
91
+ gray = np.asarray(img.convert("YCbCr"))[:, :, 0] if is_jpeg else np.asarray(img.convert("L"))
92
+ quant = out.get("quantization") or {}
93
+ luma = quant.get("luma_table")
94
+ items, local_maps = [], {}
95
+
96
+ # ---------------- integrity of the examined file ----------------
97
+ h = J.hashes(data)
98
+ out["hashes"] = h
99
+ items.append(_item("hash", "file", ("بصمة الملف (Hash)", "File hash"), "File Format (Hash)", REF["hash"], "info",
100
+ (f"SHA-256: {h['sha256']}\nMD5: {h['md5']}\nالحجم: {h['size']:,} بايت",
101
+ f"SHA-256: {h['sha256']}\nMD5: {h['md5']}\nSize: {h['size']:,} bytes"),
102
+ ("البصمة تثبت أن الملف الذي فُحص هو نفسه الملف المقدَّم؛ أي تغيير ولو في بايت واحد يغيّرها. تُقارن ببصمة النسخة الأصلية عند تسلّمها.",
103
+ "The hash proves the examined file is the same file that was submitted; changing even one byte changes it. Compare it with the hash recorded when the original was received."),
104
+ ("تثبت سلامة النسخة فقط ولا تدل على صحة محتوى الصورة.", "It proves the copy is intact, not that the content is genuine.")))
105
+
106
+ # ---------------- content integrity ----------------
107
+ L = raw.get("learned")
108
+ if L:
109
+ s = L["score"]
110
+ res = "suspicious" if s >= 0.7 else "attention" if s >= 0.5 else "consistent"
111
+ m = L["map"]
112
+ local_maps["learned"] = m
113
+ reg = _main_region(m > 0.6)
114
+ items.append(_item("learned", "content", ("نموذج تحديد مواضع التلاعب", "Forgery localization model"),
115
+ "لا يوجد فلتر مطابق (أقرب ما يقابله: Fusion Map)", REF["learned"], res,
116
+ (f"قدّر النموذج احتمال التلاعب بالصورة بنحو {round(s * 100)}%" + (f"، وأبرز منطقة تغطي نحو {round(reg['area'] * 100)}% من الصورة." if reg and s >= 0.5 else "."),
117
+ f"The model estimated a {round(s * 100)}% probability of manipulation" + (f"; the main highlighted area covers about {round(reg['area'] * 100)}% of the picture." if reg and s >= 0.5 else ".")),
118
+ ("نموذج مدرَّب على آلاف الصور الأصلية والمعدّلة يتعلّم «بصمة الضوضاء» التي تتركها الكاميرا، فإذا انقطعت هذه البصمة في منطقة فهي على الأرجح مضافة أو معدّلة. خريطة الموثوقية المرافقة تبيّن أين قد يخطئ.",
119
+ "A model trained on thousands of authentic and edited images learns the camera noise fingerprint; where it breaks, the area was most likely added or altered. The accompanying reliability map shows where it may be wrong."),
120
+ ("قد يعطي إنذارًا كاذبًا على الصور شديدة الضغط أو المصغّرة أو المناطق المشبعة، ونتيجته احتمالية وليست قاطعة.",
121
+ "May give false alarms on heavily compressed, downscaled or saturated images; its output is a probability, not proof."),
122
+ suspicion=s, measures=[["الاحتمال", "Probability", f"{round(s * 100)}%"]], map_key="learned"))
123
+
124
+ plot = None
125
+ if is_jpeg and luma:
126
+ plot = J.dct_plot(gray, luma)
127
+ out["dct_plot"] = plot
128
+ adj = J.adjpeg_map(gray, luma, plot) if plot else None
129
+ if adj is not None:
130
+ hot = (adj["prob"] > 0.85) & adj["texture"]
131
+ reg = _main_region(hot)
132
+ pm = np.where(adj["texture"], adj["prob"], 0)
133
+ local_maps["adjpeg"] = _orient(pm, orient)
134
+ out["maps"].append({"key": "adjpeg", "ar": "ADJPEG — الضغط المزدوج المحاذي", "en": "ADJPEG — aligned double JPEG",
135
+ "help_ar": "باقي الصورة حُفظ مرتين؛ المناطق الحمراء لا تحمل أثر الحفظ الأول، أي أنها على الأرجح أُضيفت بعده.",
136
+ "help_en": "The rest of the picture was saved twice; red areas lack the first save, so they were most likely added after it.",
137
+ "image": JF._heat_png(local_maps["adjpeg"], rgb_disp)})
138
+ if reg:
139
+ s = 0.9 if reg["area"] >= 0.015 else 0.6
140
+ res = "suspicious" if s >= 0.85 else "attention"
141
+ fnd = (f"منطقة متصلة تغطي نحو {round(reg['area'] * 100, 1)}% من الصورة لا تحمل أثر الحفظ الأول (جودة ≈ {plot['first_quality'] or 'غير محددة'}) الموجود في باقي الصورة.",
142
+ f"A connected area covering about {round(reg['area'] * 100, 1)}% of the picture lacks the first save (quality ≈ {plot['first_quality'] or 'unknown'}) present in the rest.")
143
+ else:
144
+ s, res = 0.05, "consistent"
145
+ fnd = ("كل مناطق الصورة تحمل أثر الحفظ الأول نفسه؛ لا توجد منطقة مختلفة.", "Every area carries the same first-save trace; no area stands out.")
146
+ items.append(_item("adjpeg", "content", ("الضغط المزدوج المحاذي (ADJPEG)", "Aligned double JPEG (ADJPEG)"),
147
+ "ADJPEG", REF["adjpeg"], res, fnd,
148
+ ("عند حفظ صورة JPEG مرتين تتكوّن في معاملات DCT فجوات منتظمة. إذا أُلصق جسم من مصدر آخر ثم حُفظت الصورة، فإن الجسم الملصوق يمر بالحفظ الأخير فقط، فتغيب عنه تلك الفجوات فيظهر مختلفًا عن محيطه.",
149
+ "Saving a JPEG twice leaves regular gaps in its DCT coefficients. An object pasted from another source before the last save goes through that save only, so it lacks those gaps and stands out from its surroundings."),
150
+ ("يعمل فقط إذا حُفظت الصورة مرتين وكانت جودة الحفظ الأول أقل من الأخير، وعلى مناطق فيها تفاصيل؛ المناطق المسطحة لا تُقيَّم.",
151
+ "Works only when the picture was saved twice with the first quality lower than the last, and on textured areas; flat areas are not assessed."),
152
+ suspicion=s, measures=[["المنطقة", "Area", f"{round(reg['area'] * 100, 1)}%" if reg else "—"]], map_key="adjpeg"))
153
+ if reg:
154
+ local_maps["_adj_box"] = reg["box"]
155
+ elif plot is not None:
156
+ items.append(_item("adjpeg", "content", ("الضغط المزدوج المحاذي (ADJPEG)", "Aligned double JPEG (ADJPEG)"),
157
+ "ADJPEG", REF["adjpeg"], "na",
158
+ ("لا ينطبق: لم يُرصد حفظ مزدوج على مستوى الصورة (حُفظت مرة واحدة، أو كان الحفظ الأول بجودة أعلى من الأخير).",
159
+ "Not applicable: no double save detected for the whole picture (saved once, or first saved at a higher quality than the last)."),
160
+ ("الطريقة تبحث عن منطقة تختلف عن بقية صورة محفوظة مرتين.", "The method looks for an area that differs from a picture saved twice."),
161
+ ("غياب الحفظ المزدوج لا يعني الأصالة.", "No double save does not mean authentic.")))
162
+
163
+ glob, loc = J.grid_analysis(gray)
164
+ out["grid"] = glob
165
+ widespread = loc is not None and loc["valid"].sum() >= 30 and float(loc["hot"][loc["valid"]].mean()) > 0.4
166
+ if widespread:
167
+ items.append(_item("nadjpeg", "content", ("شبكة الضغط غير المحاذية (NADJPEG)", "Non-aligned double JPEG (NADJPEG)"),
168
+ "NADJPEG / Blocking Artifacts (BAG)", REF["nadjpeg"], "na",
169
+ ("لا ينطبق: شبكة الكتل مضطربة في معظم الصورة (تغيير الحجم أو نمط متكرر في المشهد)، فلا يمكن تمييز منطقة بعينها.",
170
+ "Not applicable: the block grid is disturbed across most of the picture (resizing or a repetitive pattern in the scene), so no single area can be singled out."),
171
+ ("الطريقة تقارن شبكة كل منطقة بشبكة باقي الصورة، وتحتاج شبكة واضحة ومتسقة.", "The method compares each area's grid with the rest and needs a clear, consistent grid."),
172
+ ("تغيير الحجم بعد الحفظ يمحو الشبكة.", "Resizing after saving erases the grid.")))
173
+ elif loc is not None and loc["valid"].sum() >= 30:
174
+ hot = loc["hot"]
175
+ reg = _main_region(hot, 0.01)
176
+ sm = np.where(loc["valid"], np.clip(loc["score"] / 2.0, 0, 1), 0)
177
+ local_maps["nadjpeg"] = _orient(sm, orient)
178
+ out["maps"].append({"key": "nadjpeg", "ar": "NADJPEG — شبكة ضغط مختلفة", "en": "NADJPEG — different JPEG grid",
179
+ "help_ar": "المناطق الحمراء تحمل شبكة كتل 8×8 في موضع مختلف عن باقي الصورة، أي أنها جاءت من صورة JPEG أخرى.",
180
+ "help_en": "Red areas carry an 8×8 block grid at a different position from the rest, i.e. they came from another JPEG.",
181
+ "image": JF._heat_png(local_maps["nadjpeg"], rgb_disp)})
182
+ if reg:
183
+ s, res = (0.85, "suspicious") if reg["area"] >= 0.015 else (0.55, "attention")
184
+ fnd = (f"منطقة تغطي نحو {round(reg['area'] * 100, 1)}% من الصورة شبكتها مزاحة عن شبكة باقي الصورة.",
185
+ f"An area covering about {round(reg['area'] * 100, 1)}% of the picture has its grid shifted from the rest.")
186
+ local_maps["_nadj_box"] = reg["box"]
187
+ else:
188
+ s, res = 0.05, "consistent"
189
+ fnd = ("شبكة الكتل متسقة في كل مناطق الصورة التي يمكن ق��اسها.", "The block grid is consistent across every measurable area.")
190
+ items.append(_item("nadjpeg", "content", ("شبكة الضغط غير المحاذية (NADJPEG)", "Non-aligned double JPEG (NADJPEG)"),
191
+ "NADJPEG / Blocking Artifacts (BAG)", REF["nadjpeg"], res, fnd,
192
+ ("ضغط JPEG يقسم الصورة إلى كتل 8×8 ويترك حدودًا خفيفة بينها. الجزء المقتطع من صورة JPEG أخرى يحمل شبكته الخاصة، ونادرًا ما يُلصق بحيث تنطبق على شبكة الصورة الجديدة، فتظهر شبكتان في موضعين مختلفين.",
193
+ "JPEG splits a picture into 8×8 blocks and leaves faint edges between them. A piece cut from another JPEG keeps its own grid and is rarely pasted exactly onto the new picture's grid, so two grids appear at different positions."),
194
+ ("يحتاج أن يكون الجزء الملصوق قد ضُغط سابقًا وأن تكون الجودة الأخيرة غير عالية جدًا؛ المناطق المسطحة لا تُقيَّم.",
195
+ "Needs the pasted part to have been JPEG-compressed before and a final quality that is not very high; flat areas are not assessed."),
196
+ suspicion=s, measures=[["المنطقة", "Area", f"{round(reg['area'] * 100, 1)}%" if reg else "—"]], map_key="nadjpeg"))
197
+
198
+ G = raw.get("ghost_local")
199
+ if G:
200
+ local_maps["ghost_local"] = _orient(G["map"], orient)
201
+ c = G["contrast"]
202
+ s, res = (min(1.0, 0.4 + c * 0.6), "suspicious") if c > 0.55 else (0.1, "consistent")
203
+ items.append(_item("ghost_local", "content", ("أشباح JPEG", "JPEG ghosts"), "JPEG Ghosts Map", REF["ghost"], res,
204
+ ((f"منطقة محددة تُظهر «شبحًا» عند الجودة {G['quality']} لا يظهر في باقي الصورة (التباين {c:.2f}).",
205
+ f"A specific area shows a ghost at quality {G['quality']} not seen in the rest (contrast {c:.2f}).") if c > 0.55 else
206
+ ("لم تظهر منطقة بشبح يختلف بوضوح عن باقي الصورة.", "No area shows a ghost clearly different from the rest.")),
207
+ ("تُعاد كتابة الصورة بجودات متعددة. الجزء الذي حُفظ سابقًا بجودة معيّنة يتغيّر أقل ما يمكن عند تلك الجودة («الشبح»)، فإذا ظهر الشبح على جزء واحد فقط فذلك الجزء له تاريخ ضغط مختلف.",
208
+ "The picture is re-saved at many qualities. A part previously saved at a given quality changes least at that quality (the ghost); a ghost on one part only means that part has a different compression history."),
209
+ ("لا يكشف الجزء إذا كانت جودته السابقة أعلى من الجودة الأخيرة، وقد تتأثر المناطق المسطحة أو المشبعة.",
210
+ "Misses parts whose earlier quality was higher than the last one; flat or saturated areas can mislead."),
211
+ suspicion=s, measures=[["الجودة", "Quality", str(G["quality"])], ["التباين", "Contrast", f"{c:.2f}"]], map_key="ghost"))
212
+
213
+ D = raw.get("dq_local")
214
+ if D:
215
+ m = D["map"]
216
+ ex = D.get("extent", [1, 1])
217
+ if ex[0] >= 0.99 and ex[1] >= 0.99:
218
+ local_maps["dq_local"] = _orient(m, orient)
219
+ f = D["frac"]
220
+ s, res = (0.7, "attention") if 0.04 <= f <= 0.3 else (0.1, "consistent")
221
+ items.append(_item("dq_local", "content", ("سجل الضغط حسب المنطقة", "Compression history by region"),
222
+ "ADJPEG (طريقة مكمّلة على نوافذ)", REF["dct"], res,
223
+ ((f"نحو {round(f * 100)}% من الصورة يختلف في سجل الضغط عن باقيها.", f"About {round(f * 100)}% of the picture has a different compression history from the rest.")
224
+ if res == "attention" else ("سجل الضغط متقارب في مناطق الصورة.", "The compression history is similar across the picture.")),
225
+ ("تُقاس فجوات معاملات DCT في كل نافذة من الصورة على حدة؛ النافذة التي تختلف عن أغلب الصورة لها تاريخ حفظ مختلف.",
226
+ "DCT-coefficient gaps are measured window by window; a window that differs from most of the picture has a different save history."),
227
+ ("أخشن من ADJPEG (نوافذ 192 بكسل)، ويُستخدم للتأكيد.", "Coarser than ADJPEG (192-pixel windows); used as confirmation."),
228
+ suspicion=s, measures=[["المنطقة", "Area", f"{round(f * 100)}%"]], map_key="dq"))
229
+
230
+ T = raw.get("thumbnail")
231
+ if T:
232
+ sim = T["similarity"]
233
+ if T["aspect_mismatch"] or sim < 0.9:
234
+ s, res = 0.95, "suspicious"
235
+ elif sim < 0.97:
236
+ s, res = 0.5, "attention"
237
+ else:
238
+ s, res = 0.0, "consistent"
239
+ items.append(_item("thumbnail", "content", ("ا��صورة المصغّرة داخل الملف", "Embedded thumbnail"), "Thumbnail Analysis", REF["thumbnail"], res,
240
+ (f"تطابق الصورة المصغّرة المحفوظة داخل الملف مع الصورة الحالية: {round(sim * 100)}%" + ("، ونسبة الأبعاد مختلفة." if T["aspect_mismatch"] else "."),
241
+ f"Similarity between the thumbnail stored in the file and the current picture: {round(sim * 100)}%" + (", and the aspect ratio differs." if T["aspect_mismatch"] else ".")),
242
+ ("الكاميرا تحفظ نسخة مصغّرة من الصورة داخل الملف لحظة الالتقاط. بعض برامج التحرير تعدّل الصورة ولا تحدّث المصغّرة، فتبقى المصغّرة شاهدًا على الصورة قبل التعديل.",
243
+ "The camera stores a small copy of the picture inside the file at capture. Some editors change the picture without updating the thumbnail, so the thumbnail remains a witness of the picture before editing."),
244
+ ("تطابق المصغّرة لا يثبت الأصالة، فكثير من البرامج تحدّثها؛ والقص أو التدوير قد يسبب اختلافًا دون تلاعب بالمحتوى.",
245
+ "A matching thumbnail does not prove authenticity (many programs update it); cropping or rotating can cause a difference without altering content."),
246
+ suspicion=s, measures=[["التطابق", "Similarity", f"{round(sim * 100)}%"]]))
247
+
248
+ # ---------------- fusion map + region crops ----------------
249
+ fus_in = [(local_maps.get(k), WEIGHTS[k]) for k in ("learned", "adjpeg", "nadjpeg", "ghost_local", "dq_local")
250
+ if local_maps.get(k) is not None]
251
+ regions = []
252
+ if len(fus_in) >= 2:
253
+ H0, W0 = rgb_disp.shape[:2]
254
+ sh = (96, max(8, int(round(96 * W0 / H0)))) if H0 >= W0 else (max(8, int(round(96 * H0 / W0))), 96)
255
+ fus = J.fuse(fus_in, sh)
256
+ out["maps"].append({"key": "fusion", "ar": "خريطة الدمج (Fusion)", "en": "Fusion map",
257
+ "help_ar": "تجمع الخرائط المحلية بأوزانها في خريطة واحدة؛ المنطقة التي تتفق عليها أكثر من طريقة تظهر أوضح.",
258
+ "help_en": "Combines the local maps by weight; an area several methods agree on stands out most.",
259
+ "image": JF._heat_png(fus / max(float(fus.max()), 1e-6), rgb_disp)})
260
+ thr = max(0.3, 0.6 * float(fus.max()))
261
+ for comp in J.components(fus >= thr, 0.004)[:3]:
262
+ if comp["area"] > 0.45:
263
+ continue
264
+ agree = []
265
+ flagged = {i["key"] for i in items if i["result"] in ("suspicious", "attention")}
266
+ for k in ("learned", "adjpeg", "nadjpeg", "ghost_local", "dq_local"):
267
+ mk = local_maps.get(k)
268
+ if mk is None or k not in flagged:
269
+ continue
270
+ import cv2
271
+ r = cv2.resize(np.clip(mk, 0, 1).astype(np.float32), (sh[1], sh[0]))
272
+ x0, y0, x1, y1 = [int(round(v)) for v in (comp["box"][0] * sh[1], comp["box"][1] * sh[0], comp["box"][2] * sh[1], comp["box"][3] * sh[0])]
273
+ inside = r[y0:max(y1, y0 + 1), x0:max(x1, x0 + 1)].mean()
274
+ if inside > 0.5 and inside > 2 * (r.mean() + 1e-3):
275
+ agree.append(k)
276
+ if not agree:
277
+ continue
278
+ regions.append({"box": [round(v, 4) for v in comp["box"]], "area": round(comp["area"], 4), "methods": agree,
279
+ "crop": J.crop_png(rgb_disp, comp["box"])})
280
+ out["regions"] = regions
281
+ if regions:
282
+ top = regions[0]
283
+ items.append(_item("fusion", "content", ("خريطة الدمج", "Fusion map"), "Fusion Map", REF["fusion"],
284
+ "suspicious" if len(top["methods"]) >= 2 else "attention",
285
+ (f"أبرز منطقة تغطي نحو {round(top['area'] * 100, 1)}% من الصورة، وتتفق عليها {len(top['methods'])} من الطرق المستقلة.",
286
+ f"The main area covers about {round(top['area'] * 100, 1)}% of the picture; {len(top['methods'])} independent methods agree on it."),
287
+ ("اتفاق طرق تقيس آثارًا مختلفة (الضوضاء، شبكة الضغط، معاملات DCT، الأشباح) على المنطقة نفسها أقوى بكثير من نتيجة طريقة واحدة.",
288
+ "Agreement on the same area between methods that measure different traces (noise, compression grid, DCT coefficients, ghosts) is far stronger than any single result."),
289
+ ("الخريطة تلخيص للخرائط الأخرى وليست طريقة مستقلة؛ لا تُحسب مرة ثانية في الحكم.",
290
+ "The map summarises the others and is not an independent method; it is not counted again in the opinion."),
291
+ measures=[["ا��طرق المتفقة", "Agreeing methods", str(len(top["methods"]))]], map_key="fusion"))
292
+
293
+ # ---------------- processing history (not tampering) ----------------
294
+ hist_flags = []
295
+ if quant:
296
+ std = quant.get("standard_tables")
297
+ mk = ""
298
+ try:
299
+ mk = str(img.getexif().get(271, "") or "")
300
+ except Exception:
301
+ pass
302
+ mismatch = std and "apple" in mk.lower()
303
+ res = "attention" if (std or mismatch) else "consistent"
304
+ if std:
305
+ hist_flags.append("qt")
306
+ items.append(_item("qt", "history", ("جداول التكميم", "Quantization tables"), "JPEG QT", REF["qt"], res,
307
+ ((f"الجداول قياسية (مكتبة JPEG) بجودة ≈ {quant.get('quality')}" + (f"، بينما يذكر الملف جهاز {mk} الذي يستخدم جداول خاصة." if mismatch else "."))
308
+ if std else f"الجداول غير قياسية بجودة ≈ {quant.get('quality')}، وهو نمط الكاميرات والهواتف.",
309
+ (f"Standard library tables at quality ≈ {quant.get('quality')}" + (f", while the file names a {mk} device, which uses its own tables." if mismatch else "."))
310
+ if std else f"Non-standard tables at quality ≈ {quant.get('quality')}, the pattern of cameras and phones."),
311
+ ("كل كاميرا وبرنامج يحفظ الصورة بجداول ضغط مميّزة؛ الجداول تكشف آخر برنامج أو جهاز حفظ الملف. الجداول القياسية تعني غالبًا برنامج تحرير أو منصة أو إعادة حفظ.",
312
+ "Each camera and program saves with distinctive tables, so they reveal the last program or device that saved the file. Standard tables usually mean an editor, a platform or a re-save."),
313
+ ("تكشف من حفظ الملف آخر مرة، لا ما إذا تغيّر المحتوى. بعض الهواتف تستخدم الجداول القياسية.",
314
+ "Shows who saved the file last, not whether the content changed. Some phones use the standard tables."),
315
+ measures=[["الجودة", "Quality", str(quant.get("quality"))], ["قياسية", "Standard", "✓" if std else "✗"]]))
316
+ if plot is not None:
317
+ if plot["double"]:
318
+ hist_flags.append("double")
319
+ items.append(_item("dct", "history", ("مخطط معاملات DCT", "DCT plot"), "DCT Plot", REF["dct"],
320
+ "attention" if plot["double"] else "consistent",
321
+ ((f"المدرّجات على شكل مشط في {plot['votes']} من 15 معاملًا: حُفظت الصورة أولًا بجودة ≈ {plot['first_quality'] or 'غير محددة'} ثم بجودة ≈ {quant.get('quality')}.",
322
+ f"Comb-shaped histograms in {plot['votes']} of 15 coefficients: first saved at quality ≈ {plot['first_quality'] or 'unknown'}, then at ≈ {quant.get('quality')}.")
323
+ if plot["double"] else ("المدرّجات ملساء متناقصة، وهو شكل الحفظ مرة واحدة (أو حفظ سابق بجودة أعلى).",
324
+ "Smooth, decaying histograms — the shape of a single save (or an earlier save at a higher quality).")),
325
+ ("الحفظ مرتين بجودتين مختلفتين يترك قيمًا فارغة منتظمة بين أعمدة مدرّج معاملات DCT («مشط»)، وتباعدها يحدد جودة الحفظ الأول.",
326
+ "Saving twice at different qualities leaves regularly empty values between the bars of the DCT histogram (a comb); their spacing gives the first save quality."),
327
+ ("إعادة الحفظ وحدها ليست تلاعبًا: الإرسال عبر تطبيقات المراسلة أو المنصات يسببها.",
328
+ "Re-saving alone is not tampering: messaging apps and platforms cause it."),
329
+ measures=[["الجودة الأولى", "First quality", str(plot["first_quality"] or "—")], ["المعاملات", "Coefficients", f"{plot['votes']}/15"]]))
330
+ if glob["clear"] and (glob["x"], glob["y"]) != (0, 0):
331
+ hist_flags.append("cropped")
332
+ items.append(_item("grid", "history", ("موضع شبكة الضغط", "JPEG grid position"), "Blocking Artifacts (BAG)", REF["grid"], "attention",
333
+ (f"شبكة الكتل تبدأ عند البكسل ({glob['x']}، {glob['y']}) وليس (0، 0).", f"The block grid starts at pixel ({glob['x']}, {glob['y']}), not (0, 0)."),
334
+ ("الكاميرا تبدأ شبكة الضغط من الزاوية العليا. انزياح الشبكة يعني أن الصورة قُصّت من أطرافها بعد حفظها بصيغة JPEG.",
335
+ "The camera starts the grid at the top-left corner. A shifted grid means the picture was cropped at its edges after being saved as JPEG."),
336
+ ("القص ليس تلاعبًا بالمحتوى بالضرورة، لكنه يعني أن الملف ليس الأصل.", "Cropping is not necessarily content tampering, but the file is not the original."),
337
+ measures=[["الإزاحة", "Offset", f"{glob['x']}, {glob['y']}"]]))
338
+ pf = out.get("platform") or {}
339
+ cands = pf.get("candidates") or []
340
+ if cands:
341
+ hist_flags.append("platform")
342
+ c = cands[0]
343
+ items.append(_item("platform", "history", ("المنصة", "Platform"), "Social Media Identification", REF["platform"], "attention",
344
+ (f"سمات الملف تطابق {c.get('ar')} ({'مؤشرات قوية' if c.get('level') == 'strong' else 'محتمل'}).",
345
+ f"The file traits match {c.get('en')} ({c.get('level')})."),
346
+ ("كل منصة تعيد ضغط الصور بأبعاد وجداول وبيانات وصفية معروفة.", "Each platform re-compresses with known sizes, tables and metadata."),
347
+ ("السمات تتغير مع الوقت وقد تتشابه بين المنصات.", "Traits change over time and may look alike between platforms.")))
348
+
349
+ # ---------------- opinion ----------------
350
+ scored = [i for i in items if i["group"] == "content" and i["weight"] and i["suspicion"] is not None]
351
+ wsum = sum(i["weight"] for i in scored)
352
+ # A single method cannot carry the opinion: when the checks that apply
353
+ # weigh less than MIN_COVER, the missing weight counts as "no sign".
354
+ denom = max(wsum, MIN_COVER)
355
+ score = sum(i["weight"] * i["suspicion"] for i in scored) / denom if wsum else None
356
+ for i in scored:
357
+ i["contribution"] = round(100 * i["weight"] * i["suspicion"] / denom, 1)
358
+ i["share"] = round(100 * i["weight"] / denom, 1)
359
+ level = "low"
360
+ reasons = []
361
+ if score is not None:
362
+ level = "high" if score >= HIGH else "medium" if score >= MEDIUM else "low"
363
+ th = next((i for i in scored if i["key"] == "thumbnail"), None)
364
+ if th and th["suspicion"] >= 0.9 and level != "high":
365
+ level = "high"
366
+ reasons.append(["المصغّرة لا تطابق الصورة: مؤشر حاسم بمفرده.", "Thumbnail does not match: decisive on its own."])
367
+ if level == "low" and any(i["result"] == "suspicious" for i in scored):
368
+ level = "medium"
369
+ reasons.append(["أحد الفحوص أعطى مؤشرًا قويًا يحتاج إلى تأكيد من فحص آخر.", "One check gave a strong indicator that needs confirmation by another."])
370
+ nagree = len(regions[0]["methods"]) if regions else 0
371
+ if nagree >= 3 and level != "high":
372
+ level = "high"
373
+ reasons.append(["ثلاث طرق مستقلة أو أكثر تتفق على منطقة واحدة.", "Three or more independent methods agree on one area."])
374
+ elif nagree >= 2 and level == "low":
375
+ level = "medium"
376
+ reasons.append(["طريقتان مستقلتان تتفقان على منطقة واحدة.", "Two independent methods agree on one area."])
377
+ hist = "edited_or_resaved" if hist_flags else "consistent"
378
+ out["opinion"] = {"content_level": level, "content_score": None if score is None else round(score, 3),
379
+ "thresholds": {"high": HIGH, "medium": MEDIUM}, "overrides": reasons,
380
+ "history": hist, "history_flags": hist_flags, "checks_used": len(scored),
381
+ "limited": wsum < MIN_COVER}
382
+ out["evidence"] = items
383
+ # keep the old single status in step with the opinion
384
+ out["status"] = level
route/jpeg_advanced.py ADDED
@@ -0,0 +1,276 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Advanced JPEG checks (training-free, published methods):
3
+
4
+ * File hashes (MD5 / SHA-256) - integrity of the examined file.
5
+ * DCT Plot - histogram of each low-frequency DCT coefficient. A JPEG saved
6
+ twice (first at a lower quality) has a comb-shaped histogram whose period
7
+ gives the FIRST quantization step, hence the first save quality.
8
+ (Lukas & Fridrich 2003; Popescu & Farid 2004.)
9
+ * ADJPEG - aligned double JPEG localization: per 8x8 block probability of
10
+ NOT having gone through the first compression the rest of the picture
11
+ shows (Lin, He, Tang & Tang 2009; Bianchi & Piva 2012). A pasted object
12
+ usually lacks it.
13
+ * NADJPEG / Blocking - the 8x8 blocking grid is estimated for the whole
14
+ image and per window. A grid not at the origin means the picture was
15
+ cropped after compression; a window with a different grid means content
16
+ from another JPEG (Bianchi & Piva 2012; Li, Yuan & Yu 2009).
17
+ * Fusion map - weighted combination of the local maps.
18
+
19
+ Every function is defensive: it returns None when the method does not
20
+ apply, so the caller can say so instead of guessing.
21
+ """
22
+ import base64
23
+ import hashlib
24
+ import io
25
+
26
+ import cv2
27
+ import numpy as np
28
+ from PIL import Image
29
+
30
+ _ZZ = [(0, 1), (1, 0), (2, 0), (1, 1), (0, 2), (0, 3), (1, 2), (2, 1), (3, 0), (4, 0), (3, 1), (2, 2), (1, 3),
31
+ (0, 4), (0, 5)] # first 15 AC coefficients, zig-zag order
32
+ _C = np.array([[np.sqrt((1 if k == 0 else 2) / 8) * np.cos((2 * n + 1) * k * np.pi / 16) for n in range(8)]
33
+ for k in range(8)], dtype=np.float32)
34
+
35
+
36
+ def hashes(data):
37
+ return {"md5": hashlib.md5(data).hexdigest(), "sha256": hashlib.sha256(data).hexdigest(), "size": len(data)}
38
+
39
+
40
+ def block_dct(gray, oy=0, ox=0):
41
+ """8x8 DCT of every block on the grid starting at (oy, ox). Same scaling
42
+ as the JPEG standard (orthonormal 2-D DCT, level-shifted)."""
43
+ g = gray[oy:, ox:].astype(np.float32) - 128.0
44
+ h, w = (g.shape[0] // 8) * 8, (g.shape[1] // 8) * 8
45
+ b = g[:h, :w].reshape(h // 8, 8, w // 8, 8).transpose(0, 2, 1, 3)
46
+ return np.einsum("ki,abij,lj->abkl", _C, b, _C, optimize=True)
47
+
48
+
49
+ def _ijg(q, base):
50
+ q = min(max(int(q), 1), 100)
51
+ s = 5000 / q if q < 50 else 200 - 2 * q
52
+ return np.clip(np.floor((base * s + 50) / 100), 1, 255)
53
+
54
+
55
+ def _populated(q1, q2, kmax):
56
+ """Values round(m*q1/q2) reachable after quantizing with q1 then q2."""
57
+ vals = set()
58
+ m = 0
59
+ while True:
60
+ k = int(np.floor(m * q1 / q2 + 0.5))
61
+ if k > kmax + 2:
62
+ break
63
+ vals.add(k)
64
+ m += 1
65
+ return vals
66
+
67
+
68
+ def _estimate_q1(hist, q2, kmax=30):
69
+ """hist: counts of |k| (k = round(dct/q2)). Returns (q1, strength) or
70
+ (None, 0). strength ~ how empty the 'forbidden' bins are."""
71
+ e = {}
72
+ for k in range(1, kmax):
73
+ nb = (hist[k - 1] + hist[k + 1]) / 2
74
+ if hist[k - 1] + hist[k] + hist[k + 1] < 25 or nb <= 0:
75
+ continue
76
+ e[k] = hist[k] / nb
77
+ if len(e) < 6:
78
+ return None, 0.0
79
+ best = (None, 0.0)
80
+ for q1 in range(int(q2) + 1, int(min(4 * q2, 120)) + 1):
81
+ P = _populated(q1, q2, kmax)
82
+ a = [e[k] for k in e if k in P]
83
+ b = [e[k] for k in e if k not in P]
84
+ if len(b) < 3 or len(a) < 3:
85
+ continue
86
+ s = float(np.mean(a) - np.mean(b))
87
+ if s > best[1] + 0.05 * (best[0] is not None): # prefer the smallest step on ties
88
+ best = (q1, s)
89
+ # forbidden bins must be clearly emptier than the populated ones
90
+ return best if best[1] > 0.6 else (None, best[1])
91
+
92
+
93
+ def dct_plot(gray, luma_table):
94
+ """Per-coefficient histograms and first-compression estimate."""
95
+ if luma_table is None:
96
+ return None
97
+ d = block_dct(gray).reshape(-1, 8, 8)
98
+ if len(d) > 60000:
99
+ d = d[np.random.default_rng(0).choice(len(d), 60000, replace=False)]
100
+ q2 = np.asarray(luma_table, dtype=np.float32).reshape(8, 8)
101
+ coeffs, votes = [], []
102
+ for idx, (u, v) in enumerate(_ZZ):
103
+ k = np.round(d[:, u, v] / q2[u, v]).astype(np.int32)
104
+ hs = np.bincount(np.clip(k, -40, 40) + 40, minlength=81).astype(int)
105
+ habs = np.bincount(np.clip(np.abs(k), 0, 41), minlength=42).astype(np.float64)
106
+ q1, strength = _estimate_q1(habs, float(q2[u, v]))
107
+ coeffs.append({"index": idx + 1, "uv": [u, v], "q2": int(q2[u, v]), "hist": hs.tolist(),
108
+ "q1": q1, "strength": round(float(strength), 2),
109
+ "populated": sorted(_populated(q1, float(q2[u, v]), 40)) if q1 else None})
110
+ if q1:
111
+ votes.append((u, v, q1))
112
+ first_q = None
113
+ if len(votes) >= 3:
114
+ base = np.array([16, 11, 10, 16, 24, 40, 51, 61, 12, 12, 14, 19, 26, 58, 60, 55, 14, 13, 16, 24, 40, 57,
115
+ 69, 56, 14, 17, 22, 29, 51, 87, 80, 62, 18, 22, 37, 56, 68, 109, 103, 77, 24, 35, 55, 64,
116
+ 81, 104, 113, 92, 49, 64, 78, 87, 103, 121, 120, 101, 72, 92, 95, 98, 112, 100, 103, 99],
117
+ dtype=np.float64).reshape(8, 8)
118
+ best = None
119
+ for q in range(30, 100):
120
+ t = _ijg(q, base)
121
+ err = np.mean([abs(t[u, v] - q1) / q1 for u, v, q1 in votes])
122
+ if best is None or err < best[1]:
123
+ best = (q, err)
124
+ if best and best[1] < 0.15:
125
+ first_q = best[0]
126
+ return {"coefficients": coeffs, "double": len(votes) >= 3, "votes": len(votes), "first_quality": first_q}
127
+
128
+
129
+ def _box(m, r):
130
+ return cv2.blur(m.astype(np.float32), (2 * r + 1, 2 * r + 1), borderType=cv2.BORDER_REFLECT)
131
+
132
+
133
+ def adjpeg_map(gray, luma_table, plot):
134
+ """Per-block probability of being single-compressed inside a doubly
135
+ compressed picture (Lin et al. 2009 posterior, coefficients combined in
136
+ the log domain). Needs the global first step from dct_plot."""
137
+ if not plot or not plot["double"]:
138
+ return None
139
+ d = block_dct(gray)
140
+ nby, nbx = d.shape[:2]
141
+ q2 = np.asarray(luma_table, dtype=np.float32).reshape(8, 8)
142
+ llr = np.zeros((nby, nbx), dtype=np.float32) # log p_single - log p_double
143
+ used = 0
144
+ for c in plot["coefficients"]:
145
+ if not c["q1"]:
146
+ continue
147
+ u, v = c["uv"]
148
+ P = sorted(set(c["populated"]))
149
+ habs = np.zeros(42)
150
+ hs = np.array(c["hist"])
151
+ for i, n in enumerate(hs):
152
+ habs[min(abs(i - 40), 41)] += n
153
+ k = np.abs(np.round(d[:, :, u, v] / q2[u, v]).astype(np.int32))
154
+ # period containing each bin: [P_i, P_{i+1})
155
+ p_dq = np.full(42, np.nan)
156
+ p_sq = np.full(42, np.nan)
157
+ for a, b in zip(P[:-1], P[1:]):
158
+ if b > 41:
159
+ break
160
+ tot = habs[a:b].sum()
161
+ if tot < 5:
162
+ continue
163
+ for kk in range(a, b):
164
+ p_dq[kk] = max(habs[kk] / tot, 1e-3)
165
+ p_sq[kk] = 1.0 / (b - a)
166
+ kk = np.clip(k, 0, 41)
167
+ ok = (kk > 0) & np.isfinite(p_dq[kk])
168
+ contrib = np.where(ok, np.log(np.nan_to_num(p_sq[kk], nan=1)) - np.log(np.nan_to_num(p_dq[kk], nan=1)), 0)
169
+ llr += np.clip(contrib, -4, 4).astype(np.float32)
170
+ used += 1
171
+ if used < 2:
172
+ return None
173
+ llr = _box(llr, 2) # 5x5-block neighbourhood
174
+ prob = 1.0 / (1.0 + np.exp(-llr))
175
+ tex = gray[:nby * 8, :nbx * 8].reshape(nby, 8, nbx, 8).std(axis=(1, 3)) > 2.0
176
+ return {"prob": prob.astype(np.float32), "texture": tex}
177
+
178
+
179
+ def _grid_profile(gray):
180
+ """Blockiness per grid origin (0..7), horizontally and vertically: the
181
+ mean absolute step between neighbouring pixels, grouped by position
182
+ modulo 8. A JPEG grid starting at origin o has its block edges between
183
+ columns o-1 and o, so steps there are larger."""
184
+ g = gray.astype(np.float32)
185
+ dx = np.abs(g[:, 1:] - g[:, :-1]) # step between x and x+1
186
+ dy = np.abs(g[1:, :] - g[:-1, :])
187
+ # remove texture: compare each step to the mean of its two neighbours
188
+ rx = np.maximum(dx[:, 1:-1] - 0.5 * (dx[:, :-2] + dx[:, 2:]), 0).mean(axis=0)
189
+ ry = np.maximum(dy[1:-1, :] - 0.5 * (dy[:-2, :] + dy[2:, :]), 0).mean(axis=1)
190
+ # rx[i] is the step between columns i+1 and i+2 -> origin (i+2) % 8
191
+ px = np.array([rx[(np.arange(len(rx)) + 2) % 8 == o].mean() for o in range(8)])
192
+ py = np.array([ry[(np.arange(len(ry)) + 2) % 8 == o].mean() for o in range(8)])
193
+ return px, py
194
+
195
+
196
+ def _peak(p):
197
+ o = int(np.argmax(p))
198
+ rest = np.median(np.delete(p, o))
199
+ return o, float(p[o] / (rest + 1e-6))
200
+
201
+
202
+ def grid_analysis(gray, win=96):
203
+ """Global grid origin + per-window score of a DIFFERENT grid (NADJPEG /
204
+ blocking). Score = log-ratio of the strongest other origin to the global
205
+ one, smoothed over neighbouring windows."""
206
+ px, py = _grid_profile(gray)
207
+ ox, rx = _peak(px)
208
+ oy, ry = _peak(py)
209
+ glob = {"x": ox, "y": oy, "strength": round(min(rx, ry), 2), "clear": rx > 1.3 and ry > 1.3}
210
+ h, w = gray.shape
211
+ stride = max(16, int(np.ceil(max(h, w) / 110 / 8)) * 8)
212
+ H, W = (h - win) // stride + 1, (w - win) // stride + 1
213
+ if H < 3 or W < 3:
214
+ return glob, None
215
+ sc = np.zeros((H, W), dtype=np.float32)
216
+ val = np.zeros((H, W), dtype=bool)
217
+ for i in range(H):
218
+ for j in range(W):
219
+ t = gray[i * stride:i * stride + win, j * stride:j * stride + win]
220
+ if t.std() < 6:
221
+ continue
222
+ a, b = _grid_profile(t)
223
+ la, lb = int(np.argmax(a)), int(np.argmax(b))
224
+ val[i, j] = True
225
+ # Expected grids: the global one and (0, 0) - the grid of the last
226
+ # save when the picture was cropped and saved again.
227
+ if (la, lb) not in ((ox, oy), (0, 0)):
228
+ ea = max(a[ox], a[0], 1e-3)
229
+ eb = max(b[oy], b[0], 1e-3)
230
+ sc[i, j] = np.log(max(a[la] / ea, 1)) + np.log(max(b[lb] / eb, 1))
231
+ sm = _box(sc, 2)
232
+ return glob, {"score": sm, "valid": val, "hot": (sm > 0.8) & val, "stride": stride, "win": win}
233
+
234
+
235
+ def components(mask, min_frac=0.01):
236
+ """Bounding boxes (fractions of the map) of connected hot regions."""
237
+ m = mask.astype(np.uint8)
238
+ n, lab, st, _ = cv2.connectedComponentsWithStats(m, connectivity=8)
239
+ H, W = mask.shape
240
+ out = []
241
+ for i in range(1, n):
242
+ x, y, w, h, a = st[i]
243
+ if a / (H * W) >= min_frac:
244
+ out.append({"box": [x / W, y / H, (x + w) / W, (y + h) / H], "area": a / (H * W)})
245
+ return sorted(out, key=lambda r: -r["area"])
246
+
247
+
248
+ def crop_png(rgb, box, pad=0.04, max_side=520):
249
+ h, w = rgb.shape[:2]
250
+ x0 = int(max(0, (box[0] - pad) * w)); y0 = int(max(0, (box[1] - pad) * h))
251
+ x1 = int(min(w, (box[2] + pad) * w)); y1 = int(min(h, (box[3] + pad) * h))
252
+ if x1 - x0 < 8 or y1 - y0 < 8:
253
+ return None
254
+ c = rgb[y0:y1, x0:x1].copy()
255
+ # outline the detected region inside the crop
256
+ bx0, by0 = int(box[0] * w) - x0, int(box[1] * h) - y0
257
+ bx1, by1 = int(box[2] * w) - x0, int(box[3] * h) - y0
258
+ cv2.rectangle(c, (bx0, by0), (bx1 - 1, by1 - 1), (239, 68, 68), max(1, int(max(c.shape[:2]) / 260)))
259
+ s = max_side / max(c.shape[:2])
260
+ if s < 1:
261
+ c = cv2.resize(c, (int(c.shape[1] * s), int(c.shape[0] * s)), interpolation=cv2.INTER_AREA)
262
+ buf = io.BytesIO()
263
+ Image.fromarray(c).save(buf, "JPEG", quality=88)
264
+ return "data:image/jpeg;base64," + base64.b64encode(buf.getvalue()).decode()
265
+
266
+
267
+ def fuse(maps, shape=(96, 96)):
268
+ """maps: list of (array 0..1, weight). Weighted average on a common grid."""
269
+ acc = np.zeros(shape, dtype=np.float32)
270
+ ws = 0.0
271
+ for m, w in maps:
272
+ if m is None or w <= 0:
273
+ continue
274
+ acc += w * cv2.resize(np.clip(m, 0, 1).astype(np.float32), (shape[1], shape[0]), interpolation=cv2.INTER_LINEAR)
275
+ ws += w
276
+ return acc / ws if ws else None
route/jpeg_forensics.py CHANGED
@@ -290,6 +290,7 @@ def analyze(data, make=None):
290
  except Exception:
291
  make = ""
292
  out = {"format": fmt, "size": [int(rgb_full.shape[1]), int(rgb_full.shape[0])]}
 
293
 
294
  if fmt != "JPEG":
295
  add("info", f"الملف بصيغة {fmt or 'غير معروفة'} وليس JPEG، لذا لا تنطبق فحوص جداول الضغط والضغط المزدوج والصورة المصغّرة. فحص شبكة الكتل والأشباح يُطبَّق على المحتوى.",
@@ -330,6 +331,8 @@ def analyze(data, make=None):
330
  # saved once overall: areas WITH a strong double-compression trace stand out
331
  minority = np.where(valid, ldq > 0.3, False)
332
  mfrac = float(minority[valid].mean())
 
 
333
  base = rgb_full[:gray_grid.shape[0], :gray_grid.shape[1]]
334
  maps.append({"key": "dq", "ar": "خريطة الضغط المزدوج", "en": "Double-compression map",
335
  "help_ar": "المناطق الملوّنة تختلف في سلوك الضغط عن معظم الصورة (حُفظت عددًا مختلفًا من المرات) — قد تكون مضافة من مصدر آخر.",
@@ -343,6 +346,7 @@ def analyze(data, make=None):
343
  g = _ghosts(small)
344
  if g:
345
  q, m, contrast = g
 
346
  maps.append({"key": "ghost", "ar": f"أشباح JPEG (جودة {q})", "en": f"JPEG ghosts (quality {q})",
347
  "help_ar": "المناطق الحمراء تتصرّف كأنها حُفظت سابقًا بجودة مختلفة عن باقي الصورة.",
348
  "help_en": "Red areas behave as if previously saved at a different quality than the rest.",
@@ -355,6 +359,7 @@ def analyze(data, make=None):
355
  th = _exif_thumbnail(img, rgb_full)
356
  if th:
357
  out["thumbnail"] = th
 
358
  if th["aspect_mismatch"] or th["similarity"] < 0.9:
359
  add("high", "الصورة المصغّرة المحفوظة داخل الملف لا تطابق الصورة الحالية — مؤشر قوي على تعديل الصورة بعد التقاطها (تحتفظ المصغّرة غالبًا بالأصل).",
360
  "The thumbnail stored in the file does not match the current picture — a strong sign it was edited after capture (the thumbnail often keeps the original).")
 
290
  except Exception:
291
  make = ""
292
  out = {"format": fmt, "size": [int(rgb_full.shape[1]), int(rgb_full.shape[0])]}
293
+ raw = out["_raw"] = {} # numeric results for the evidence builder (removed before sending)
294
 
295
  if fmt != "JPEG":
296
  add("info", f"الملف بصيغة {fmt or 'غير معروفة'} وليس JPEG، لذا لا تنطبق فحوص جداول الضغط والضغط المزدوج والصورة المصغّرة. فحص شبكة الكتل والأشباح يُطبَّق على المحتوى.",
 
331
  # saved once overall: areas WITH a strong double-compression trace stand out
332
  minority = np.where(valid, ldq > 0.3, False)
333
  mfrac = float(minority[valid].mean())
334
+ raw["dq_local"] = {"map": minority.astype(np.float32), "frac": mfrac,
335
+ "extent": [gray_grid.shape[1] / gray_full.shape[1], gray_grid.shape[0] / gray_full.shape[0]]}
336
  base = rgb_full[:gray_grid.shape[0], :gray_grid.shape[1]]
337
  maps.append({"key": "dq", "ar": "خريطة الضغط المزدوج", "en": "Double-compression map",
338
  "help_ar": "المناطق الملوّنة تختلف في سلوك الضغط عن معظم الصورة (حُفظت عددًا مختلفًا من المرات) — قد تكون مضافة من مصدر آخر.",
 
346
  g = _ghosts(small)
347
  if g:
348
  q, m, contrast = g
349
+ raw["ghost_local"] = {"map": m, "contrast": contrast, "quality": q}
350
  maps.append({"key": "ghost", "ar": f"أشباح JPEG (جودة {q})", "en": f"JPEG ghosts (quality {q})",
351
  "help_ar": "المناطق الحمراء تتصرّف كأنها حُفظت سابقًا بجودة مختلفة عن باقي الصورة.",
352
  "help_en": "Red areas behave as if previously saved at a different quality than the rest.",
 
359
  th = _exif_thumbnail(img, rgb_full)
360
  if th:
361
  out["thumbnail"] = th
362
+ raw["thumbnail"] = th
363
  if th["aspect_mismatch"] or th["similarity"] < 0.9:
364
  add("high", "الصورة المصغّرة المحفوظة داخل الملف لا تطابق الصورة الحالية — مؤشر قوي على تعديل الصورة بعد التقاطها (تحتفظ المصغّرة غالبًا بالأصل).",
365
  "The thumbnail stored in the file does not match the current picture — a strong sign it was edited after capture (the thumbnail often keeps the original).")
templates/forensics.html CHANGED
@@ -59,6 +59,26 @@ input[type=range]{width:100%}
59
  .fb button.ok{color:var(--ok);border-color:rgba(34,197,94,.45)}.fb button.no{color:var(--bad);border-color:rgba(239,68,68,.45)}
60
  .fb button.sel{background:var(--acc);color:#fff;border-color:var(--acc)}
61
  .fb input{width:100%;padding:8px 10px;border-radius:8px;border:1px solid var(--line);background:var(--panel2);color:var(--txt);font:inherit;font-size:12.5px;margin:4px 0 8px}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
  @media (max-width:700px){main{padding:0}.grid{grid-template-columns:1fr}.card{padding:12px}}
63
  </style>
64
  </head>
@@ -140,7 +160,7 @@ if(P.get('theme')==='light') document.documentElement.dataset.theme='light';
140
  const T={
141
  ar:{tabJ:'كشف التلاعب',tabP:'مطابقة بصمة الكاميرا',
142
  jTitle:'كشف التلاعب في الصورة',
143
- jSub:'نموذج مدرّب لتحديد مواضع التلاعب، مع فحوص ضغط كلاسيكية: جداول الضغط وتقدير جودة الحفظ، والضغط المزدوج على مستوى الصورة وكل منطقة، وأشباح JPEG، والصورة المصغّرة المحفوظة داخل الملف. تُبيّن الخرائط المناطق التي يختلف سجل ضغطها عن باقي الصورة.',
144
  jDrop:'اسحب الصورة إلى هنا أو اضغط للاختيار',analyzing:'جارٍ التحليل…',
145
  vHigh:'مؤشرات قوية على التعديل',vMed:'مؤشرات تستدعي المراجعة',vLow:'لم تظهر مؤشرات تعديل واضحة',
146
  findings:'النتائج',maps:'الخرائط',zoomHint:'اضغط على الخريطة لتكبيرها',original:'الصورة الأصلية',
@@ -165,6 +185,21 @@ const T={
165
  progressive:'ترميز تدريجي',subsampling:'أخذ عينات الألوان',icc:'ملف الألوان (ICC)',
166
  platNote:'يعتمد التحديد على سمات معروفة لكل منصة (الأبعاد، جداول الضغط، البيانات المتبقية، اسم الملف)، وقد تتغيّر هذه السمات أو تتشابه بين فيسبوك وإنستغرام، فهو مؤشر للتوجيه.',
167
  noteJ:'هذه الفحوص مؤشرات وليست دليلًا قاطعًا: إعادة الحفظ عبر المنصات وتطبيقات المراسلة تُحدث بعض الآثار نفسها دون تلاعب، وغياب المؤشرات لا يُثبت الأصالة.',
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
168
  pTitle:'مطابقة بصمة حسّاس الكاميرا (PRNU)',
169
  pSub:'لكل حسّاس كاميرا بصمة دقيقة ثابتة تظهر في كل صورة يلتقطها. تُستخرج البصمة من صور مرجعية مؤكدة من الجهاز، ثم تُقارن بالصورة محل الفحص لمعرفة ما إذا كانت ملتقطة بالجهاز نفسه.',
170
  pRefs:'1) الصور المرجعية من الجهاز',
@@ -180,7 +215,7 @@ const T={
180
  noteP:'المطابقة مؤشر علمي قوي لكنه ليس معتمدًا كدليل رسمي من هذا البرنامج. النتيجة السلبية لا تنفي بالضرورة أن الصورة من الجهاز إذا كانت قد عُدِّلت أو أُعيد تحجيمها.'},
181
  en:{tabJ:'Tampering detection',tabP:'Camera fingerprint match',
182
  jTitle:'Image tampering detection',
183
- jSub:'A trained model that localizes manipulation, plus classic compression checks: quantization tables and estimated save quality, double compression for the whole picture and per region, JPEG ghosts, and the thumbnail stored in the file. The maps show areas whose compression history differs from the rest.',
184
  jDrop:'Drag an image here or tap to choose',analyzing:'Analyzing…',
185
  vHigh:'Strong signs of editing',vMed:'Signs that need review',vLow:'No clear signs of editing',
186
  findings:'Findings',maps:'Maps',zoomHint:'Tap a map to zoom',original:'Original image',
@@ -205,6 +240,21 @@ const T={
205
  progressive:'Progressive encoding',subsampling:'Chroma subsampling',icc:'Colour profile (ICC)',
206
  platNote:'Based on known per-platform traits (dimensions, tables, remaining metadata, file name). These change over time and Facebook/Instagram can look alike, so treat it as a lead.',
207
  noteJ:'These checks are indicators, not proof: re-saving by platforms and messaging apps leaves some of the same traces without tampering, and no signs does not prove authenticity.',
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
208
  pTitle:'Camera sensor fingerprint (PRNU)',
209
  pSub:'Every camera sensor leaves a faint, fixed pattern in each photo. A fingerprint is estimated from confirmed reference photos of a device and compared with the questioned photo to tell whether the same device took it.',
210
  pRefs:'1) Reference photos from the device',
@@ -280,8 +330,12 @@ function againBtn(){return `<div class="row"><button class="btn sec" id="jAgain"
280
  function bindAgain(){const b=$('jAgain'); if(b) b.onclick=()=>{$('jOut').innerHTML='';$('jDropCard').style.display='';};}
281
  function renderJ(d,url){
282
  const v=d.status==='high'?['high',T.vHigh]:d.status==='medium'?['medium',T.vMed]:['low',T.vLow];
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>`;});
@@ -302,7 +356,9 @@ function renderJ(d,url){
302
  `<div class="kv"><span>${T.format}</span><span>${esc(d.format)}</span></div>`+
303
  `<div class="kv"><span>${T.size}</span><span>${d.size[0]} × ${d.size[1]}</span></div>`+
304
  (q.quality!=null?`<div class="kv"><span>${T.quality}</span><span>${q.quality}</span></div><div class="kv"><span>${T.stdTables}</span><span>${q.standard_tables?T.yes:T.no}</span></div>`:'')+
305
- (d.double_compression_score!=null?`<div class="kv"><span>${T.dqScore}</span><span>${d.double_compression_score}</span></div>`:'')+`</div>`;
 
 
306
  if(q.all_tables&&q.all_tables.length){
307
  h+=`<div class="card"><h2>${T.qtTitle}</h2><div class="mut" style="margin-bottom:10px">${T.qtSub}</div><div class="grid">`;
308
  q.all_tables.forEach(t=>{
@@ -325,6 +381,76 @@ function renderJ(d,url){
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 ----------
@@ -385,8 +511,18 @@ function ghostCard(file){
385
  `<input type="range" id="gRange" min="0" max="${Q.length-1}" value="${qIdx}">`+
386
  `<div class="gwrap" id="gWrap" style="margin-top:8px"><img id="gImg" src="${g.preview}"><canvas id="gCanvas"></canvas><div class="gsel" id="gSel"></div></div>`+
387
  `<div class="row" style="margin-top:10px"><button class="btn sec" id="gRegionBtn">${T.gPick}</button><button class="btn sec" id="gClear" style="display:none">${T.gClear}</button></div>`+
388
- `<div class="mut" id="gPickHint" style="display:none;margin-top:6px">${T.gPickHint}</div></div>`;
 
389
  plot(); $('gImg').onload=draw; if($('gImg').complete) draw();
 
 
 
 
 
 
 
 
 
390
  $('gRange').oninput=e=>{qIdx=+e.target.value; draw(); plot();};
391
  let picking=false,start=null;
392
  $('gRegionBtn').onclick=()=>{picking=true;$('gPickHint').style.display='';};
 
59
  .fb button.ok{color:var(--ok);border-color:rgba(34,197,94,.45)}.fb button.no{color:var(--bad);border-color:rgba(239,68,68,.45)}
60
  .fb button.sel{background:var(--acc);color:#fff;border-color:var(--acc)}
61
  .fb input{width:100%;padding:8px 10px;border-radius:8px;border:1px solid var(--line);background:var(--panel2);color:var(--txt);font:inherit;font-size:12.5px;margin:4px 0 8px}
62
+ .ev{display:flex;flex-wrap:wrap;gap:8px}
63
+ .ev button{display:inline-flex;align-items:center;gap:8px;padding:9px 13px;border-radius:11px;border:1px solid var(--line);background:var(--panel2);color:var(--txt);font:inherit;font-size:13px;font-weight:700;cursor:pointer}
64
+ .ev button i{width:9px;height:9px;border-radius:50%;flex:0 0 9px}
65
+ .ev button.on{outline:2px solid var(--acc);outline-offset:1px}
66
+ .evd{margin-top:12px;border:1px solid var(--line);border-radius:12px;padding:14px;background:var(--panel2)}
67
+ .evd h4{margin:12px 0 4px;font-size:12.5px;color:var(--mut);font-weight:700}
68
+ .evd h4:first-of-type{margin-top:0}
69
+ .evd p{margin:0;font-size:13.5px;line-height:1.75;white-space:pre-line}
70
+ .evd .ref{font-size:12px;direction:ltr;text-align:left;unicode-bidi:plaintext;color:var(--mut)}
71
+ .evd img{max-width:100%;border-radius:10px;margin-top:6px;cursor:zoom-in;border:1px solid var(--line)}
72
+ .bar{align-self:stretch;width:100%;height:10px;border-radius:6px;background:var(--panel2);border:1px solid var(--line);overflow:hidden;display:flex}
73
+ .bar span{display:block;height:100%}
74
+ .op{display:grid;grid-template-columns:1fr 1fr;gap:12px}
75
+ @media (max-width:700px){.op{grid-template-columns:1fr}}
76
+ .reg{display:grid;grid-template-columns:repeat(auto-fill,minmax(220px,1fr));gap:12px}
77
+ .reg img{width:100%;border-radius:10px;cursor:zoom-in;border:1px solid var(--line)}
78
+ .dct select{padding:7px 10px;border-radius:8px;border:1px solid var(--line);background:var(--panel2);color:var(--txt);font:inherit}
79
+ .gt{display:grid;grid-template-columns:repeat(auto-fill,minmax(120px,1fr));gap:8px;margin-top:10px}
80
+ .gt div{position:relative}.gt img{width:100%;display:block;border-radius:8px}.gt canvas{position:absolute;inset:0;width:100%;height:100%;border-radius:8px;image-rendering:pixelated}
81
+ .gt b{display:block;text-align:center;font-size:12px;margin-top:3px}
82
  @media (max-width:700px){main{padding:0}.grid{grid-template-columns:1fr}.card{padding:12px}}
83
  </style>
84
  </head>
 
160
  const T={
161
  ar:{tabJ:'كشف التلاعب',tabP:'مطابقة بصمة الكاميرا',
162
  jTitle:'كشف التلاعب في الصورة',
163
+ jSub:'فحوص مستقلة منشورة علميًا: نموذج تحديد مواضع التلاعب، وADJPEG وNADJPEG، وأشباح JPEG، ومخطط DCT، وجداول التكميم، والصورة المصغّرة، وبصمة الملف. كل فحص يظهر كدليل مستقل بتفاصيله، ويُبنى الرأي من أوزانها، مع فصل سلامة المحتوى عن سجل المعالجة.',
164
  jDrop:'اسحب الصورة إلى هنا أو اضغط للاختيار',analyzing:'جارٍ التحليل…',
165
  vHigh:'مؤشرات قوية على التعديل',vMed:'مؤشرات تستدعي المراجعة',vLow:'لم تظهر مؤشرات تعديل واضحة',
166
  findings:'النتائج',maps:'الخرائط',zoomHint:'اضغط على الخريطة لتكبيرها',original:'الصورة الأصلية',
 
185
  progressive:'ترميز تدريجي',subsampling:'أخذ عينات الألوان',icc:'ملف الألوان (ICC)',
186
  platNote:'يعتمد التحديد على سمات معروفة لكل منصة (الأبعاد، جداول الضغط، البيانات المتبقية، اسم الملف)، وقد تتغيّر هذه السمات أو تتشابه بين فيسبوك وإنستغرام، فهو مؤشر للتوجيه.',
187
  noteJ:'هذه الفحوص مؤشرات وليست دليلًا قاطعًا: إعادة الحفظ عبر المنصات وتطبيقات المراسلة تُحدث بعض الآثار نفسها دون تلاعب، وغياب المؤشرات لا يُثبت الأصالة.',
188
+ evTitle:'الأدلة',evSub:'كل زر فحص مستقل. اضغطي عليه لعرض ما وُجد، ولماذا يُعدّ مؤشرًا، والطريقة ومرجعها العلمي، والفلتر المقابل في Amped Authenticate، وحدود الطريقة، ووزنه في الرأي.',
189
+ rSusp:'مؤشر قوي',rAtt:'يستدعي المراجعة',rOk:'متسق',rNa:'لا ينطبق',rInfo:'معلومة',
190
+ dFound:'ما وُجد',dWhy:'لماذا يُعدّ مؤشرًا',dMethod:'الطريقة',dAmped:'الفلتر المقابل في Amped Authenticate',dRef:'المرجع العلمي',dLimits:'حدود الطريقة',dMeasure:'القياسات',dWeight:'الوزن في الرأي',dMap:'الخريطة',
191
+ wText:(w,c)=>`وزنها ${w}% من الرأي، وأضافت ${c} نقطة من 100 إلى درجة الاشتباه.`,wNone:'لا تدخل في درجة الاشتباه (تخص سجل المعالجة أو للتوثيق).',
192
+ opContent:'سلامة المحتوى',opHistory:'سجل المعالجة',opScore:s=>`درجة الاشتباه ${s} من 100`,
193
+ hOrig:'لا مؤشرات على إعادة الحفظ أو القص؛ قد يكون الملف أصليًا من الجهاز.',hEdited:'الملف ليس الأصل الصادر من الجهاز:',
194
+ hf:{qt:'حُفظ بجداول برنامج أو منصة',double:'حُفظ بصيغة JPEG أكثر من مرة',cropped:'قُصّ بعد الحفظ',platform:'مرّ بمنصة تواصل'},
195
+ hNote:'إعادة الحفظ أو القص ليست تلاعبًا بالمحتوى بالضرورة، لكنها تعني أن الملف ليس الأصل، وتُضعف بعض الفحوص.',
196
+ opLimited:'عدد الفحوص التي انطبقت على هذه الصورة قليل، لذا الرأي محدود ولا يكفي فحص واحد لرفعه.',opHow:'كيف حُسب الرأي',opHowText:(n)=>`متوسط موزون لدرجات ${n} فحوص مستقلة تخص المحتوى. 50 فأكثر: مؤشرات قوية، ومن 28 إلى 49: يستدعي المراجعة.`,
197
+ ampedNote:'TruScan لا يستخدم برنامج Amped. أسماء الفلاتر مذكورة ليتمكّن أي خبير من إعادة الفحص نفسه ببرنامج معتمد والتحقق من النتيجة.',
198
+ regTitle:'المناطق المشتبه بها',regSub:'قصّات من الصورة للمناطق التي ظهرت في خريطة الدمج، مع الطرق التي اتفقت عليها.',regArea:a=>`نحو ${a}% من الصورة`,regBy:'رصدتها:',
199
+ hashTitle:'بصمة الملف',
200
+ dctTitle:'مخطط معاملات DCT (DCT Plot)',dctSub:'مدرّج قيم معامل DCT في كل كتل الصورة. الحفظ مرة واحدة يعطي شكلًا أملس متناقصًا؛ الحفظ مرتين يعطي «مشطًا» تتباعد أعمدته بانتظام، وتباعدها يكشف جودة الحفظ الأول. الأعمدة الحمراء قيم يجب أن تكون شبه فارغة لو حُفظت الصورة كلها مرتين؛ امتلاؤها يعني أن جزءًا من الصورة لم يمر بالحفظ الأول.',
201
+ dctCoef:'المعامل',dctQ2:'خطوة الحفظ الأخير',dctQ1:'خطوة الحفظ الأول المقدّرة',dctFirst:'جودة الحفظ الأول المقدّرة',dctNone:'لا يظهر مشط',dctAll:n=>`مشط في ${n} من 15 معاملًا`,
202
+ gtTitle:'خريطة الأشباح لكل جودة',
203
  pTitle:'مطابقة بصمة حسّاس الكاميرا (PRNU)',
204
  pSub:'لكل حسّاس كاميرا بصمة دقيقة ثابتة تظهر في كل صورة يلتقطها. تُستخرج البصمة من صور مرجعية مؤكدة من الجهاز، ثم تُقارن بالصورة محل الفحص لمعرفة ما إذا كانت ملتقطة بالجهاز نفسه.',
205
  pRefs:'1) الصور المرجعية من الجهاز',
 
215
  noteP:'المطابقة مؤشر علمي قوي لكنه ليس معتمدًا كدليل رسمي من هذا البرنامج. النتيجة السلبية لا تنفي بالضرورة أن الصورة من الجهاز إذا كانت قد عُدِّلت أو أُعيد تحجيمها.'},
216
  en:{tabJ:'Tampering detection',tabP:'Camera fingerprint match',
217
  jTitle:'Image tampering detection',
218
+ jSub:'Independent, published checks: forgery localization model, ADJPEG and NADJPEG, JPEG ghosts, DCT plot, quantization tables, thumbnail and file hash. Each appears as its own piece of evidence with details; the opinion is built from their weights, keeping content integrity separate from processing history.',
219
  jDrop:'Drag an image here or tap to choose',analyzing:'Analyzing…',
220
  vHigh:'Strong signs of editing',vMed:'Signs that need review',vLow:'No clear signs of editing',
221
  findings:'Findings',maps:'Maps',zoomHint:'Tap a map to zoom',original:'Original image',
 
240
  progressive:'Progressive encoding',subsampling:'Chroma subsampling',icc:'Colour profile (ICC)',
241
  platNote:'Based on known per-platform traits (dimensions, tables, remaining metadata, file name). These change over time and Facebook/Instagram can look alike, so treat it as a lead.',
242
  noteJ:'These checks are indicators, not proof: re-saving by platforms and messaging apps leaves some of the same traces without tampering, and no signs does not prove authenticity.',
243
+ evTitle:'Evidence',evSub:'Each button is an independent check. Tap it to see what was found, why it is an indicator, the method and its reference, the matching Amped Authenticate filter, the method limits, and its weight in the opinion.',
244
+ rSusp:'strong indicator',rAtt:'needs review',rOk:'consistent',rNa:'not applicable',rInfo:'information',
245
+ dFound:'What was found',dWhy:'Why it is an indicator',dMethod:'Method',dAmped:'Matching Amped Authenticate filter',dRef:'Scientific reference',dLimits:'Limits of the method',dMeasure:'Measurements',dWeight:'Weight in the opinion',dMap:'Map',
246
+ wText:(w,c)=>`Weight ${w}% of the opinion; it added ${c} points out of 100 to the suspicion score.`,wNone:'Not part of the suspicion score (processing history or documentation).',
247
+ opContent:'Content integrity',opHistory:'Processing history',opScore:s=>`Suspicion score ${s} / 100`,
248
+ hOrig:'No sign of re-saving or cropping; the file may be the device original.',hEdited:'The file is not the device original:',
249
+ hf:{qt:'saved with program or platform tables',double:'saved as JPEG more than once',cropped:'cropped after saving',platform:'passed through a social platform'},
250
+ hNote:'Re-saving or cropping is not necessarily content tampering, but the file is not the original and some checks become weaker.',
251
+ opLimited:'Few checks applied to this picture, so the opinion is limited; one check alone cannot raise it.',opHow:'How the opinion is computed',opHowText:(n)=>`Weighted average of ${n} independent content checks. 50 or more: strong signs; 28–49: needs review.`,
252
+ ampedNote:'TruScan does not run Amped software. Filter names are given so any examiner can repeat the same analysis with certified software and verify the result.',
253
+ regTitle:'Suspicious regions',regSub:'Crops of the areas highlighted by the fusion map, with the methods that agree on them.',regArea:a=>`about ${a}% of the picture`,regBy:'Found by:',
254
+ hashTitle:'File hash',
255
+ dctTitle:'DCT plot',dctSub:'Histogram of one DCT coefficient over all blocks. A single save gives a smooth, decaying shape; a double save gives a comb of regularly spaced bars whose spacing reveals the first save quality. Red bars are values that should be nearly empty if the whole picture was saved twice; if they are filled, part of the picture skipped the first save.',
256
+ dctCoef:'Coefficient',dctQ2:'Last save step',dctQ1:'Estimated first save step',dctFirst:'Estimated first save quality',dctNone:'no comb',dctAll:n=>`comb in ${n} of 15 coefficients`,
257
+ gtTitle:'Ghost map per quality',
258
  pTitle:'Camera sensor fingerprint (PRNU)',
259
  pSub:'Every camera sensor leaves a faint, fixed pattern in each photo. A fingerprint is estimated from confirmed reference photos of a device and compared with the questioned photo to tell whether the same device took it.',
260
  pRefs:'1) Reference photos from the device',
 
330
  function bindAgain(){const b=$('jAgain'); if(b) b.onclick=()=>{$('jOut').innerHTML='';$('jDropCard').style.display='';};}
331
  function renderJ(d,url){
332
  const v=d.status==='high'?['high',T.vHigh]:d.status==='medium'?['medium',T.vMed]:['low',T.vLow];
333
+ let h='';
334
+ if(d.opinion&&d.evidence){ h+=opinionHtml(d,v)+evidenceHtml(d)+regionsHtml(d); }
335
+ else{
336
+ h+=`<div class="card"><div class="verdict ${v[0]}"><div><b>${v[1]}</b></div></div></div>`;
337
+ 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>`;
338
+ }
339
  h+=`<div class="card"><h2>${T.maps}</h2><div class="mut" style="margin-bottom:10px">${T.zoomHint}</div><div class="grid">`;
340
  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>`;
341
  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>`;});
 
356
  `<div class="kv"><span>${T.format}</span><span>${esc(d.format)}</span></div>`+
357
  `<div class="kv"><span>${T.size}</span><span>${d.size[0]} × ${d.size[1]}</span></div>`+
358
  (q.quality!=null?`<div class="kv"><span>${T.quality}</span><span>${q.quality}</span></div><div class="kv"><span>${T.stdTables}</span><span>${q.standard_tables?T.yes:T.no}</span></div>`:'')+
359
+ (d.double_compression_score!=null?`<div class="kv"><span>${T.dqScore}</span><span>${d.double_compression_score}</span></div>`:'')+
360
+ (d.hashes?`<div class="kv"><span>MD5</span><span style="font:12px ui-monospace,monospace;word-break:break-all">${d.hashes.md5}</span></div><div class="kv"><span>SHA-256</span><span style="font:12px ui-monospace,monospace;word-break:break-all">${d.hashes.sha256}</span></div>`:'')+`</div>`;
361
+ if(d.dct_plot) h+=`<div class="card dct" id="dctCard"></div>`;
362
  if(q.all_tables&&q.all_tables.length){
363
  h+=`<div class="card"><h2>${T.qtTitle}</h2><div class="mut" style="margin-bottom:10px">${T.qtSub}</div><div class="grid">`;
364
  q.all_tables.forEach(t=>{
 
381
  $('jOut').innerHTML=h; bindAgain();
382
  $('jOut').querySelectorAll('img[data-z]').forEach(i=>i.onclick=()=>window.tsZoom&&window.tsZoom(i.dataset.z));
383
  $('jOut').querySelectorAll('[data-ela]').forEach(b=>b.onclick=()=>window.tsEla&&window.tsEla(b.dataset.ela));
384
+ if(d.evidence) bindEvidence(d);
385
+ if(d.dct_plot) dctPlot(d.dct_plot);
386
+ }
387
+
388
+ // ---------- evidence ----------
389
+ const RES={suspicious:['var(--bad)','rSusp'],attention:['var(--warn)','rAtt'],consistent:['var(--ok)','rOk'],na:['var(--mut)','rNa'],info:['var(--info)','rInfo']};
390
+ const L=(o,k)=>o[k+(LANG==='en'?'_en':'_ar')];
391
+ function opinionHtml(d,v){
392
+ const o=d.opinion, sc=o.content_score==null?null:Math.round(o.content_score*100);
393
+ const ev=d.evidence.filter(i=>i.contribution!=null).sort((a,b)=>b.contribution-a.contribution);
394
+ const cols=['#ef4444','#f59e0b','#a855f7','#3b82f6','#14b8a6','#ec4899'];
395
+ let bar=`<div class="bar" style="margin:10px 0 6px">`+ev.map((i,k)=>`<span title="${esc(L(i,'name'))}" style="width:${i.contribution}%;background:${cols[k%cols.length]}"></span>`).join('')+`</div>`;
396
+ bar+=`<div class="mut">`+ev.filter(i=>i.contribution>=0.5).map((i,k)=>`<span style="color:${cols[ev.indexOf(i)%cols.length]};font-weight:700">■</span> ${esc(L(i,'name'))} ${i.contribution}`).join(' &nbsp; ')+`</div>`;
397
+ const hist=o.history_flags.length?`<b>${T.hEdited}</b><ul style="margin:6px 0 0;padding-inline-start:18px">`+o.history_flags.map(f=>`<li>${T.hf[f]||f}</li>`).join('')+`</ul>`:`<b>${T.hOrig}</b>`;
398
+ return `<div class="card"><div class="op">`+
399
+ `<div class="verdict ${v[0]}" style="flex-direction:column;gap:4px"><div class="mut">${T.opContent}</div><b>${v[1]}</b>${sc!=null?`<div style="font-size:13px">${T.opScore(sc)}</div>`:''}${bar}`+
400
+ (o.overrides||[]).map(r=>`<div class="mut" style="color:var(--warn)">${esc(LANG==='en'?r[1]:r[0])}</div>`).join('')+`</div>`+
401
+ `<div class="verdict ${o.history_flags.length?'medium':'low'}" style="flex-direction:column;gap:4px"><div class="mut">${T.opHistory}</div><div style="font-size:13.5px;line-height:1.7">${hist}</div><div class="mut">${T.hNote}</div></div>`+
402
+ `</div>${o.limited?`<div class="note" style="color:var(--warn)">${T.opLimited}</div>`:''}<div class="note"><b>${T.opHow}:</b> ${T.opHowText(o.checks_used)}</div></div>`;
403
+ }
404
+ function evidenceHtml(d){
405
+ const order={content:0,history:1,file:2}, its=[...d.evidence].sort((a,b)=>(order[a.group]-order[b.group]));
406
+ return `<div class="card"><h2>${T.evTitle}</h2><div class="mut" style="margin-bottom:10px">${T.evSub}</div><div class="ev">`+
407
+ its.map(i=>{const r=RES[i.result]||RES.info;return `<button data-ev="${i.key}" title="${T[r[1]]}"><i style="background:${r[0]}"></i>${esc(L(i,'name'))}<span class="mut" style="font-weight:500">· ${T[r[1]]}</span></button>`;}).join('')+
408
+ `</div><div id="evDetail"></div><div class="note">${T.ampedNote}</div></div>`;
409
+ }
410
+ function regionsHtml(d){
411
+ if(!d.regions||!d.regions.length) return '';
412
+ const nm=k=>{const i=d.evidence.find(e=>e.key===k);return i?L(i,'name'):k;};
413
+ return `<div class="card"><h2>${T.regTitle}</h2><div class="mut" style="margin-bottom:10px">${T.regSub}</div><div class="reg">`+
414
+ d.regions.filter(r=>r.crop).map(r=>`<div><img src="${r.crop}" data-z="${r.crop}"><div style="font-size:13px;margin-top:6px"><b>${T.regArea((r.area*100).toFixed(1))}</b></div><div class="mut">${T.regBy} ${r.methods.map(nm).map(esc).join('، ')}</div></div>`).join('')+`</div></div>`;
415
+ }
416
+ function bindEvidence(d){
417
+ const box=$('evDetail'); let cur=null;
418
+ document.querySelectorAll('[data-ev]').forEach(b=>b.onclick=()=>{
419
+ const k=b.dataset.ev; document.querySelectorAll('[data-ev]').forEach(x=>x.classList.toggle('on',x===b&&cur!==k));
420
+ if(cur===k){cur=null;box.innerHTML='';return;} cur=k;
421
+ const i=d.evidence.find(e=>e.key===k), r=RES[i.result]||RES.info;
422
+ const mp=i.map&&d.maps.find(m=>m.key===i.map);
423
+ let h=`<div class="evd"><div style="display:flex;align-items:center;gap:8px;margin-bottom:10px"><i style="width:10px;height:10px;border-radius:50%;background:${r[0]}"></i><b style="font-size:15px">${esc(L(i,'name'))}</b><span class="badge">${T[r[1]]}</span></div>`+
424
+ `<h4>${T.dFound}</h4><p>${esc(L(i,'found'))}</p>`+
425
+ `<h4>${T.dWhy}</h4><p>${esc(L(i,'why'))}</p>`+
426
+ (i.measures&&i.measures.length?`<h4>${T.dMeasure}</h4>`+i.measures.map(m=>`<div class="kv"><span>${esc(LANG==='en'?m[1]:m[0])}</span><span>${esc(m[2])}</span></div>`).join(''):'')+
427
+ `<h4>${T.dAmped}</h4><p>${esc(i.amped)}</p>`+
428
+ `<h4>${T.dRef}</h4><p class="ref">${esc(i.reference)}</p>`+
429
+ `<h4>${T.dLimits}</h4><p>${esc(L(i,'limits'))}</p>`+
430
+ `<h4>${T.dWeight}</h4><p>${i.contribution!=null?T.wText(i.share,i.contribution):T.wNone}</p>`+
431
+ (mp?`<h4>${T.dMap}</h4><img src="${mp.image}" data-z="${mp.image}">`:'')+`</div>`;
432
+ box.innerHTML=h; box.querySelectorAll('img[data-z]').forEach(im=>im.onclick=()=>window.tsZoom&&window.tsZoom(im.dataset.z));
433
+ box.scrollIntoView({block:'nearest',behavior:'smooth'});
434
+ });
435
+ }
436
+ function dctPlot(p){
437
+ const c=$('dctCard'); if(!c) return;
438
+ const first=p.coefficients.findIndex(x=>x.q1); let idx=first<0?0:first;
439
+ c.innerHTML=`<h2>${T.dctTitle}</h2><div class="mut" style="margin-bottom:10px">${T.dctSub}</div>`+
440
+ `<div class="row"><label>${T.dctCoef} <select id="dctSel">`+p.coefficients.map((x,k)=>`<option value="${k}">${x.index} (${x.uv[0]},${x.uv[1]})${x.q1?' ●':''}</option>`).join('')+`</select></label>`+
441
+ `<span class="badge">${p.double?T.dctAll(p.votes):T.dctNone}</span>${p.first_quality?`<span class="badge">${T.dctFirst}: ${p.first_quality}</span>`:''}</div><div id="dctSvg" style="margin-top:10px"></div>`;
442
+ const draw=()=>{
443
+ const x=p.coefficients[idx], H=x.hist, W=640, Hh=220, PL=10, PB=24, n=H.length, bw=(W-2*PL)/n, mx=Math.max(...H.filter((v,k)=>k!==40&&k>0&&k<H.length-1))||1;
444
+ const pop=new Set((x.populated||[]));
445
+ let svg=`<svg viewBox="0 0 ${W} ${Hh}" style="width:100%;direction:ltr">`;
446
+ H.forEach((v,k)=>{if(k===0||k===H.length-1) return; const val=k-40, hh=Math.min(1,v/mx)*(Hh-PB-10), clip=v>mx, fb=x.q1&&!pop.has(Math.abs(val))&&val!==0;
447
+ svg+=`<rect x="${PL+k*bw}" y="${Hh-PB-hh}" width="${Math.max(1,bw-1)}" height="${hh}" fill="${fb?'#ef4444':'#60a5fa'}"/>`;
448
+ if(fb&&hh<3) svg+=`<rect x="${PL+k*bw}" y="${Hh-PB-3}" width="${Math.max(1,bw-1)}" height="3" fill="#ef4444"/>`;
449
+ if(val%10===0) svg+=`<text x="${PL+k*bw+bw/2}" y="${Hh-6}" fill="var(--mut)" font-size="11" text-anchor="middle">${val}</text>`;});
450
+ svg+=`</svg>`;
451
+ $('dctSvg').innerHTML=svg+`<div class="kv"><span>${T.dctQ2}</span><span>${x.q2}</span></div><div class="kv"><span>${T.dctQ1}</span><span>${x.q1||'—'}</span></div>`;
452
+ };
453
+ $('dctSel').value=idx; $('dctSel').onchange=e=>{idx=+e.target.value;draw();}; draw();
454
  }
455
 
456
  // ---------- JPEG ghost plot ----------
 
511
  `<input type="range" id="gRange" min="0" max="${Q.length-1}" value="${qIdx}">`+
512
  `<div class="gwrap" id="gWrap" style="margin-top:8px"><img id="gImg" src="${g.preview}"><canvas id="gCanvas"></canvas><div class="gsel" id="gSel"></div></div>`+
513
  `<div class="row" style="margin-top:10px"><button class="btn sec" id="gRegionBtn">${T.gPick}</button><button class="btn sec" id="gClear" style="display:none">${T.gClear}</button></div>`+
514
+ `<div class="mut" id="gPickHint" style="display:none;margin-top:6px">${T.gPickHint}</div>`+
515
+ `<h3 style="font-size:14px;margin:14px 0 0">${T.gtTitle}</h3><div class="gt" id="gTiles"></div></div>`;
516
  plot(); $('gImg').onload=draw; if($('gImg').complete) draw();
517
+ const tiles=$('gTiles');
518
+ [60,65,70,75,80,85,90,95].forEach(qq=>{const k=Q.indexOf(qq); if(k<0) return;
519
+ const el=document.createElement('div'); el.innerHTML=`<img src="${g.preview}"><canvas></canvas><b>Q ${qq}</b>`; tiles.appendChild(el);
520
+ const cv=el.querySelector('canvas'); cv.width=nw; cv.height=nh; const ctx=cv.getContext('2d'), id=ctx.createImageData(nw,nh);
521
+ for(let i=0;i<N;i++){ if(!tex(i)) continue; const v=D[k*N+i], gh=1-(v-mn[i])/((mx[i]-mn[i])||1);
522
+ const a=gh>0.75?Math.min(1,(gh-0.75)*4):0; id.data[i*4]=239;id.data[i*4+1]=68;id.data[i*4+2]=68;id.data[i*4+3]=Math.round(a*190);}
523
+ ctx.putImageData(id,0,0);
524
+ el.onclick=()=>{qIdx=k;$('gRange').value=k;draw();plot();$('gWrap').scrollIntoView({block:'center',behavior:'smooth'});};
525
+ });
526
  $('gRange').oninput=e=>{qIdx=+e.target.value; draw(); plot();};
527
  let picking=false,start=null;
528
  $('gRegionBtn').onclick=()=>{picking=true;$('gPickHint').style.display='';};
templates/ts-ela.js CHANGED
@@ -32,7 +32,9 @@
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>' +
@@ -149,7 +151,63 @@
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).
 
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>' +
36
+ '<button data-a="grid" style="' + btn + '">' + T('شبكة الجودات 60–100', 'Quality grid 60–100') + '</button></div>' +
37
+ '<div data-grid style="display:none"></div>' +
38
  '<label style="display:block">' + T('جودة إعادة الحفظ', 'Re-save quality') + ': <b data-v="q"></b>' +
39
  '<input data-s="q" type="range" min="60" max="100" step="1" value="90" style="width:100%"></label>' +
40
  '<label style="display:block">' + T('شدة الإبراز', 'Intensity') + ': <b data-v="g"></b>' +
 
151
  if (a === 'close') ov.remove();
152
  else if (a === 'overlay') { overlay = !overlay; paintButtons(); compute(); }
153
  else if (a === 'zoom' && window.tsZoom) window.tsZoom(cv.toDataURL('image/png'));
154
+ else if (a === 'grid') showGrid();
155
  });
156
+
157
+ // ELA at every 5th quality side by side: an edited area stays different
158
+ // across qualities, the original goes dark near its last save quality.
159
+ function showGrid() {
160
+ var box = ov.querySelector('[data-grid]');
161
+ if (box.style.display === 'block') { box.style.display = 'none'; return; }
162
+ if (!base) return;
163
+ box.style.display = 'block';
164
+ box.innerHTML = '<div style="font-size:12.5px;opacity:.85;margin-bottom:8px">' +
165
+ T('كل خانة ELA عند جودة مختلفة بالمقياس نفسه. اضغطي على خانة لتكبيرها.', 'Each tile is ELA at a different quality, same scale. Tap a tile to enlarge it.') + '</div>' +
166
+ '<div data-tiles style="display:grid;grid-template-columns:repeat(auto-fill,minmax(150px,1fr));gap:8px"></div>';
167
+ var tiles = box.querySelector('[data-tiles]');
168
+ var s = Math.min(1, 420 / Math.max(W, H)), w = Math.max(1, Math.round(W * s)), h = Math.max(1, Math.round(H * s));
169
+ var c0 = document.createElement('canvas'); c0.width = W; c0.height = H; c0.getContext('2d').putImageData(base, 0, 0);
170
+ var qs = [60, 65, 70, 75, 80, 85, 90, 95, 100], results = [], done = 0;
171
+ qs.forEach(function (qq, idx) {
172
+ var cell = document.createElement('div');
173
+ cell.innerHTML = '<canvas style="width:100%;border-radius:8px;background:#000;display:block;cursor:zoom-in"></canvas>' +
174
+ '<div style="text-align:center;font-size:12px;margin-top:4px;font-weight:700">Q ' + qq + ' · <span data-m></span></div>';
175
+ tiles.appendChild(cell);
176
+ c0.toBlob(function (blob) {
177
+ var url = URL.createObjectURL(blob), im = new Image();
178
+ im.onload = function () {
179
+ var c1 = document.createElement('canvas'); c1.width = W; c1.height = H;
180
+ var x1 = c1.getContext('2d'); x1.drawImage(im, 0, 0);
181
+ var re = x1.getImageData(0, 0, W, H).data, a = base.data, d = new Float32Array(W * H), se = 0;
182
+ for (var i = 0, j = 0; i < a.length; i += 4, j++) {
183
+ var e0 = a[i] - re[i], e1 = a[i + 1] - re[i + 1], e2 = a[i + 2] - re[i + 2];
184
+ d[j] = Math.max(Math.abs(e0), Math.abs(e1), Math.abs(e2)); se += (e0 * e0 + e1 * e1 + e2 * e2) / 3;
185
+ }
186
+ URL.revokeObjectURL(url);
187
+ results[idx] = { d: d, mse: se / (W * H), cell: cell };
188
+ if (++done === qs.length) paint();
189
+ };
190
+ im.src = url;
191
+ }, 'image/jpeg', qq / 100);
192
+ });
193
+ function paint() {
194
+ var mx = 1; // common scale: 99.5th percentile over all tiles
195
+ var hist = new Uint32Array(256), n = 0;
196
+ results.forEach(function (r) { for (var i = 0; i < r.d.length; i += 7) { hist[Math.min(255, r.d[i] | 0)]++; n++; } });
197
+ for (var t = 0, acc = 0; t < 256; t++) { acc += hist[t]; if (acc >= n * 0.995) { mx = Math.max(1, t); break; } }
198
+ results.forEach(function (r) {
199
+ var cv2 = r.cell.querySelector('canvas'); cv2.width = w; cv2.height = h;
200
+ var ctx = cv2.getContext('2d'), out = ctx.createImageData(w, h), o = out.data;
201
+ for (var y = 0; y < h; y++) for (var x = 0; x < w; x++) {
202
+ var v = Math.min(255, r.d[Math.min(H - 1, Math.floor(y / s)) * W + Math.min(W - 1, Math.floor(x / s))] * 255 / mx), k = (y * w + x) * 4;
203
+ o[k] = o[k + 1] = o[k + 2] = v; o[k + 3] = 255;
204
+ }
205
+ ctx.putImageData(out, 0, 0);
206
+ r.cell.querySelector('[data-m]').textContent = 'MSE ' + r.mse.toFixed(1);
207
+ cv2.onclick = function () { if (window.tsZoom) window.tsZoom(cv2.toDataURL('image/png')); };
208
+ });
209
+ }
210
+ }
211
  };
212
 
213
  // Current frame of a <video> as an image URL (for ELA on video).