-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.py
More file actions
2237 lines (1853 loc) · 101 KB
/
app.py
File metadata and controls
2237 lines (1853 loc) · 101 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import streamlit as st
import os
import gc
from PIL import Image
import analysis # lazy sub-module imports via __getattr__
# ── Memory-management helpers ─────────────────────────────────────
MAX_DIMENSION = 2048 # max width/height for analysis (keeps RAM in check)
def _downscale_if_needed(file_path):
"""
If the image exceeds MAX_DIMENSION on either axis, downscale it
and save a temp copy. Returns the (possibly new) path to use for analysis.
This prevents a single large upload from blowing up memory across all tabs.
"""
try:
img = Image.open(file_path)
w, h = img.size
if w <= MAX_DIMENSION and h <= MAX_DIMENSION:
img.close()
return file_path # no downscale needed
# Calculate new size preserving aspect ratio
scale = min(MAX_DIMENSION / w, MAX_DIMENSION / h)
new_size = (int(w * scale), int(h * scale))
img = img.resize(new_size, Image.LANCZOS)
downscaled_path = os.path.join(
"temp", "_analysis_" + os.path.basename(file_path))
os.makedirs("temp", exist_ok=True)
img.save(downscaled_path, quality=95)
img.close()
return downscaled_path
except Exception:
return file_path # fallback to original on any error
def _cleanup():
"""Prompt Python's garbage collector after heavy work."""
gc.collect()
# 1. Page Configuration
st.set_page_config(
page_title="Veritas - Digital Forensics",
page_icon="🔍",
layout="wide"
)
# 2. Helper: Save Uploaded File to Disk (Required for some OpenCV algos)
def save_uploaded_file(uploaded_file):
if not os.path.exists("temp"):
os.makedirs("temp")
file_path = os.path.join("temp", uploaded_file.name)
with open(file_path, "wb") as f:
f.write(uploaded_file.getbuffer())
return file_path
# 3. Helper: Load Technique Description
def load_description(technique_name):
"""
Load markdown description for a forensic technique.
Args:
technique_name: Name of technique (e.g., 'ELA', 'Metadata', 'FFT')
Returns:
String containing markdown content, or error message if not found
"""
description_file = os.path.join("Descriptions", f"{technique_name}.md")
if os.path.exists(description_file):
try:
with open(description_file, 'r', encoding='utf-8') as f:
return f.read()
except Exception as e:
return f"Error loading description: {str(e)}"
else:
return f"Description file not found: {description_file}"
# 4. Technique Description Mapping
TECHNIQUES = {
"🕵️ ELA": "ELA",
"📋 Metadata": "Metadata",
"📊 Histogram": "Histogram",
"👻 Noise/Ghost": "Noise_Ghost",
"💾 Quantization": "Quantization",
"🔄 CMFD": "CMFD",
"📡 PRNU": "PRNU",
"📈 Frequency": "Frequency",
"😁 Deepfake": "Deepfake",
"🔀 Resampling": "Resampling",
"🔐 Steganography": "Steganography",
"🔑 Hash Verify": "Hash_Verification",
}
# 5. Default Sample Image Path
DEFAULT_SAMPLE_IMAGE = os.path.join(
"assets", "sample images", "sampleImg.jpeg")
# 6. Sidebar - File Upload Section
st.sidebar.markdown("#### 🔍 Veritas Tool")
uploaded_file = st.sidebar.file_uploader(
"Upload an image to analyze", type=["jpg", "jpeg", "png"])
# Show info about default sample
if uploaded_file is None and os.path.exists(DEFAULT_SAMPLE_IMAGE):
st.sidebar.caption("📸 No upload? Using default sample image.")
# 7. Sidebar - Technique Descriptions Section
with st.sidebar.expander("📚 Technique Descriptions", expanded=False):
st.caption("Learn about each forensic analysis method")
desc_cols = st.columns(2)
selected_description = None
for idx, (display_name, technique_key) in enumerate(TECHNIQUES.items()):
col = desc_cols[idx % 2]
if col.button(display_name, key=f"desc_{technique_key}", use_container_width=True):
selected_description = technique_key
st.session_state.selected_description = technique_key
# Check session state for selected description
if "selected_description" in st.session_state:
selected_description = st.session_state.selected_description
# Display Technique Description if selected
if selected_description is not None:
st.markdown("---")
st.markdown(f"## 📖 {selected_description} Description")
description_content = load_description(selected_description)
st.markdown(description_content)
st.markdown("---")
# 8. Main Logic - Determine which image to use
if uploaded_file is not None:
# User uploaded a file
file_path = save_uploaded_file(uploaded_file)
image_name = uploaded_file.name
is_sample = False
elif os.path.exists(DEFAULT_SAMPLE_IMAGE):
# Use default sample image
file_path = DEFAULT_SAMPLE_IMAGE
image_name = "Sample Image (Default)"
is_sample = True
else:
# No image available
file_path = None
image_name = None
is_sample = False
# Process the image if available
if file_path is not None:
# Downscale large images to cap memory usage across all analysis modules
analysis_path = _downscale_if_needed(file_path)
# Display Original
col1, col2 = st.columns([1, 2])
with col1:
st.image(file_path, caption="Original Image", width="stretch")
with col2:
if is_sample:
st.info(f"📸 Analyzing: {image_name}")
st.caption(
"This is a sample image loaded by default. Upload your own image in the sidebar to analyze it.")
else:
st.warning(f"Analyzing: {image_name}")
# 5. Analysis Tabs
tab1, tab2, tab3, tab4, tab5, tab6, tab7, tab8, tab9, tab10, tab11, tab12, tab13, tab14 = st.tabs(
["🕵️ ELA", "📋 Metadata", "📊 Histogram", "👻 Noise/Ghost", "💾 Quant Table",
"🔄 CMFD", "📡 PRNU", "📈 Frequency", "😁 Deepfake", "🔀 Resampling",
"🔐 Steganography", "🔑 Hash Verify", "ℹ️ Info", "🔬 Advanced"])
# --- TAB 1: ELA ---
with tab1:
st.subheader("Advanced Error Level Analysis (ELA)")
st.write(
"The enhanced ELA module performs multi-quality ELA, block analysis, noise profiling, "
"SSIM comparison, entropy, and more."
)
# ---------- User Inputs ----------
quality = st.slider(
label="ELA JPEG Quality",
min_value=50,
max_value=95,
value=90,
step=1,
help="Select the JPEG recompression quality used for ELA processing (lower = stronger artifacts)."
)
error_scale = st.slider(
label="ELA Error Scale",
min_value=1,
max_value=100,
value=20,
step=1,
help="Amplify subtle compression differences to make edits more visible."
)
overlay_opacity = st.slider(
label="ELA Overlay Opacity",
min_value=0.0,
max_value=1.0,
value=0.8,
step=0.05,
help="Blend the ELA map on the original image for better visualization."
)
st.write(
f"Selected JPEG quality: **{quality}**, Error Scale: **{error_scale}**, Overlay Opacity: **{overlay_opacity}**")
# ---------- Run ELA ----------
if st.button("Run Full ELA Analysis"):
with st.spinner("Running Enhanced ELA Pipeline..."):
try:
report = analysis.ela.forensic_analysis(
analysis_path,
qualities=[quality],
error_scale=error_scale,
overlay_opacity=overlay_opacity
)
# 1. Main ELA (Grayscale + Overlay)
st.subheader("📷 ELA Result")
col_ela1, col_ela2 = st.columns(2)
with col_ela1:
st.image(
report["ela_90"], caption=f"ELA Grayscale (Quality {quality})", width="stretch")
with col_ela2:
st.image(
report["ela_90_overlay"], caption=f"ELA Overlay (Quality {quality})", width="stretch")
st.json(report["ela_90_metrics"])
st.markdown("---")
st.subheader("📊 Block-Based ELA Statistics")
st.json(report["block_stats"])
# 2. Multi-quality ELA (overlays included)
st.markdown("---")
st.subheader("📉 Multi-Quality ELA Results")
for q, res in report["ela_multi_quality"].items():
st.write(f"**Quality {q}**")
col_multi1, col_multi2 = st.columns(2)
with col_multi1:
st.image(res["ela"], caption="ELA Grayscale",
width="stretch")
with col_multi2:
st.image(res["overlay"], caption="ELA Overlay",
width="stretch")
st.json(res["metrics"])
# 3. Supporting Maps
st.markdown("---")
st.subheader("🧭 Supporting Forensic Maps")
col_a, col_b, col_c = st.columns(3)
with col_a:
st.image(report["noise_map"],
caption="Noise Map", width="stretch")
with col_b:
st.image(
report["sharpness_map"], caption="Sharpness Map", width="stretch")
with col_c:
st.image(
report["entropy_map"], caption="Entropy Map", width="stretch")
# 4. SSIM
st.markdown("---")
st.subheader("📝 SSIM Map")
st.image(
report["ssim_img"], caption=f"SSIM Map (Score: {report['ssim_score']:.4f})", width="stretch")
# 5. Threshold Mask
st.markdown("---")
st.subheader("🎯 Threshold Mask")
st.image(report["threshold_mask"],
caption="High Error Regions", width="stretch")
except Exception as e:
st.error(f"ELA Processing Error: {e}")
finally:
_cleanup()
# --- TAB 2: METADATA ---
with tab2:
st.subheader("🔍 Advanced Metadata Forensics")
st.write(
"Deep analysis of EXIF data, GPS coordinates, timestamps, software signatures, "
"and file structure integrity. Detects metadata anomalies and tampering indicators."
)
if st.button("🚀 Extract & Analyze Metadata", type="primary"):
with st.spinner("Analyzing metadata and file structure..."):
try:
# Run full analysis
report = analysis.metadata_analysis.full_metadata_analysis(
file_path)
# ========== SUMMARY CARD ==========
st.markdown("---")
st.subheader("📊 Analysis Summary")
col1, col2, col3, col4 = st.columns(4)
with col1:
score = report["summary"]["authenticity_score"]
if score >= 80:
color = "🟢"
elif score >= 50:
color = "🟡"
else:
color = "🔴"
st.metric("Authenticity Score", f"{score}/100")
st.markdown(
f"### {color} **{report['summary']['verdict']}**")
with col2:
st.metric("Total Warnings",
report["summary"]["total_warnings"])
st.metric("File Type", report["summary"]["file_type"])
with col3:
st.metric(
"Has EXIF", "✅ Yes" if report["summary"]["has_exif"] else "❌ No")
st.metric(
"Has GPS", "✅ Yes" if report["summary"]["has_gps"] else "❌ No")
with col4:
st.metric(
"Edited", "⚠️ Yes" if report["summary"]["edited"] else "✅ No")
file_size = report["metadata"]["basic_info"]["file_size_mb"]
st.metric("File Size", f"{file_size} MB")
# ========== ANOMALIES ==========
st.markdown("---")
st.subheader("⚠️ Anomaly Detection")
anomalies = report["anomalies"]
if anomalies["critical"]:
st.error("**🔴 Critical Issues**")
for issue in anomalies["critical"]:
st.markdown(f"- {issue}")
if anomalies["warning"]:
st.warning("**🟡 Warnings**")
for warning in anomalies["warning"]:
st.markdown(f"- {warning}")
if anomalies["info"]:
st.info("**ℹ️ Informational**")
for info in anomalies["info"]:
st.markdown(f"- {info}")
if not (anomalies["critical"] or anomalies["warning"] or anomalies["info"]):
st.success("✅ No significant anomalies detected")
# ========== BASIC INFO ==========
st.markdown("---")
st.subheader("📄 Basic File Information")
col_left, col_right = st.columns(2)
with col_left:
basic = report["metadata"]["basic_info"]
st.json({
"Filename": basic["filename"],
"Format": basic["format"],
"Dimensions": f"{basic['width']}x{basic['height']}",
"Megapixels": basic["megapixels"],
"Color Mode": basic["mode"],
"File Size (MB)": basic["file_size_mb"],
"File Size (Bytes)": basic["file_size_bytes"]
})
with col_right:
st.json({
"File Created": basic["file_created"],
"File Modified": basic["file_modified"],
"File Accessed": basic["file_accessed"]
})
# ========== CAMERA INFO ==========
if report["metadata"]["camera"]:
st.markdown("---")
st.subheader("📷 Camera Information")
st.json(report["metadata"]["camera"])
# ========== SOFTWARE INFO ==========
if report["metadata"]["software"]:
st.markdown("---")
st.subheader("💻 Software & Processing")
st.json(report["metadata"]["software"])
# Highlight if editing software detected
software_str = str(
report["metadata"]["software"]).lower()
editing_apps = [
"photoshop", "gimp", "lightroom", "paint.net", "affinity", "pixlr"]
if any(editor in software_str for editor in editing_apps):
st.warning(
"⚠️ Image editing software detected in metadata")
# ========== TIMESTAMPS ==========
if report["metadata"]["timestamps"]:
st.markdown("---")
st.subheader("🕐 Timestamp Information")
st.json(report["metadata"]["timestamps"])
# ========== GPS DATA ==========
if report["metadata"]["gps"]:
st.markdown("---")
st.subheader("🌍 GPS Location Data")
if "coordinates" in report["metadata"]["gps"]:
coords = report["metadata"]["gps"]["coordinates"]
col_gps1, col_gps2 = st.columns(2)
with col_gps1:
st.metric("Latitude", coords["latitude"])
st.metric("Longitude", coords["longitude"])
with col_gps2:
st.markdown(
f"**[📍 View on Google Maps]({coords['google_maps']})**")
st.info("Click the link above to view location")
# Show map if coordinates are valid
if coords["latitude"] != 0 and coords["longitude"] != 0:
try:
import pandas as pd
map_data = pd.DataFrame({
'lat': [coords["latitude"]],
'lon': [coords["longitude"]]
})
st.map(map_data)
except Exception as map_error:
st.warning(
f"Could not display map: {map_error}")
# Show raw GPS data
with st.expander("📋 View Raw GPS Tags"):
gps_display = {
k: v for k, v in report["metadata"]["gps"].items() if k != "coordinates"}
if gps_display:
st.json(gps_display)
else:
st.info("Only coordinate data available")
# ========== EXIF DATA ==========
if report["metadata"]["exif"]:
st.markdown("---")
st.subheader("🔬 EXIF Data")
with st.expander("📋 View All EXIF Tags", expanded=False):
st.json(report["metadata"]["exif"])
else:
st.markdown("---")
st.warning("⚠️ No EXIF data found in image")
# ========== THUMBNAIL ==========
if report["metadata"]["thumbnail"].get("present"):
st.markdown("---")
st.subheader("🖼️ Embedded Thumbnail")
with st.expander("📋 View Thumbnail Metadata"):
st.json(report["metadata"]["thumbnail"])
# ========== FILE STRUCTURE ==========
st.markdown("---")
st.subheader("🔧 File Structure Analysis")
structure = report["file_structure"]
col_struct1, col_struct2 = st.columns(2)
with col_struct1:
st.markdown("**File Signature**")
st.json(structure["signature"])
with col_struct2:
st.markdown("**Integrity Hashes**")
st.code(
f"MD5: {structure['integrity']['md5']}", language=None)
st.code(
f"SHA256: {structure['integrity']['sha256']}", language=None)
# JPEG Structure
if structure["jpeg_structure"]:
st.markdown("---")
st.markdown("**JPEG Structure Analysis**")
jpeg_info = structure["jpeg_structure"]
col_jpeg1, col_jpeg2 = st.columns(2)
with col_jpeg1:
st.metric("Total Segments",
jpeg_info["total_segments"])
st.metric("Has Thumbnail",
"✅ Yes" if jpeg_info["has_embedded_thumbnail"] else "❌ No")
with col_jpeg2:
double_comp = jpeg_info["double_compressed_indicator"]
if double_comp:
st.warning(
"⚠️ Multiple Quantization Tables Detected")
st.markdown(
"*May indicate recompression/editing*")
else:
st.success("✅ Single Compression Detected")
with st.expander("📋 View JPEG Segment Sequence"):
st.code(
", ".join(jpeg_info["segment_sequence"]), language=None)
# File structure warnings
if structure["warnings"]:
st.markdown("---")
st.warning("**⚠️ File Structure Warnings**")
for warning in structure["warnings"]:
st.markdown(f"- {warning}")
# ========== EXPORT OPTIONS ==========
st.markdown("---")
st.subheader("💾 Export Report")
col_export1, col_export2 = st.columns(2)
with col_export1:
# Convert report to JSON string
import json
json_str = json.dumps(report, indent=2, default=str)
st.download_button(
label="📥 Download JSON Report",
data=json_str,
file_name=f"metadata_report_{report['metadata']['basic_info']['filename']}.json",
mime="application/json",
help="Download complete metadata analysis as JSON file"
)
with col_export2:
# Create summary text
summary_text = f"""Metadata Analysis Report
========================
File: {report['metadata']['basic_info']['filename']}
Authenticity Score: {report['summary']['authenticity_score']}/100
Verdict: {report['summary']['verdict']}
Total Warnings: {report['summary']['total_warnings']}
Anomalies:
- Critical Issues: {len(anomalies['critical'])}
- Warnings: {len(anomalies['warning'])}
- Informational: {len(anomalies['info'])}
File Info:
- Format: {report['summary']['file_type']}
- Size: {report['metadata']['basic_info']['file_size_mb']} MB
- Dimensions: {report['metadata']['basic_info']['width']}x{report['metadata']['basic_info']['height']}
- Has EXIF: {'Yes' if report['summary']['has_exif'] else 'No'}
- Has GPS: {'Yes' if report['summary']['has_gps'] else 'No'}
- Edited: {'Yes' if report['summary']['edited'] else 'No'}
"""
st.download_button(
label="📋 Download Summary Text",
data=summary_text,
file_name=f"metadata_summary_{report['metadata']['basic_info']['filename']}.txt",
mime="text/plain",
help="Download quick summary as text file"
)
except Exception as e:
st.error(f"❌ Metadata Analysis Error: {str(e)}")
with st.expander("🐛 View Error Details"):
st.exception(e)
# --- TAB 3: HISTOGRAM ---
with tab3:
st.subheader("📊 Advanced Histogram Analysis")
st.write(
"RGB histogram analysis with statistical forensics to detect manipulation indicators "
"such as artificial gaps (comb patterns), clipping, and unusual distributions."
)
if st.button("🚀 Generate Histogram Analysis", type="primary"):
with st.spinner("Analyzing color distribution patterns..."):
try:
result = analysis.histogram_analysis.generate_histogram(
analysis_path)
if result['status'] == 'success':
# Display histogram image
st.markdown("---")
st.subheader("📈 RGB Histogram")
st.image(
result['histogram_path'], caption="Histogram Analysis", width='stretch')
# Statistics summary cards
st.markdown("---")
st.subheader("📊 Statistical Summary")
col1, col2, col3 = st.columns(3)
with col1:
st.markdown("**🔴 Red Channel**")
red_stats = result['statistics']['red']
st.metric("Mean", f"{red_stats['mean']:.2f}")
st.metric("Std Dev", f"{red_stats['std']:.2f}")
st.metric(
"Range", f"{red_stats['min']:.0f} - {red_stats['max']:.0f}")
st.metric("Median", f"{red_stats['median']:.2f}")
with col2:
st.markdown("**🟢 Green Channel**")
green_stats = result['statistics']['green']
st.metric("Mean", f"{green_stats['mean']:.2f}")
st.metric("Std Dev", f"{green_stats['std']:.2f}")
st.metric(
"Range", f"{green_stats['min']:.0f} - {green_stats['max']:.0f}")
st.metric("Median", f"{green_stats['median']:.2f}")
with col3:
st.markdown("**🔵 Blue Channel**")
blue_stats = result['statistics']['blue']
st.metric("Mean", f"{blue_stats['mean']:.2f}")
st.metric("Std Dev", f"{blue_stats['std']:.2f}")
st.metric(
"Range", f"{blue_stats['min']:.0f} - {blue_stats['max']:.0f}")
st.metric("Median", f"{blue_stats['median']:.2f}")
# Warnings section
if result['warnings']:
st.markdown("---")
st.subheader("⚠️ Detected Anomalies")
for warning in result['warnings']:
st.warning(f"⚠️ {warning}")
else:
st.markdown("---")
st.success("✅ No histogram anomalies detected")
# Interpretation
st.markdown("---")
st.subheader("💡 Interpretation")
st.info(result['interpretation'])
# Raw data expander
with st.expander("📋 View Raw Statistics"):
st.json(result['statistics'])
else:
st.error(
f"❌ Analysis Error: {result.get('error', 'Unknown error')}")
except Exception as e:
st.error(f"❌ Histogram Analysis Error: {str(e)}")
with st.expander("🐛 View Error Details"):
st.exception(e)
# --- TAB 4: NOISE & GHOST ---
with tab4:
st.subheader("👻 Noise Analysis & JPEG Ghost Detection")
st.write(
"Detect tampering through noise inconsistencies and compression artifacts. "
"Authentic images have uniform noise patterns; manipulated regions show noise discrepancies."
)
# Noise Map Section
st.markdown("---")
st.markdown("### 🔬 Noise Map Analysis")
st.write(
"Extract and analyze high-frequency noise patterns to detect inconsistencies")
if st.button("🚀 Generate Noise Map", type="primary", key="noise_btn"):
with st.spinner("Extracting noise patterns..."):
try:
result = analysis.noise_map.generate_noise_map(
analysis_path)
if result['status'] == 'success':
# Display noise map
st.image(
result['noise_map_path'], caption="Noise Map (High-Frequency Components)", width='stretch')
# Metrics display
st.markdown("---")
st.subheader("📊 Noise Metrics")
col1, col2 = st.columns(2)
with col1:
st.markdown("**Channel Variance**")
variance = result['metrics']['channel_noise_variance']
st.metric("Red Channel", f"{variance['red']:.2f}")
st.metric("Green Channel",
f"{variance['green']:.2f}")
st.metric("Blue Channel",
f"{variance['blue']:.2f}")
with col2:
st.markdown("**Consistency Analysis**")
st.metric(
"Overall Variance", f"{result['metrics']['overall_variance']:.2f}")
st.metric(
"Block Variance Std", f"{result['metrics']['block_variance_std']:.2f}")
st.metric("Blocks Analyzed",
result['metrics']['blocks_analyzed'])
# Warnings
if result['warnings']:
st.markdown("---")
st.subheader("⚠️ Detected Issues")
for warning in result['warnings']:
st.warning(f"⚠️ {warning}")
else:
st.success("✅ Noise pattern appears consistent")
# Interpretation
st.markdown("---")
st.info(f"💡 {result['interpretation']}")
else:
st.error(
f"❌ Error: {result.get('error', 'Unknown error')}")
except Exception as e:
st.error(f"❌ Noise Analysis Error: {str(e)}")
# JPEG Ghost Section
st.markdown("---")
st.markdown("---")
st.markdown("### 👻 JPEG Ghost Detection")
st.write(
"Multi-quality compression analysis to estimate last save quality and detect re-editing")
if st.button("🚀 Detect JPEG Ghost", type="primary", key="ghost_btn"):
with st.spinner("Analyzing compression history..."):
try:
result = analysis.jpeg_ghost.detect_jpeg_ghost(file_path)
if result['status'] == 'success':
# Display combined ghost visualization
if result['combined_ghost_path']:
st.image(
result['combined_ghost_path'], caption="JPEG Ghost Analysis (Multiple Quality Levels)", width='stretch')
# Quality estimation results
st.markdown("---")
st.subheader("📊 Quality Estimation")
col1, col2, col3 = st.columns(3)
with col1:
st.metric("Estimated Last Save Quality",
f"{result['estimated_last_save_quality']}")
with col2:
confidence = result['quality_confidence']
color = "🟢" if confidence == 'high' else "🟡"
st.metric("Confidence",
f"{color} {confidence.upper()}")
with col3:
min_score = min(
result['difference_scores'].values())
st.metric("Min Difference Score",
f"{min_score:.2f}")
# Difference scores by quality
st.markdown("---")
st.subheader("📈 Difference Scores by Quality")
st.write(
"Lower scores indicate quality closer to original compression")
import pandas as pd
df_scores = pd.DataFrame([
{"Quality Level": q, "Difference Score": score}
for q, score in sorted(result['difference_scores'].items())
])
st.dataframe(df_scores, width='stretch')
# Warnings
if result['warnings']:
st.markdown("---")
st.subheader("⚠️ Detected Issues")
for warning in result['warnings']:
st.warning(f"⚠️ {warning}")
else:
st.success("✅ No compression anomalies detected")
# Interpretation
st.markdown("---")
st.info(f"💡 {result['interpretation']}")
else:
st.error(
f"❌ Error: {result.get('error', 'Unknown error')}")
except Exception as e:
st.error(f"❌ JPEG Ghost Error: {str(e)}")
# --- TAB 5: QUANTIZATION TABLE ---
with tab5:
st.subheader("💾 JPEG Quantization Table Analysis")
st.write(
"Analyze JPEG quantization tables to identify compression software, "
"estimate quality settings, and detect non-standard table modifications."
)
if st.button("🚀 Analyze Quantization Tables", type="primary"):
with st.spinner("Extracting and analyzing Q-tables..."):
try:
result = analysis.quant_table.analyze_quantization_table(
file_path)
if result['status'] == 'success':
# Quality estimation
st.markdown("---")
st.subheader("📊 Quality Assessment")
col1, col2, col3 = st.columns(3)
with col1:
quality = result.get(
'estimated_quality', 'Unknown')
st.metric("Estimated Quality", quality)
with col2:
tables_count = result.get('tables_found', 0)
st.metric("Tables Found", tables_count)
with col3:
is_standard = result.get(
'uses_standard_tables', 'Unknown')
indicator = "✅" if is_standard else "⚠️"
st.metric("Standard Tables",
f"{indicator} {is_standard}")
# Table details
if 'tables' in result:
st.markdown("---")
st.subheader("🔍 Quantization Table Details")
for table_id, table_data in result['tables'].items():
with st.expander(f"📋 Table {table_id}"):
# Display as 8x8 matrix
import numpy as np
table_array = np.array(
table_data).reshape(8, 8)
# Format as DataFrame for better display
import pandas as pd
df_table = pd.DataFrame(table_array)
st.dataframe(
df_table, width='stretch')
st.caption(
"Lower values = higher quality | Higher values = more compression")
# Warnings
if result.get('warnings'):
st.markdown("---")
st.subheader("⚠️ Detected Issues")
for warning in result['warnings']:
st.warning(f"⚠️ {warning}")
else:
st.success("✅ No Q-table anomalies detected")
# Interpretation
if result.get('interpretation'):
st.markdown("---")
st.info(f"💡 {result['interpretation']}")
# Raw data
with st.expander("📋 View Raw Analysis Data"):
st.json(result)
else:
st.error(
f"❌ Analysis Error: {result.get('error', 'Unknown error')}")
except Exception as e:
st.error(f"❌ Q-Table Analysis Error: {str(e)}")
with st.expander("🐛 View Error Details"):
st.exception(e)
# --- TAB 6: CMFD ---
with tab6:
st.subheader("🔄 Copy-Move Forgery Detection (CMFD)")
st.write(
"Detect duplicated regions within the image using DCT-based block matching. "
"This technique identifies areas that have been copied and pasted to conceal or clone content."
)
# Parameter controls
with st.expander("⚙️ Advanced Parameters"):
col_p1, col_p2 = st.columns(2)
with col_p1:
block_size = st.slider(
"Block Size", 8, 32, 16, 4, help="Size of blocks for matching (larger = faster but less precise)")
with col_p2:
threshold = st.slider(
"Similarity Threshold", 0.5, 0.99, 0.9, 0.05, help="Higher = stricter matching")
if st.button("🚀 Run CMFD Analysis", type="primary"):
with st.spinner("Analyzing for copy-move forgery... This may take a minute..."):
try:
result = analysis.cmfd.detect_copy_move(
analysis_path, block_size=block_size, threshold=threshold)
if result['status'] == 'success':
# Display result image
st.markdown("---")
st.subheader("🖼️ Detection Result")
st.image(result['results']['result_image_path'],
caption="Copy-Move Detection (Green/Red: Matched regions | Lines: Connections)",
width='stretch')
# Analysis metrics
st.markdown("---")
st.subheader("📊 Analysis Metrics")
col1, col2, col3 = st.columns(3)
with col1:
st.metric(
"Blocks Analyzed", f"{result['results']['total_blocks_analyzed']:,}")
with col2:
matches = result['results']['matches_found']
color = "🔴" if matches > 20 else (
"🟡" if matches > 5 else "🟢")
st.metric("Matches Found", f"{color} {matches}")
with col3:
st.metric("Match Groups",
result['results']['match_groups'])
# Parameters used
st.markdown("---")
st.subheader("⚙️ Parameters Used")
col_param1, col_param2, col_param3 = st.columns(3)
with col_param1:
st.metric(
"Block Size", f"{result['parameters']['block_size']}x{result['parameters']['block_size']}")
with col_param2:
st.metric(
"Threshold", result['parameters']['threshold'])
with col_param3:
st.metric("Min Distance",
result['parameters']['min_distance'])
# Match details
if result.get('matches') and len(result['matches']) > 0:
st.markdown("---")
st.subheader("🔍 Top Matches")
import pandas as pd
match_data = []
for i, match in enumerate(result['matches'][:10], 1):
match_data.append({
"#": i,
"Block 1": f"({match['block1'][0]}, {match['block1'][1]})",
"Block 2": f"({match['block2'][0]}, {match['block2'][1]})",
"Similarity": f"{match['similarity']:.4f}"
})
df_matches = pd.DataFrame(match_data)
st.dataframe(df_matches, width='stretch')
# Warnings
if result.get('warnings'):
st.markdown("---")
st.subheader("⚠️ Detected Issues")
for warning in result['warnings']:
st.warning(f"⚠️ {warning}")
else:
st.success("✅ No copy-move forgery detected")
# Interpretation
st.markdown("---")
st.info(f"💡 {result['interpretation']}")
# Raw data
with st.expander("📋 View Raw Analysis Data"):
st.json(result)
else:
st.error(
f"❌ Analysis Error: {result.get('error', 'Unknown error')}")
except Exception as e:
st.error(f"❌ CMFD Error: {str(e)}")
with st.expander("🐛 View Error Details"):
st.exception(e)
finally:
_cleanup()