Commit ·
55ae7dd
0
Parent(s):
Clean deployment: model loaded from HF Hub at runtime
Browse filesCo-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Files changed (13)
- .gitattributesAdded+3
- .gitignoreAdded+43
- CLAUDE.mdAdded+55
- README.mdAdded+33
- app.pyAdded+188
- documents/Project_Report_Digital_Image_Forgery_Detector.docxAdded+3
- documents/REMEDIATION_PLAN.mdAdded+450
- documents/remediation_plan.htmlAdded+1084
- notebooks/Image_Forgery_Detection_Colab_1.ipynbAdded+3
- notebooks/Image_Forgery_Training_Notebook.ipynbAdded+3
- packages.txtAdded+8
- requirements.txtAdded+8
- train.pyAdded+172
123*.keras filter=lfs diff=lfs merge=lfs -text*.ipynb filter=lfs diff=lfs merge=lfs -text*.docx filter=lfs diff=lfs merge=lfs -text12345678910111213141516171819202122232425262728293031323334353637383940414243# --- Local IDE / Claude Code ---.claude/.vscode/.idea/
# --- HTML build artefact (rebuilt by pandoc; not source) ---Documents/header_inline.html
# --- Future: data files (see PROJECT_SCOPE.md §5.2 + §6) ---data/raw/data/processed/
# --- Future: training outputs (weights live on HuggingFace Hub) ---checkpoints/logs/
# --- Python ---__pycache__/*.py[cod]*$py.class*.so.Python.venv/venv/env/*.egg-info/.pytest_cache/.ruff_cache/
# --- Jupyter ---.ipynb_checkpoints/
# --- OS ---.DS_StoreThumbs.db
# --- Secrets / credentials ---.env.env.local*.pemkaggle.jsonmodel/*.h5model/*.keras12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Commands
**Install dependencies:**```bashpip install -r requirements.txt```
**Run the Streamlit app locally:**```bashstreamlit run app.py```
**Train the model (generates synthetic data and saves `model/M3_best.keras`):**```bashpython train.py```
The trained model file `model/M3_best.keras` is tracked via Git LFS (~98 MB).
## Architecture
This is a two-file ML project: a training script and a Streamlit inference app.
### Model: Dual-Branch CNN (`train.py`)
The model takes two inputs for every image:
- **RGB branch** — frozen ResNet50 (pretrained on ImageNet) → `GlobalAveragePooling2D`. Captures semantic/texture features.- **ELA branch** — custom 3-block CNN (Conv2D → BatchNorm → MaxPool, filters: 32→64→128) → `GlobalAveragePooling2D`. Operates on the Error Level Analysis image.
Both branch outputs are concatenated → Dense(256, relu) → Dropout(0.5) → Dense(1, sigmoid). Binary output: 0 = Authentic, 1 = Forged.
**ELA** (Error Level Analysis): re-saves the image as JPEG at `quality=90`, diffs it against the original, then amplifies the difference by `scale=15`. Tampered regions show higher residuals due to compression inconsistency.
**Dataset convention (CASIA v2 naming):**- Authentic files: `Au_<type>_<id>.jpg`- Tampered files: `Tp_s_N_<type>_<donor_id>_<tampered_id>_<seq>.jpg`
`CASIAParser` extracts IDs from filenames to ensure donor/tampered image pairs stay in the same split (prevents data leakage across train/val/test).
### Inference App (`app.py`)
Loads `model/M3_best.keras` (cached via `@st.cache_resource`). For each uploaded image:1. Computes ELA image using identical parameters as training (`quality=90`, `scale=15`).2. Resizes both RGB and ELA to `(224, 224)` and runs `model.predict`.3. Threshold: `pred > 0.5` → FORGED, `pred < 0.5` → AUTHENTIC, `0.45–0.55` → UNCERTAIN.4. Generates a **Grad-CAM** heatmap by dynamically finding the last `conv2d` layer, computing gradients of the output w.r.t. that layer's activations, and overlaying a JET colormap on the original image.
### Deployment
Configured for **Hugging Face Spaces** (Streamlit SDK). The `README.md` frontmatter contains the Space metadata. `packages.txt` installs system-level dependencies needed for OpenCV headless (`libgl1`, `libsm6`, `libxext6`) and Git LFS.123456789101112131415161718192021222324252627282930313233---title: Image Forgery Detectoremoji: 🛡️colorFrom: bluecolorTo: redsdk: streamlitsdk_version: 1.35.0python_version: 3.11app_file: app.pypinned: false---
# Image Forgery Detector
This application detects tampering in images using a Dual-Branch CNN architecture.
## How it works:1. **RGB Branch:** Uses a pretrained ResNet50 to extract semantic features from the original image.2. **ELA Branch:** Computes Error Level Analysis (ELA) to detect JPEG compression inconsistencies.3. **Fused Model:** Combines features from both branches to make a final prediction.
## Explainability:The app uses **Grad-CAM** to visualize which parts of the image the model focused on when making its decision.
## Deployment:🚀 **Live on Hugging Face Spaces:** [image-forgery-detector](https://huggingface.co/spaces/usamaalam/image-forgery-detector)
## Repository:- **GitHub:** [https://github.com/salmanzaman777/image-forgery-detector](https://github.com/salmanzaman777/image-forgery-detector)- **Branch:** `usama` (latest with M3 model trained on CASIA v2)
## Documents:- [Project Report](documents/Project_Report_Digital_Image_Forgery_Detector.docx)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188import streamlit as stimport numpy as npimport tensorflow as tfimport cv2import iofrom PIL import Image, ImageChops, ImageEnhancefrom tensorflow.keras import models
# ── Configuration ────────────────────────────────────────────────────────────IMG_SIZE = (224, 224)ELA_QUALITY = 90ELA_SCALE = 15
# ── Forensic Utilities ───────────────────────────────────────────────────────def compute_ela(original, quality=ELA_QUALITY, scale=ELA_SCALE): original = original.convert('RGB') buf = io.BytesIO() original.save(buf, 'JPEG', quality=quality) buf.seek(0) compressed = Image.open(buf)
ela_image = ImageChops.difference(original, compressed) ela_image = ImageEnhance.Brightness(ela_image).enhance(scale) return ela_image
def get_gradcam(model, input_data): # Dynamically find the last conv layer last_conv_layer_name = None for layer in reversed(model.layers): if 'conv2d' in layer.name: last_conv_layer_name = layer.name break if not last_conv_layer_name: # Fallback to any layer with conv in name for layer in reversed(model.layers): if 'conv' in layer.name: last_conv_layer_name = layer.name break
grad_model = models.Model( inputs=model.inputs, outputs=[model.get_layer(last_conv_layer_name).output, model.output] )
with tf.GradientTape() as tape: last_conv_out, preds = grad_model(input_data) class_channel = preds[:, 0]
grads = tape.gradient(class_channel, last_conv_out) pooled_grads = tf.reduce_mean(grads, axis=(0, 1, 2)) heatmap = last_conv_out[0] @ pooled_grads[..., tf.newaxis]
max_val = tf.math.reduce_max(heatmap) if max_val == 0: max_val = 1e-10 heatmap = tf.squeeze(tf.maximum(heatmap, 0) / max_val).numpy() return heatmap
def build_model(model_type='M3'): IMG_SIZE = (224, 224) ela_input = layers.Input(shape=(*IMG_SIZE, 3), name='ela_input') x = layers.Conv2D(32, (3,3), activation='relu', padding='same')(ela_input) x = layers.BatchNormalization()(x) x = layers.MaxPooling2D()(x) x = layers.Conv2D(64, (3,3), activation='relu', padding='same')(x) x = layers.BatchNormalization()(x) x = layers.MaxPooling2D()(x) x = layers.Conv2D(128, (3,3), activation='relu', padding='same')(x) x = layers.BatchNormalization()(x) x = layers.MaxPooling2D()(x) ela_features = layers.GlobalAveragePooling2D(name='ela_gap')(x)
rgb_input = layers.Input(shape=(*IMG_SIZE, 3), name='rgb_input') resnet = tf.keras.applications.ResNet50(weights='imagenet', include_top=False, input_tensor=rgb_input) for layer in resnet.layers: layer.trainable = False rgb_features = layers.GlobalAveragePooling2D(name='rgb_gap')(resnet.output)
combined = layers.Concatenate(name='fused')([rgb_features, ela_features]) x = layers.Dense(256, activation='relu')(combined) x = layers.Dropout(0.5)(x) output = layers.Dense(1, activation='sigmoid', name='output')(x)
return tf.keras.Model(inputs=[rgb_input, ela_input], outputs=output, name=model_type)
@st.cache_resourcedef load_trained_model(): import os from huggingface_hub import hf_hub_download
model_path = 'M3_best.h5'
# Try local file first if os.path.exists(model_path): try: model = build_model('M3') model.load_weights(model_path) return model except Exception as e: st.warning(f"Local model load failed: {e}. Downloading from HF Hub...")
# Download from HF Model Hub try: st.info("Downloading model from Hugging Face Hub...") model_path = hf_hub_download( repo_id="usamaalam/image-forgery-detection-model", filename="M3_best.h5", cache_dir=".cache" ) model = build_model('M3') model.load_weights(model_path) st.success("Model loaded successfully!") return model except Exception as e: st.error(f"Failed to load model: {e}") return None
# ── Main UI ──────────────────────────────────────────────────────────────────st.set_page_config(page_title="Image Forgery Detector", layout="wide")
st.title("🛡️ Image Forgery Detector")st.markdown("""Detect tampering in images using a Dual-Branch CNN (RGB + ELA).Upload an image to see if it's Authentic or Forged.""")
uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png", "tif"])
if uploaded_file is not None: image = Image.open(uploaded_file).convert('RGB') col1, col2 = st.columns(2) with col1: st.image(image, caption="Original Image", use_column_width=True) with st.spinner("Analyzing..."): # Load model m3 = load_trained_model() # Prepare inputs — normalize to [0, 1] to match training rgb_in = np.array(image.resize(IMG_SIZE)).astype(np.float32)[np.newaxis] / 255.0 ela_img = compute_ela(image) ela_in = np.array(ela_img.resize(IMG_SIZE)).astype(np.float32)[np.newaxis] / 255.0 input_data = [rgb_in, ela_in] # Inference pred = m3.predict(input_data, verbose=0)[0][0] label = "FORGED" if pred > 0.5 else "AUTHENTIC" confidence = pred if pred > 0.5 else 1 - pred if 0.45 <= pred <= 0.55: label = "UNCERTAIN" with col2: st.subheader("Prediction Result") color = "red" if label == "FORGED" else "green" if label == "AUTHENTIC" else "orange" st.markdown(f"### Result: <span style='color:{color}'>{label}</span>", unsafe_allow_html=True) st.write(f"**Confidence:** {confidence:.2%}") st.progress(float(confidence))
st.divider() col3, col4 = st.columns(2) with col3: st.subheader("ELA Artifacts") st.image(ela_img, caption="Error Level Analysis (JPEG inconsistencies)", use_column_width=True) st.info("ELA highlights regions with different compression levels, often indicating tampered areas.") with col4: st.subheader("Grad-CAM Explainability") try: heatmap = get_gradcam(m3, input_data) heatmap_color = cv2.applyColorMap(np.uint8(255 * heatmap), cv2.COLORMAP_JET) heatmap_color = cv2.cvtColor(heatmap_color, cv2.COLOR_BGR2RGB) heatmap_resized = cv2.resize(heatmap_color, (image.size[0], image.size[1])) # Blend img_np = np.array(image) overlay = np.uint8(heatmap_resized * 0.4 + img_np * 0.6) st.image(overlay, caption="Model Focus Regions", use_column_width=True) st.info("The heatmap shows which parts of the image the model focused on to make its decision.") except Exception as e: st.error(f"Could not generate Grad-CAM: {e}")
else: st.info("Please upload an image to start detection.")123version https://git-lfs.github.com/spec/v1oid sha256:7744b5d6ae0dbb487a8093db92798e1b4732788f6a4ac713ee4e0c4bc7fe9a6csize 23701123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450# Remediation & Enhancement Plan## Image Forgery Detector — PGD Student Project
This document lists every gap and issue found during validation, with step-by-step actions to fix each one. Work through the sections **in priority order** (Critical → High → Medium → Low). Do not skip ahead — later fixes depend on earlier ones being done first.
---
## Quick Reference: Issue Summary
| # | Severity | Issue | Files Affected ||---|----------|-------|----------------|| 1 | CRITICAL | `run_training()` never defined in notebook | `.ipynb` || 2 | CRITICAL | Synthetic toy data — model learns nothing real | `.ipynb`, `train.py` || 3 | HIGH | Notebook section order is broken (§9 → §7 → §8) | `.ipynb` || 4 | HIGH | No meaningful evaluation metrics (only accuracy) | `.ipynb` || 5 | HIGH | Ablation study conclusion is invalid (all 100%) | `.ipynb` || 6 | MEDIUM | `train.py` only trains M3, not M1/M2 | `train.py` || 7 | MEDIUM | Project report document missing from repo | `Documents/` || 8 | MEDIUM | No literature comparison or baseline results | `.ipynb` || 9 | LOW | `get_gradcam()` in app.py is simplified vs notebook | `app.py` || 10 | LOW | Gradio vs Streamlit discrepancy not documented | `README.md` |
---
## CRITICAL FIXES
---
### Fix 1 — Add the Missing `run_training()` Function to the Notebook
**Problem:** Cell 16 of the notebook calls `run_training('M1', ...)`, `run_training('M2', ...)`, and `run_training('M3', ...)`, but this function is never defined in any visible cell. The notebook **cannot be run end-to-end** as currently submitted. An examiner who tries to run it will get a `NameError`.
**Why this matters:** A Colab notebook is expected to be fully self-contained. Every function that is called must be defined above the call site.
**Steps to fix:**
1. Open `Image_Forgery_Detection_Colab_1.ipynb` in Google Colab.2. Insert a new code cell **between the `build_model()` cell and the ablation execution cell** (between the current cell-9 and cell-16).3. Add the following function to that cell:
```pythondef run_training(model_type, train_ds_base, val_ds_base, n_train, n_val): print(f"\n{'='*55}") print(f"Training {model_type}") print(f"{'='*55}")
train_ds = adapt_dataset_for_model(train_ds_base, model_type) val_ds = adapt_dataset_for_model(val_ds_base, model_type)
model = build_model(model_type) model.compile( optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'] )
steps_per_epoch = max(1, int(np.ceil(n_train / BATCH_SIZE))) validation_steps = max(1, int(np.ceil(n_val / BATCH_SIZE)))
history = model.fit( train_ds, validation_data=val_ds, epochs=EPOCHS, steps_per_epoch=steps_per_epoch, validation_steps=validation_steps, verbose=1, )
save_path = f"{model_type}_best.keras" model.save(save_path) print(f"✔ {model_type} saved → {save_path}") return model, history```
4. Run all cells from top to bottom to confirm there are no errors.5. The notebook output should show three training runs (M1, M2, M3) completing without a `NameError`.
---
### Fix 2 — Replace Synthetic Toy Data with Real CASIA v2
**Problem:** The current dataset is:- **Authentic**: random noise pixels (RGB 100–200), no real photographic content- **Forged**: same random noise + a solid red rectangle at fixed coordinates [50–150, 50–150]
The model trivially learns "red rectangle = forged" and achieves 100% accuracy. This has **no relationship to real image forgery detection**. The architecture, ELA, and Grad-CAM are all correctly implemented — but without real data, none of it is being tested.
**Why this matters:** An examiner will immediately recognise that 100% accuracy on 120 synthetic images is not a valid result. It is the single biggest weakness in the submission.
**Steps to fix:**
#### Step 2a — Download CASIA v2
1. Go to Kaggle and search for **"CASIA v2 image forgery"** or **"CASIA 2.0 dataset"**.2. Download the dataset (approximately 3.3 GB). It contains: - ~12,614 authentic images (`Au_*.jpg`, `Au_*.tif`, etc.) - ~5,123 tampered images (`Tp_*.jpg`, `Tp_*.tif`, etc.)3. Upload to your **Google Drive** in a folder named `casia_v2/`.
#### Step 2b — Mount Drive and Point Training to Real Data
1. In the notebook, add a cell at the very beginning of the data section:
```pythonfrom google.colab import drivedrive.mount('/content/drive')
TARGET_DIR = "/content/drive/MyDrive/casia_v2" # adjust path if needed```
2. Remove or comment out the call to `generate_robust_dataset()` — you no longer need synthetic data.3. Run `split_dataset(TARGET_DIR)` directly on the real data.
#### Step 2c — Verify the Split is Correct
After splitting, print and confirm the numbers look reasonable:
```pythonsplits = split_dataset(TARGET_DIR)print(f"Train: {len(splits['train'])} | Val: {len(splits['val'])} | Test: {len(splits['test'])}")
# Also check label distributionfor split_name, paths in splits.items(): authentic = sum(1 for p in paths if os.path.basename(p).startswith('Au_')) forged = sum(1 for p in paths if os.path.basename(p).startswith('Tp_')) print(f"{split_name}: {authentic} authentic, {forged} forged")```
Expected output (approximate):```Train: ~14,000 | Val: ~1,700 | Test: ~1,700train: ~10,000 authentic, ~4,000 forged```
#### Step 2d — Note on Class Imbalance
CASIA v2 has roughly 2.5× more authentic than tampered images. Update the model compilation to handle this:
```python# Add class_weight to model.fit to handle imbalancefrom sklearn.utils.class_weight import compute_class_weight
all_labels = train_labels # the label array from preload_imagesclasses = np.unique(all_labels)weights = compute_class_weight('balanced', classes=classes, y=all_labels)class_weight_dict = dict(zip(classes, weights))print("Class weights:", class_weight_dict)```
Pass `class_weight=class_weight_dict` to `model.fit()`.
#### Step 2e — Re-train and Save Model
Re-run training. The accuracy will no longer be 100%. Expect:- A reasonable result is **80–92% accuracy** on real CASIA v2 with this architecture- If accuracy is above 95%, double-check for data leakage- If accuracy is below 70%, consider increasing EPOCHS to 10–15
Save the newly trained M3 to `M3_best.keras` and download it from Colab:
```pythonfrom google.colab import filesfiles.download('M3_best.keras')```
Then replace the existing `M3_best.keras` in the repo with the newly trained file (Git LFS will handle the upload).
---
## HIGH PRIORITY FIXES
---
### Fix 3 — Reorder Notebook Sections
**Problem:** The notebook section headings appear in the wrong order:- Cell-10 is labelled **§9 Execute** but appears before §7 and §8- Cell-11 is **§7 Explainability**- Cell-13 is **§8 Interactive Interface**
This makes the notebook hard to follow and looks unpolished for submission.
**Steps to fix:**
1. Open the notebook in Colab.2. Rearrange cells so the section flow is: - §1 Setup & Dependencies - §2 Synthetic Dataset Generation *(keep for reproducibility reference, but mark as "optional / replaced by real data")* - §3 ELA Utility - §4 Data Pipeline (CASIAParser, split_dataset, preload_images, make_dataset) - §5 Model Architecture (get_rgb_branch, get_ela_branch, build_model) - §6 Training Engine (`run_training` — now added from Fix 1) - §7 Explainability (get_gradcam) - §8 Interactive Interface (Gradio demo) - §9 Execute: 3-Way Ablation Study (the main run cell) - §10 Results & Evaluation *(new — see Fix 4)*
3. Renumber all section headings to match the above order.4. Run all cells again to confirm execution order is correct.
---
### Fix 4 — Add Proper Evaluation Metrics
**Problem:** The only evaluation metric reported is `accuracy`. For a forensics/detection task on an imbalanced dataset, accuracy alone is misleading — a model that always predicts "authentic" would achieve ~71% accuracy on CASIA v2 while being completely useless.
**Steps to fix:**
1. After the training/evaluation cell (§9), add a new section **§10 Results & Evaluation**.2. Add the following evaluation code:
```pythonfrom sklearn.metrics import ( confusion_matrix, classification_report, roc_auc_score, RocCurveDisplay)import matplotlib.pyplot as pltimport seaborn as sns
# --- Get predictions on the test set ---test_ds_m3 = adapt_dataset_for_model( make_dataset(test_rgb, test_ela, test_labels, repeat=False), 'M3')
y_pred_prob = model_m3.predict(test_ds_m3, verbose=0).flatten()y_pred = (y_pred_prob > 0.5).astype(int)y_true = test_labels
# --- Classification Report ---print("="*50)print("M3 (Fused) — Classification Report")print("="*50)print(classification_report(y_true, y_pred, target_names=['Authentic', 'Forged']))
# --- Confusion Matrix ---cm = confusion_matrix(y_true, y_pred)fig, ax = plt.subplots(figsize=(5, 4))sns.heatmap(cm, annot=True, fmt='d', cmap='Blues', xticklabels=['Authentic', 'Forged'], yticklabels=['Authentic', 'Forged'])ax.set_xlabel('Predicted')ax.set_ylabel('Actual')ax.set_title('M3 Confusion Matrix')plt.tight_layout()plt.savefig('confusion_matrix_m3.png', dpi=150)plt.show()
# --- ROC-AUC ---auc = roc_auc_score(y_true, y_pred_prob)print(f"ROC-AUC Score: {auc:.4f}")RocCurveDisplay.from_predictions(y_true, y_pred_prob)plt.title("M3 ROC Curve")plt.savefig('roc_curve_m3.png', dpi=150)plt.show()```
3. Also run the same evaluation for M1 and M2, then produce a **comparison table**:
```pythonresults = {}for name, model, m_type in [("M1_RGB", model_m1, 'M1'), ("M2_ELA", model_m2, 'M2'), ("M3_Fused", model_m3, 'M3')]: ds = adapt_dataset_for_model( make_dataset(test_rgb, test_ela, test_labels, repeat=False), m_type ) probs = model.predict(ds, verbose=0).flatten() preds = (probs > 0.5).astype(int) from sklearn.metrics import f1_score, precision_score, recall_score results[name] = { 'Accuracy': np.mean(preds == test_labels), 'Precision': precision_score(test_labels, preds, zero_division=0), 'Recall': recall_score(test_labels, preds, zero_division=0), 'F1': f1_score(test_labels, preds, zero_division=0), 'AUC': roc_auc_score(test_labels, probs), }
import pandas as pddf_results = pd.DataFrame(results).Tprint("\nAblation Study Results")print(df_results.to_string(float_format="{:.4f}".format))```
4. Save `confusion_matrix_m3.png` and `roc_curve_m3.png` — include these images in your project report.
---
### Fix 5 — Make the Ablation Study Meaningful
**Problem:** With synthetic data, M1=M2=M3=100% — the ablation study proves nothing. With real CASIA v2 data (from Fix 2), the three models will produce genuinely different results, making the ablation meaningful.
**Steps to fix (depends on Fix 2 and Fix 4 being done first):**
1. Once real data training is complete, you should see a pattern similar to published results: - M1 (RGB only): moderate accuracy, ~75–85% - M2 (ELA only): lower accuracy on complex forgeries, ~70–80% - M3 (Fused): highest accuracy, ~85–92%2. The comparison table from Fix 4 is your ablation study table.3. In the notebook, add a markdown cell before the results table with this text:
```markdown## Ablation Study: Why Fusion Works
| Model | Input | Expected Strength | Expected Weakness ||-------|-------|-------------------|-------------------|| M1 (RGB) | Original image | Detects semantic inconsistencies | Misses compression artifacts || M2 (ELA) | ELA residuals | Detects compression tampering | Misses structural forgeries || M3 (Fused) | Both | Combines both signals | Slightly slower inference |
The fused model (M3) is expected to outperform both single-branch models because itcombines semantic visual evidence (RGB) with forensic compression evidence (ELA).```
---
## MEDIUM PRIORITY FIXES
---
### Fix 6 — Update `train.py` to Match the Notebook
**Problem:** `train.py` only builds and trains M3. It is missing M1, M2, the `adapt_dataset_for_model()` helper, and the `run_training()` function — all of which exist in the notebook.
**Steps to fix:**
1. Add `adapt_dataset_for_model()` from the notebook to `train.py`.2. Add `run_training()` (same function from Fix 1) to `train.py`.3. Update the `build_model()` function signature to accept a `model_type` parameter (`'M1'`, `'M2'`, `'M3'`) — same as the notebook version.4. Update the `if __name__ == "__main__":` block to train all three models and print the ablation comparison.
---
### Fix 7 — Add the Project Report to the Repository
**Problem:** `README.md` references `Documents/Project_Report_Digital_Image_Forgery_Detector.docx` but neither the file nor the `Documents/` folder exists in the repo.
**Steps to fix:**
1. Create the `Documents/` folder in the repo root.2. Place the project report `.docx` file inside it.3. `git add Documents/` and commit.
If the report does not yet exist, remove the reference from `README.md` until it is ready.
---
### Fix 8 — Add a Literature Comparison Section
**Problem:** The notebook does not reference any published results on CASIA v2, making it impossible for an examiner to judge whether the results are competitive.
**Steps to fix:**
1. After the results table (§10), add a markdown cell titled **"Comparison with Published Baselines"**.2. Include a table similar to this (fill in your actual results after Fix 2):
```markdown## Comparison with Published Baselines (CASIA v2)
| Method | Accuracy | F1 | Notes ||--------|----------|----|-------|| Rao et al. (2016) — CNN on SRM features | 82.2% | — | Single-branch || Salloum et al. (2018) — FCN | 89.3% | — | Pixel-level || **Our M1 (RGB only)** | _your result_ | _your result_ | ResNet50 || **Our M2 (ELA only)** | _your result_ | _your result_ | Custom CNN || **Our M3 (Fused)** | _your result_ | _your result_ | Dual-branch |
Note: Published results use full CASIA v2; our results use the same dataset withan 80/10/10 train/val/test split.```
3. Add a brief (2–3 sentence) comment in the markdown on whether your M3 result is competitive and why it may be higher or lower.
---
## LOW PRIORITY FIXES
---
### Fix 9 — Align `get_gradcam()` in `app.py` with the Notebook
**Problem:** The notebook's `get_gradcam()` uses a `model_type` parameter to intelligently pick the correct last conv layer for each model variant. The `app.py` version is a simplified copy that only searches for `conv2d` named layers.
This currently works correctly for M3 since the last `conv2d` in M3 belongs to the ELA branch, which is the forensically meaningful branch. However, if the model is ever updated or swapped, this could silently pick the wrong layer.
**Steps to fix:**
1. In `app.py`, replace the `get_gradcam()` function with the more robust version from the notebook.2. Since `app.py` only ever runs M3, hard-code `model_type='M3'` in the call: ```python heatmap = get_gradcam(m3, input_data, model_type='M3') ```
---
### Fix 10 — Document the Gradio → Streamlit Difference
**Problem:** The notebook uses **Gradio** for its interactive demo (Colab-native), while the deployed app uses **Streamlit** (Hugging Face Spaces). This difference is intentional and correct, but it is not explained anywhere, which could confuse an examiner.
**Steps to fix:**
1. Add a sentence to `README.md` under a new heading **"Development vs Deployment UI"**:
```markdown## Development vs Deployment UI
The Colab notebook uses **Gradio** for its interactive demo because Gradio worksnatively within Colab with a public share link. The deployed Hugging Face Spaceuses **Streamlit** because it is the SDK configured in the Space settings.Both interfaces implement identical inference logic.```
---
## Implementation Order (Recommended)
Work through the fixes in this order to avoid rework:
```Fix 2a-b → Download and mount CASIA v2 dataFix 1 → Add run_training() to notebookFix 3 → Reorder notebook sectionsFix 2c-e → Retrain on real data, save new M3_best.kerasFix 4 → Add confusion matrix, F1, ROC-AUCFix 5 → Validate and write up ablation studyFix 6 → Update train.py to match notebookFix 7 → Add project report to repoFix 8 → Add literature comparisonFix 9 → Improve get_gradcam in app.pyFix 10 → Update README.md```
---
## Definition of Done
The submission is ready when:
- [ ] Notebook runs end-to-end in Colab without errors (no missing functions)- [ ] Notebook sections are numbered and ordered correctly- [ ] Training uses real CASIA v2 data (not synthetic noise)- [ ] Accuracy is in a realistic range (75–92%) — not 100%- [ ] Class imbalance is handled via class weights- [ ] Evaluation section includes: confusion matrix, precision, recall, F1, ROC-AUC- [ ] Ablation study table compares M1, M2, M3 across all metrics- [ ] Literature comparison table is present with at least two baselines- [ ] `train.py` trains all three models (M1, M2, M3)- [ ] `M3_best.keras` in the repo was trained on real data- [ ] `Documents/` folder contains the project report- [ ] `README.md` explains the Gradio vs Streamlit difference- [ ] HF Space is redeployed with the new model weights1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Remediation & Enhancement Plan — Image Forgery Detector</title><style> /* ── Reset & Base ─────────────────────────────────────────────── */ *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
:root { --critical: #dc2626; --critical-bg: #fef2f2; --critical-border: #fca5a5; --high: #d97706; --high-bg: #fffbeb; --high-border: #fcd34d; --medium: #2563eb; --medium-bg: #eff6ff; --medium-border: #93c5fd; --low: #16a34a; --low-bg: #f0fdf4; --low-border: #86efac; --code-bg: #0f172a; --code-text: #e2e8f0; --sidebar-w: 270px; --header-h: 64px; }
body { font-family: 'Segoe UI', system-ui, -apple-system, sans-serif; font-size: 15px; line-height: 1.7; color: #1e293b; background: #f8fafc; }
/* ── Top Header ───────────────────────────────────────────────── */ .top-header { position: fixed; top: 0; left: 0; right: 0; height: var(--header-h); background: #0f172a; display: flex; align-items: center; padding: 0 32px; z-index: 200; gap: 16px; } .top-header .shield { font-size: 26px; } .top-header h1 { font-size: 17px; font-weight: 700; color: #f1f5f9; line-height: 1.2; } .top-header h1 span { color: #94a3b8; font-weight: 400; font-size: 13px; display: block; } .top-header .tag { margin-left: auto; background: #1e3a5f; color: #93c5fd; font-size: 12px; font-weight: 600; padding: 4px 12px; border-radius: 20px; border: 1px solid #2563eb44; }
/* ── Sidebar ──────────────────────────────────────────────────── */ .sidebar { position: fixed; top: var(--header-h); left: 0; bottom: 0; width: var(--sidebar-w); background: #fff; border-right: 1px solid #e2e8f0; overflow-y: auto; padding: 24px 0; z-index: 100; } .sidebar-section { padding: 6px 24px 2px; font-size: 10px; font-weight: 700; letter-spacing: 0.1em; text-transform: uppercase; color: #94a3b8; margin-top: 12px; } .sidebar a { display: flex; align-items: center; gap: 10px; padding: 7px 24px; font-size: 13px; color: #475569; text-decoration: none; border-left: 3px solid transparent; transition: all 0.15s; } .sidebar a:hover { background: #f1f5f9; color: #0f172a; border-left-color: #94a3b8; } .sidebar a .badge { font-size: 10px; font-weight: 700; padding: 2px 6px; border-radius: 4px; flex-shrink: 0; } .badge.critical { background: var(--critical-bg); color: var(--critical); } .badge.high { background: var(--high-bg); color: var(--high); } .badge.medium { background: var(--medium-bg); color: var(--medium); } .badge.low { background: var(--low-bg); color: var(--low); }
/* ── Main Content ─────────────────────────────────────────────── */ .main { margin-left: var(--sidebar-w); margin-top: var(--header-h); padding: 40px 48px 80px; max-width: 960px; }
/* ── Hero ─────────────────────────────────────────────────────── */ .hero { background: linear-gradient(135deg, #0f172a 0%, #1e3a5f 100%); border-radius: 16px; padding: 40px 44px; margin-bottom: 40px; color: #f1f5f9; } .hero h2 { font-size: 26px; font-weight: 800; margin-bottom: 8px; } .hero p { color: #94a3b8; font-size: 14px; max-width: 600px; } .hero .stats { display: flex; gap: 24px; margin-top: 28px; flex-wrap: wrap; } .hero .stat { background: rgba(255,255,255,0.06); border: 1px solid rgba(255,255,255,0.1); border-radius: 10px; padding: 14px 20px; min-width: 110px; } .hero .stat .n { font-size: 28px; font-weight: 800; line-height: 1; } .hero .stat .l { font-size: 11px; color: #94a3b8; margin-top: 4px; } .hero .stat.c .n { color: #f87171; } .hero .stat.h .n { color: #fbbf24; } .hero .stat.m .n { color: #60a5fa; } .hero .stat.lo .n { color: #4ade80; }
/* ── Issue Summary Table ──────────────────────────────────────── */ .summary-table { width: 100%; border-collapse: collapse; background: #fff; border-radius: 12px; overflow: hidden; box-shadow: 0 1px 3px rgba(0,0,0,0.08); margin-bottom: 48px; } .summary-table th { background: #f1f5f9; text-align: left; padding: 12px 16px; font-size: 12px; font-weight: 700; letter-spacing: 0.05em; text-transform: uppercase; color: #64748b; } .summary-table td { padding: 12px 16px; font-size: 13.5px; border-top: 1px solid #f1f5f9; vertical-align: middle; } .summary-table tr:hover td { background: #fafafa; } .summary-table td code { background: #f1f5f9; padding: 2px 6px; border-radius: 4px; font-size: 12px; font-family: 'Cascadia Code', 'Fira Code', 'Consolas', monospace; color: #0f172a; } .num-badge { display: inline-flex; align-items: center; justify-content: center; width: 24px; height: 24px; border-radius: 50%; font-size: 12px; font-weight: 700; background: #e2e8f0; color: #475569; }
/* ── Section Headings ─────────────────────────────────────────── */ .section-header { display: flex; align-items: center; gap: 12px; margin: 48px 0 24px; } .section-header .pill { padding: 6px 18px; border-radius: 99px; font-size: 12px; font-weight: 800; letter-spacing: 0.08em; text-transform: uppercase; } .pill.critical { background: var(--critical); color: #fff; } .pill.high { background: var(--high); color: #fff; } .pill.medium { background: var(--medium); color: #fff; } .pill.low { background: var(--low); color: #fff; } .section-header hr { flex: 1; border: none; border-top: 2px solid #e2e8f0; }
/* ── Fix Cards ────────────────────────────────────────────────── */ .fix-card { background: #fff; border-radius: 14px; border: 1.5px solid #e2e8f0; margin-bottom: 28px; overflow: hidden; box-shadow: 0 1px 3px rgba(0,0,0,0.06); } .fix-card.critical { border-color: var(--critical-border); } .fix-card.high { border-color: var(--high-border); } .fix-card.medium { border-color: var(--medium-border); } .fix-card.low { border-color: var(--low-border); }
.fix-header { display: flex; align-items: center; gap: 14px; padding: 20px 24px; border-bottom: 1px solid #f1f5f9; } .fix-num { width: 36px; height: 36px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 15px; font-weight: 800; flex-shrink: 0; } .fix-card.critical .fix-num { background: var(--critical-bg); color: var(--critical); } .fix-card.high .fix-num { background: var(--high-bg); color: var(--high); } .fix-card.medium .fix-num { background: var(--medium-bg); color: var(--medium); } .fix-card.low .fix-num { background: var(--low-bg); color: var(--low); }
.fix-title { font-size: 16px; font-weight: 700; color: #0f172a; } .fix-body { padding: 24px; }
.problem-box { border-radius: 10px; padding: 16px 20px; margin-bottom: 20px; font-size: 14px; } .fix-card.critical .problem-box { background: var(--critical-bg); border-left: 4px solid var(--critical); } .fix-card.high .problem-box { background: var(--high-bg); border-left: 4px solid var(--high); } .fix-card.medium .problem-box { background: var(--medium-bg); border-left: 4px solid var(--medium); } .fix-card.low .problem-box { background: var(--low-bg); border-left: 4px solid var(--low); }
.problem-box .label { font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.08em; margin-bottom: 6px; } .fix-card.critical .problem-box .label { color: var(--critical); } .fix-card.high .problem-box .label { color: var(--high); } .fix-card.medium .problem-box .label { color: var(--medium); } .fix-card.low .problem-box .label { color: var(--low); }
.why-box { background: #f8fafc; border-radius: 8px; padding: 12px 16px; margin-bottom: 20px; font-size: 13.5px; color: #475569; border: 1px solid #e2e8f0; } .why-box strong { color: #1e293b; }
/* ── Steps ────────────────────────────────────────────────────── */ .steps { counter-reset: step; } .step { display: flex; gap: 14px; margin-bottom: 14px; align-items: flex-start; } .step::before { counter-increment: step; content: counter(step); min-width: 26px; height: 26px; background: #1e293b; color: #fff; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 12px; font-weight: 700; flex-shrink: 0; margin-top: 2px; } .step p { font-size: 14px; color: #374151; }
/* ── Sub-steps ────────────────────────────────────────────────── */ .substep-heading { font-size: 13px; font-weight: 700; color: #0f172a; margin: 20px 0 10px; display: flex; align-items: center; gap: 8px; } .substep-heading::before { content: ''; display: block; width: 3px; height: 14px; background: #cbd5e1; border-radius: 2px; }
/* ── Code Blocks ──────────────────────────────────────────────── */ .code-wrap { background: var(--code-bg); border-radius: 10px; margin: 14px 0; overflow: hidden; } .code-label { background: #1e293b; padding: 7px 16px; font-size: 11px; font-weight: 600; color: #94a3b8; letter-spacing: 0.05em; display: flex; align-items: center; gap: 8px; } .code-label::before { content: ''; display: inline-block; width: 8px; height: 8px; background: #4ade80; border-radius: 50%; } pre { padding: 18px 20px; overflow-x: auto; font-family: 'Cascadia Code', 'Fira Code', 'Consolas', monospace; font-size: 13px; line-height: 1.65; color: var(--code-text); } /* Simple syntax colouring via CSS */ .kw { color: #c084fc; } /* keywords */ .fn { color: #60a5fa; } /* functions */ .st { color: #86efac; } /* strings */ .cm { color: #475569; font-style: italic; } /* comments */ .nb { color: #fbbf24; } /* numbers */
/* ── Expected output box ──────────────────────────────────────── */ .expected { background: #0f2810; border: 1px solid #166534; border-radius: 8px; padding: 12px 16px; font-family: 'Cascadia Code', 'Consolas', monospace; font-size: 12.5px; color: #86efac; margin: 10px 0; } .expected .exp-label { font-size: 10px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.08em; color: #4ade80; margin-bottom: 6px; font-family: 'Segoe UI', sans-serif; }
/* ── Inline code ──────────────────────────────────────────────── */ code { background: #f1f5f9; padding: 2px 6px; border-radius: 4px; font-size: 12.5px; font-family: 'Cascadia Code', 'Fira Code', 'Consolas', monospace; color: #0f172a; }
/* ── Info callout ─────────────────────────────────────────────── */ .callout { background: #eff6ff; border-left: 4px solid #3b82f6; border-radius: 0 8px 8px 0; padding: 12px 16px; margin: 14px 0; font-size: 13.5px; color: #1e40af; }
/* ── Ablation table ───────────────────────────────────────────── */ .model-table { width: 100%; border-collapse: collapse; font-size: 13px; margin: 14px 0; } .model-table th { background: #1e293b; color: #e2e8f0; padding: 10px 14px; text-align: left; font-size: 11px; text-transform: uppercase; letter-spacing: 0.06em; } .model-table td { padding: 10px 14px; border-bottom: 1px solid #f1f5f9; } .model-table tr:nth-child(even) td { background: #f8fafc; }
/* ── Implementation order ─────────────────────────────────────── */ .order-flow { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; margin: 16px 0; } .order-step { background: #1e293b; color: #e2e8f0; padding: 8px 14px; border-radius: 8px; font-size: 13px; font-weight: 600; } .order-step span { color: #94a3b8; font-weight: 400; font-size: 11px; display: block; } .order-arrow { color: #94a3b8; font-size: 18px; }
/* ── Checklist ────────────────────────────────────────────────── */ .checklist { list-style: none; background: #fff; border: 1.5px solid #e2e8f0; border-radius: 14px; overflow: hidden; box-shadow: 0 1px 3px rgba(0,0,0,0.06); } .checklist li { display: flex; align-items: flex-start; gap: 12px; padding: 13px 20px; border-bottom: 1px solid #f1f5f9; font-size: 14px; cursor: pointer; transition: background 0.1s; } .checklist li:last-child { border-bottom: none; } .checklist li:hover { background: #f8fafc; } .checklist li input[type=checkbox] { margin-top: 3px; width: 16px; height: 16px; accent-color: #16a34a; cursor: pointer; flex-shrink: 0; } .checklist li label { cursor: pointer; } .checklist li input:checked + label { text-decoration: line-through; color: #94a3b8; }
/* ── Section scroll target padding ───────────────────────────── */ section[id] { scroll-margin-top: calc(var(--header-h) + 20px); }
/* ── Responsive ───────────────────────────────────────────────── */ @media (max-width: 768px) { .sidebar { display: none; } .main { margin-left: 0; padding: 24px 20px 60px; } }</style></head><body>
<!-- ── Top Header ───────────────────────────────────────────────── --><header class="top-header"> <span class="shield">🛡️</span> <h1>Image Forgery Detector <span>Remediation & Enhancement Plan — PGD Student Project</span> </h1> <span class="tag">10 Issues · 4 Severity Levels</span></header>
<!-- ── Sidebar ──────────────────────────────────────────────────── --><nav class="sidebar"> <div class="sidebar-section">Overview</div> <a href="#summary">Issue Summary</a> <a href="#order">Implementation Order</a> <a href="#done">Definition of Done</a>
<div class="sidebar-section">Critical Fixes</div> <a href="#fix1"><span class="badge critical">C</span> Fix 1 — run_training()</a> <a href="#fix2"><span class="badge critical">C</span> Fix 2 — Real Dataset</a>
<div class="sidebar-section">High Priority</div> <a href="#fix3"><span class="badge high">H</span> Fix 3 — Notebook Order</a> <a href="#fix4"><span class="badge high">H</span> Fix 4 — Eval Metrics</a> <a href="#fix5"><span class="badge high">H</span> Fix 5 — Ablation Study</a>
<div class="sidebar-section">Medium Priority</div> <a href="#fix6"><span class="badge medium">M</span> Fix 6 — train.py Parity</a> <a href="#fix7"><span class="badge medium">M</span> Fix 7 — Project Report</a> <a href="#fix8"><span class="badge medium">M</span> Fix 8 — Literature</a>
<div class="sidebar-section">Low Priority</div> <a href="#fix9"><span class="badge low">L</span> Fix 9 — Grad-CAM</a> <a href="#fix10"><span class="badge low">L</span> Fix 10 — README</a></nav>
<!-- ── Main ─────────────────────────────────────────────────────── --><main class="main">
<!-- Hero --> <div class="hero"> <h2>Remediation & Enhancement Plan</h2> <p>Every gap found during validation, with step-by-step actions to fix each one. Work through fixes <strong>in priority order</strong> — later fixes depend on earlier ones.</p> <div class="stats"> <div class="stat c"><div class="n">2</div><div class="l">Critical</div></div> <div class="stat h"><div class="n">3</div><div class="l">High</div></div> <div class="stat m"><div class="n">3</div><div class="l">Medium</div></div> <div class="stat lo"><div class="n">2</div><div class="l">Low</div></div> </div> </div>
<!-- Issue Summary --> <section id="summary"> <h2 style="font-size:20px;font-weight:800;margin-bottom:16px;color:#0f172a;">Quick Reference: All Issues</h2> <table class="summary-table"> <thead> <tr> <th>#</th><th>Severity</th><th>Issue</th><th>Files Affected</th> </tr> </thead> <tbody> <tr> <td><span class="num-badge">1</span></td> <td><span class="badge critical">CRITICAL</span></td> <td><code>run_training()</code> never defined in notebook</td> <td><code>.ipynb</code></td> </tr> <tr> <td><span class="num-badge">2</span></td> <td><span class="badge critical">CRITICAL</span></td> <td>Synthetic toy data — model learns nothing real</td> <td><code>.ipynb</code>, <code>train.py</code></td> </tr> <tr> <td><span class="num-badge">3</span></td> <td><span class="badge high">HIGH</span></td> <td>Notebook section order is broken (§9 → §7 → §8)</td> <td><code>.ipynb</code></td> </tr> <tr> <td><span class="num-badge">4</span></td> <td><span class="badge high">HIGH</span></td> <td>No meaningful evaluation metrics (only accuracy)</td> <td><code>.ipynb</code></td> </tr> <tr> <td><span class="num-badge">5</span></td> <td><span class="badge high">HIGH</span></td> <td>Ablation study conclusion is invalid (all 100%)</td> <td><code>.ipynb</code></td> </tr> <tr> <td><span class="num-badge">6</span></td> <td><span class="badge medium">MEDIUM</span></td> <td><code>train.py</code> only trains M3, not M1/M2</td> <td><code>train.py</code></td> </tr> <tr> <td><span class="num-badge">7</span></td> <td><span class="badge medium">MEDIUM</span></td> <td>Project report document missing from repo</td> <td><code>Documents/</code></td> </tr> <tr> <td><span class="num-badge">8</span></td> <td><span class="badge medium">MEDIUM</span></td> <td>No literature comparison or baseline results</td> <td><code>.ipynb</code></td> </tr> <tr> <td><span class="num-badge">9</span></td> <td><span class="badge low">LOW</span></td> <td><code>get_gradcam()</code> in app.py is simplified vs notebook</td> <td><code>app.py</code></td> </tr> <tr> <td><span class="num-badge">10</span></td> <td><span class="badge low">LOW</span></td> <td>Gradio vs Streamlit discrepancy not documented</td> <td><code>README.md</code></td> </tr> </tbody> </table> </section>
<!-- ═══════════════════════════ CRITICAL ═════════════════════════ --> <div class="section-header"> <span class="pill critical">Critical Fixes</span> <hr> </div>
<!-- Fix 1 --> <section id="fix1"> <div class="fix-card critical"> <div class="fix-header"> <div class="fix-num">1</div> <div class="fix-title">Add the Missing <code>run_training()</code> Function to the Notebook</div> </div> <div class="fix-body"> <div class="problem-box"> <div class="label">Problem</div> Cell 16 calls <code>run_training('M1', ...)</code>, <code>run_training('M2', ...)</code>, and <code>run_training('M3', ...)</code> but this function is <strong>never defined</strong> in any visible cell. The notebook cannot be run end-to-end — an examiner will get a <code>NameError</code> immediately. </div> <div class="why-box"> <strong>Why it matters:</strong> A Colab notebook is expected to be fully self-contained. Every function called must be defined above its call site. </div>
<div class="steps"> <div class="step"><p>Open <code>Image_Forgery_Detection_Colab_1.ipynb</code> in Google Colab.</p></div> <div class="step"><p>Insert a new code cell <strong>between the <code>build_model()</code> cell and the ablation execution cell</strong> (between current cell-9 and cell-16).</p></div> <div class="step"><p>Paste the following function into that new cell:</p></div> </div>
<div class="code-wrap"> <div class="code-label">Python — run_training() definition</div> <pre><span class="kw">def</span> <span class="fn">run_training</span>(model_type, train_ds_base, val_ds_base, n_train, n_val): <span class="fn">print</span>(<span class="st">f"\n{'='*55}"</span>) <span class="fn">print</span>(<span class="st">f"Training {model_type}"</span>) <span class="fn">print</span>(<span class="st">f"{'='*55}"</span>)
train_ds = <span class="fn">adapt_dataset_for_model</span>(train_ds_base, model_type) val_ds = <span class="fn">adapt_dataset_for_model</span>(val_ds_base, model_type)
model = <span class="fn">build_model</span>(model_type) model.<span class="fn">compile</span>( optimizer=<span class="st">'adam'</span>, loss=<span class="st">'binary_crossentropy'</span>, metrics=[<span class="st">'accuracy'</span>] )
steps_per_epoch = <span class="fn">max</span>(<span class="nb">1</span>, <span class="fn">int</span>(np.<span class="fn">ceil</span>(n_train / BATCH_SIZE))) validation_steps = <span class="fn">max</span>(<span class="nb">1</span>, <span class="fn">int</span>(np.<span class="fn">ceil</span>(n_val / BATCH_SIZE)))
history = model.<span class="fn">fit</span>( train_ds, validation_data=val_ds, epochs=EPOCHS, steps_per_epoch=steps_per_epoch, validation_steps=validation_steps, verbose=<span class="nb">1</span>, )
save_path = <span class="st">f"{model_type}_best.keras"</span> model.<span class="fn">save</span>(save_path) <span class="fn">print</span>(<span class="st">f"✔ {model_type} saved → {save_path}"</span>) <span class="kw">return</span> model, history</pre> </div>
<div class="steps"> <div class="step"><p>Run all cells from top to bottom to confirm there are no errors.</p></div> <div class="step"><p>Confirm the output shows three training runs (M1, M2, M3) completing with no <code>NameError</code>.</p></div> </div> </div> </div> </section>
<!-- Fix 2 --> <section id="fix2"> <div class="fix-card critical"> <div class="fix-header"> <div class="fix-num">2</div> <div class="fix-title">Replace Synthetic Toy Data with Real CASIA v2</div> </div> <div class="fix-body"> <div class="problem-box"> <div class="label">Problem</div> Current dataset: <strong>Authentic</strong> = random noise (RGB 100–200) | <strong>Forged</strong> = same noise + a solid red rectangle at [50–150, 50–150]. The model learns "red rectangle = forged" and gets 100% accuracy — this has <strong>no relationship to real image forgery detection</strong>. </div> <div class="why-box"> <strong>Why it matters:</strong> An examiner will immediately recognise that 100% accuracy on 120 synthetic noise images is not a valid result. It is the single biggest weakness in the submission. </div>
<div class="substep-heading">Step 2a — Download CASIA v2</div> <div class="steps"> <div class="step"><p>Go to <strong>Kaggle</strong> and search for <em>"CASIA v2 image forgery"</em> or <em>"CASIA 2.0 dataset"</em>.</p></div> <div class="step"><p>Download the dataset (~3.3 GB). It contains ~12,614 authentic images (<code>Au_*</code>) and ~5,123 tampered images (<code>Tp_*</code>).</p></div> <div class="step"><p>Upload the extracted folder to your <strong>Google Drive</strong> and name it <code>casia_v2/</code>.</p></div> </div>
<div class="substep-heading">Step 2b — Mount Drive and Update Data Path</div> <div class="steps"> <div class="step"><p>Add this cell at the top of the data section in the notebook:</p></div> </div> <div class="code-wrap"> <div class="code-label">Python — Mount Google Drive</div> <pre><span class="kw">from</span> google.colab <span class="kw">import</span> drivedrive.<span class="fn">mount</span>(<span class="st">'/content/drive'</span>)
TARGET_DIR = <span class="st">"/content/drive/MyDrive/casia_v2"</span> <span class="cm"># adjust if needed</span></pre> </div> <div class="steps"> <div class="step"><p>Comment out or remove the call to <code>generate_robust_dataset()</code> — synthetic data is no longer needed.</p></div> <div class="step"><p>Run <code>split_dataset(TARGET_DIR)</code> directly on the real data path.</p></div> </div>
<div class="substep-heading">Step 2c — Verify the Split</div> <div class="code-wrap"> <div class="code-label">Python — Verify split counts and label balance</div> <pre>splits = <span class="fn">split_dataset</span>(TARGET_DIR)<span class="fn">print</span>(<span class="st">f"Train: {len(splits['train'])} | Val: {len(splits['val'])} | Test: {len(splits['test'])}"</span>)
<span class="kw">for</span> split_name, paths <span class="kw">in</span> splits.items(): authentic = <span class="fn">sum</span>(<span class="nb">1</span> <span class="kw">for</span> p <span class="kw">in</span> paths <span class="kw">if</span> os.path.<span class="fn">basename</span>(p).<span class="fn">startswith</span>(<span class="st">'Au_'</span>)) forged = <span class="fn">sum</span>(<span class="nb">1</span> <span class="kw">for</span> p <span class="kw">in</span> paths <span class="kw">if</span> os.path.<span class="fn">basename</span>(p).<span class="fn">startswith</span>(<span class="st">'Tp_'</span>)) <span class="fn">print</span>(<span class="st">f"{split_name}: {authentic} authentic, {forged} forged"</span>)</pre> </div> <div class="expected"> <div class="exp-label">Expected Output (approximate)</div>Train: ~14000 | Val: ~1700 | Test: ~1700train: ~10000 authentic, ~4000 forged </div>
<div class="substep-heading">Step 2d — Handle Class Imbalance</div> <div class="callout"> CASIA v2 has ~2.5× more authentic than tampered images. Without class weights, the model will bias toward predicting "authentic" and appear to have high accuracy while missing most forgeries. </div> <div class="code-wrap"> <div class="code-label">Python — Compute class weights</div> <pre><span class="kw">from</span> sklearn.utils.class_weight <span class="kw">import</span> compute_class_weight
classes = np.<span class="fn">unique</span>(train_labels)weights = <span class="fn">compute_class_weight</span>(<span class="st">'balanced'</span>, classes=classes, y=train_labels)class_weight_dict = <span class="fn">dict</span>(<span class="fn">zip</span>(classes, weights))<span class="fn">print</span>(<span class="st">"Class weights:"</span>, class_weight_dict)<span class="cm"># Then pass class_weight=class_weight_dict to model.fit()</span></pre> </div>
<div class="substep-heading">Step 2e — Retrain and Save</div> <div class="steps"> <div class="step"><p>Run training. Expect accuracy in the range <strong>80–92%</strong> (not 100%). If above 95%, check for data leakage. If below 70%, increase <code>EPOCHS</code> to 10–15.</p></div> <div class="step"><p>Download the trained model from Colab:</p></div> </div> <div class="code-wrap"> <div class="code-label">Python — Download model from Colab</div> <pre><span class="kw">from</span> google.colab <span class="kw">import</span> filesfiles.<span class="fn">download</span>(<span class="st">'M3_best.keras'</span>)</pre> </div> <div class="steps"> <div class="step"><p>Replace the existing <code>M3_best.keras</code> in the repo. Git LFS will handle the large file upload automatically on the next commit.</p></div> </div> </div> </div> </section>
<!-- ═══════════════════════════ HIGH ═════════════════════════════ --> <div class="section-header"> <span class="pill high">High Priority</span> <hr> </div>
<!-- Fix 3 --> <section id="fix3"> <div class="fix-card high"> <div class="fix-header"> <div class="fix-num">3</div> <div class="fix-title">Reorder Notebook Sections</div> </div> <div class="fix-body"> <div class="problem-box"> <div class="label">Problem</div> Section headings appear in the wrong order: <strong>§9</strong> (Execute) appears before <strong>§7</strong> (Explainability) and <strong>§8</strong> (Interface). The notebook is hard to follow and looks unpolished for submission. </div> <div class="steps"> <div class="step"><p>Open the notebook in Colab and rearrange cells into this order:</p></div> </div> <table class="model-table" style="margin:14px 0;"> <thead><tr><th>Section</th><th>Content</th></tr></thead> <tbody> <tr><td>§1</td><td>Setup & Dependencies</td></tr> <tr><td>§2</td><td>Synthetic Dataset Generation <em>(mark as optional — replaced by real data)</em></td></tr> <tr><td>§3</td><td>ELA Utility (<code>compute_ela</code>)</td></tr> <tr><td>§4</td><td>Data Pipeline (CASIAParser, split, preload, make_dataset)</td></tr> <tr><td>§5</td><td>Model Architecture (get_rgb_branch, get_ela_branch, build_model)</td></tr> <tr><td>§6</td><td>Training Engine (<code>run_training</code> — added in Fix 1)</td></tr> <tr><td>§7</td><td>Explainability (<code>get_gradcam</code>)</td></tr> <tr><td>§8</td><td>Interactive Interface (Gradio demo)</td></tr> <tr><td>§9</td><td>Execute: 3-Way Ablation Study</td></tr> <tr><td>§10</td><td>Results & Evaluation <em>(new — see Fix 4)</em></td></tr> </tbody> </table> <div class="steps"> <div class="step"><p>Renumber all section headings to match the table above.</p></div> <div class="step"><p>Run all cells again top-to-bottom to confirm no execution errors.</p></div> </div> </div> </div> </section>
<!-- Fix 4 --> <section id="fix4"> <div class="fix-card high"> <div class="fix-header"> <div class="fix-num">4</div> <div class="fix-title">Add Proper Evaluation Metrics</div> </div> <div class="fix-body"> <div class="problem-box"> <div class="label">Problem</div> Only <code>accuracy</code> is reported. On an imbalanced dataset like CASIA v2, a model that always predicts "authentic" achieves ~71% accuracy while being completely useless. Accuracy alone is not sufficient for a forensics task. </div> <div class="steps"> <div class="step"><p>After the training cell (§9), add a new section <strong>§10 Results & Evaluation</strong>.</p></div> <div class="step"><p>Add this evaluation code to generate a classification report and confusion matrix:</p></div> </div> <div class="code-wrap"> <div class="code-label">Python — Classification report + confusion matrix</div> <pre><span class="kw">from</span> sklearn.metrics <span class="kw">import</span> ( confusion_matrix, classification_report, roc_auc_score, RocCurveDisplay)<span class="kw">import</span> matplotlib.pyplot <span class="kw">as</span> plt<span class="kw">import</span> seaborn <span class="kw">as</span> sns
test_ds_m3 = <span class="fn">adapt_dataset_for_model</span>( <span class="fn">make_dataset</span>(test_rgb, test_ela, test_labels, repeat=<span class="kw">False</span>), <span class="st">'M3'</span>)y_pred_prob = model_m3.<span class="fn">predict</span>(test_ds_m3, verbose=<span class="nb">0</span>).<span class="fn">flatten</span>()y_pred = (y_pred_prob > <span class="nb">0.5</span>).astype(<span class="fn">int</span>)y_true = test_labels
<span class="fn">print</span>(<span class="st">"="*50</span>)<span class="fn">print</span>(<span class="st">"M3 (Fused) — Classification Report"</span>)<span class="fn">print</span>(<span class="st">"="*50</span>)<span class="fn">print</span>(<span class="fn">classification_report</span>(y_true, y_pred, target_names=[<span class="st">'Authentic'</span>, <span class="st">'Forged'</span>]))
cm = <span class="fn">confusion_matrix</span>(y_true, y_pred)fig, ax = plt.<span class="fn">subplots</span>(figsize=(<span class="nb">5</span>, <span class="nb">4</span>))sns.<span class="fn">heatmap</span>(cm, annot=<span class="kw">True</span>, fmt=<span class="st">'d'</span>, cmap=<span class="st">'Blues'</span>, xticklabels=[<span class="st">'Authentic'</span>, <span class="st">'Forged'</span>], yticklabels=[<span class="st">'Authentic'</span>, <span class="st">'Forged'</span>])ax.<span class="fn">set_xlabel</span>(<span class="st">'Predicted'</span>); ax.<span class="fn">set_ylabel</span>(<span class="st">'Actual'</span>)ax.<span class="fn">set_title</span>(<span class="st">'M3 Confusion Matrix'</span>)plt.<span class="fn">savefig</span>(<span class="st">'confusion_matrix_m3.png'</span>, dpi=<span class="nb">150</span>)plt.<span class="fn">show</span>()
auc = <span class="fn">roc_auc_score</span>(y_true, y_pred_prob)<span class="fn">print</span>(<span class="st">f"ROC-AUC Score: {auc:.4f}"</span>)<span class="fn">RocCurveDisplay</span>.<span class="fn">from_predictions</span>(y_true, y_pred_prob)plt.<span class="fn">title</span>(<span class="st">"M3 ROC Curve"</span>)plt.<span class="fn">savefig</span>(<span class="st">'roc_curve_m3.png'</span>, dpi=<span class="nb">150</span>)plt.<span class="fn">show</span>()</pre> </div> <div class="steps"> <div class="step"><p>Add the model comparison table across all three variants:</p></div> </div> <div class="code-wrap"> <div class="code-label">Python — M1 vs M2 vs M3 metrics table</div> <pre>results = {}<span class="kw">for</span> name, model, m_type <span class="kw">in</span> [(<span class="st">"M1_RGB"</span>, model_m1, <span class="st">'M1'</span>), (<span class="st">"M2_ELA"</span>, model_m2, <span class="st">'M2'</span>), (<span class="st">"M3_Fused"</span>, model_m3, <span class="st">'M3'</span>)]: ds = <span class="fn">adapt_dataset_for_model</span>( <span class="fn">make_dataset</span>(test_rgb, test_ela, test_labels, repeat=<span class="kw">False</span>), m_type) probs = model.<span class="fn">predict</span>(ds, verbose=<span class="nb">0</span>).<span class="fn">flatten</span>() preds = (probs > <span class="nb">0.5</span>).astype(<span class="fn">int</span>) <span class="kw">from</span> sklearn.metrics <span class="kw">import</span> f1_score, precision_score, recall_score results[name] = { <span class="st">'Accuracy'</span>: np.<span class="fn">mean</span>(preds == test_labels), <span class="st">'Precision'</span>: <span class="fn">precision_score</span>(test_labels, preds, zero_division=<span class="nb">0</span>), <span class="st">'Recall'</span>: <span class="fn">recall_score</span>(test_labels, preds, zero_division=<span class="nb">0</span>), <span class="st">'F1'</span>: <span class="fn">f1_score</span>(test_labels, preds, zero_division=<span class="nb">0</span>), <span class="st">'AUC'</span>: <span class="fn">roc_auc_score</span>(test_labels, probs), }
<span class="kw">import</span> pandas <span class="kw">as</span> pddf_results = pd.<span class="fn">DataFrame</span>(results).T<span class="fn">print</span>(<span class="st">"\nAblation Study Results"</span>)<span class="fn">print</span>(df_results.<span class="fn">to_string</span>(float_format=<span class="st">"{:.4f}"</span>.<span class="fn">format</span>))</pre> </div> <div class="steps"> <div class="step"><p>Save <code>confusion_matrix_m3.png</code> and <code>roc_curve_m3.png</code> and include them in the project report.</p></div> </div> </div> </div> </section>
<!-- Fix 5 --> <section id="fix5"> <div class="fix-card high"> <div class="fix-header"> <div class="fix-num">5</div> <div class="fix-title">Make the Ablation Study Meaningful</div> </div> <div class="fix-body"> <div class="problem-box"> <div class="label">Problem</div> With synthetic data, M1=M2=M3=100% — the ablation proves nothing. With real CASIA v2, the three models will produce genuinely different results. <strong>Depends on Fix 2 and Fix 4 being completed first.</strong> </div> <div class="steps"> <div class="step"> <p>After real-data training, expect results similar to this pattern:</p> </div> </div> <table class="model-table"> <thead><tr><th>Model</th><th>Input</th><th>Expected Accuracy</th><th>Strength</th><th>Weakness</th></tr></thead> <tbody> <tr><td>M1 (RGB)</td><td>Original image</td><td>~75–85%</td><td>Semantic inconsistencies</td><td>Misses compression artifacts</td></tr> <tr><td>M2 (ELA)</td><td>ELA residuals</td><td>~70–80%</td><td>Compression tampering</td><td>Misses structural forgeries</td></tr> <tr><td><strong>M3 (Fused)</strong></td><td>Both</td><td><strong>~85–92%</strong></td><td>Combines both signals</td><td>Slightly slower inference</td></tr> </tbody> </table> <div class="steps"> <div class="step"><p>The comparison table from Fix 4 is your ablation study table — no separate code needed.</p></div> <div class="step"><p>Add a markdown cell before the results table explaining why fusion outperforms single-branch models. Use the table above as a guide.</p></div> </div> </div> </div> </section>
<!-- ═══════════════════════════ MEDIUM ═══════════════════════════ --> <div class="section-header"> <span class="pill medium">Medium Priority</span> <hr> </div>
<!-- Fix 6 --> <section id="fix6"> <div class="fix-card medium"> <div class="fix-header"> <div class="fix-num">6</div> <div class="fix-title">Update <code>train.py</code> to Match the Notebook</div> </div> <div class="fix-body"> <div class="problem-box"> <div class="label">Problem</div> <code>train.py</code> only builds and trains M3. It is missing <code>adapt_dataset_for_model()</code>, <code>run_training()</code>, and M1/M2 variants — all of which exist in the notebook. </div> <div class="steps"> <div class="step"><p>Add <code>adapt_dataset_for_model()</code> from the notebook to <code>train.py</code>.</p></div> <div class="step"><p>Add <code>run_training()</code> (same as Fix 1) to <code>train.py</code>.</p></div> <div class="step"><p>Update <code>build_model()</code> to accept a <code>model_type</code> parameter (<code>'M1'</code>, <code>'M2'</code>, <code>'M3'</code>) matching the notebook version.</p></div> <div class="step"><p>Update the <code>if __name__ == "__main__":</code> block to train all three models and print the ablation comparison table.</p></div> </div> </div> </div> </section>
<!-- Fix 7 --> <section id="fix7"> <div class="fix-card medium"> <div class="fix-header"> <div class="fix-num">7</div> <div class="fix-title">Add the Project Report to the Repository</div> </div> <div class="fix-body"> <div class="problem-box"> <div class="label">Problem</div> <code>README.md</code> references <code>Documents/Project_Report_Digital_Image_Forgery_Detector.docx</code> but neither the file nor the <code>Documents/</code> folder exist in the repo. </div> <div class="steps"> <div class="step"><p>Create the <code>Documents/</code> folder in the repo root.</p></div> <div class="step"><p>Place the project report <code>.docx</code> file inside it.</p></div> <div class="step"><p>Run <code>git add Documents/</code> and commit.</p></div> </div> <div class="callout"> If the report does not yet exist, remove the reference from <code>README.md</code> until it is ready — a broken link is worse than no link. </div> </div> </div> </section>
<!-- Fix 8 --> <section id="fix8"> <div class="fix-card medium"> <div class="fix-header"> <div class="fix-num">8</div> <div class="fix-title">Add a Literature Comparison Section</div> </div> <div class="fix-body"> <div class="problem-box"> <div class="label">Problem</div> The notebook does not reference any published results on CASIA v2, making it impossible for an examiner to judge whether the results are competitive. </div> <div class="steps"> <div class="step"><p>After the results table (§10), add a markdown cell titled <strong>"Comparison with Published Baselines"</strong>.</p></div> <div class="step"><p>Use this template (fill in your actual results after Fix 2 is done):</p></div> </div> <table class="model-table"> <thead><tr><th>Method</th><th>Accuracy</th><th>F1</th><th>Notes</th></tr></thead> <tbody> <tr><td>Rao et al. (2016) — CNN on SRM features</td><td>82.2%</td><td>—</td><td>Single-branch</td></tr> <tr><td>Salloum et al. (2018) — FCN</td><td>89.3%</td><td>—</td><td>Pixel-level</td></tr> <tr><td><strong>Our M1 (RGB only)</strong></td><td><em>your result</em></td><td><em>your result</em></td><td>ResNet50</td></tr> <tr><td><strong>Our M2 (ELA only)</strong></td><td><em>your result</em></td><td><em>your result</em></td><td>Custom CNN</td></tr> <tr><td><strong>Our M3 (Fused)</strong></td><td><em>your result</em></td><td><em>your result</em></td><td>Dual-branch</td></tr> </tbody> </table> <div class="steps"> <div class="step"><p>Add 2–3 sentences commenting on whether M3 is competitive and why it may be higher or lower than the baselines.</p></div> </div> </div> </div> </section>
<!-- ═══════════════════════════ LOW ══════════════════════════════ --> <div class="section-header"> <span class="pill low">Low Priority</span> <hr> </div>
<!-- Fix 9 --> <section id="fix9"> <div class="fix-card low"> <div class="fix-header"> <div class="fix-num">9</div> <div class="fix-title">Align <code>get_gradcam()</code> in <code>app.py</code> with the Notebook</div> </div> <div class="fix-body"> <div class="problem-box"> <div class="label">Problem</div> The notebook's <code>get_gradcam()</code> uses a <code>model_type</code> parameter to pick the correct last conv layer per model variant. The <code>app.py</code> version only searches for <code>conv2d</code> named layers — if the model is updated it could silently pick the wrong layer. </div> <div class="steps"> <div class="step"><p>In <code>app.py</code>, replace the current <code>get_gradcam()</code> with the more robust version from the notebook.</p></div> <div class="step"><p>Since <code>app.py</code> only runs M3, hard-code the call as:</p></div> </div> <div class="code-wrap"> <div class="code-label">Python — Updated call in app.py</div> <pre>heatmap = <span class="fn">get_gradcam</span>(m3, input_data, model_type=<span class="st">'M3'</span>)</pre> </div> </div> </div> </section>
<!-- Fix 10 --> <section id="fix10"> <div class="fix-card low"> <div class="fix-header"> <div class="fix-num">10</div> <div class="fix-title">Document the Gradio → Streamlit Difference in README</div> </div> <div class="fix-body"> <div class="problem-box"> <div class="label">Problem</div> The notebook uses <strong>Gradio</strong> (Colab-native); the deployed app uses <strong>Streamlit</strong> (Hugging Face Spaces). This intentional difference is not explained anywhere and may confuse an examiner. </div> <div class="steps"> <div class="step"><p>Add the following section to <code>README.md</code>:</p></div> </div> <div class="code-wrap"> <div class="code-label">Markdown — README.md addition</div> <pre>## Development vs Deployment UI
The Colab notebook uses **Gradio** for its interactive demo because Gradioworks natively within Colab with a public share link.The deployed Hugging Face Space uses **Streamlit** because it is the SDKconfigured in the Space settings.Both interfaces implement identical inference logic.</pre> </div> </div> </div> </section>
<!-- ═════════════════════ Implementation Order ═══════════════════ --> <section id="order" style="margin-top:48px;"> <h2 style="font-size:20px;font-weight:800;margin-bottom:16px;color:#0f172a;">Recommended Implementation Order</h2> <p style="color:#64748b;font-size:14px;margin-bottom:20px;">Work through the fixes in this order to avoid rework — later fixes depend on earlier ones.</p> <div class="order-flow"> <div class="order-step">Fix 2a–b <span>Download CASIA v2</span></div> <span class="order-arrow">→</span> <div class="order-step">Fix 1 <span>run_training()</span></div> <span class="order-arrow">→</span> <div class="order-step">Fix 3 <span>Reorder notebook</span></div> <span class="order-arrow">→</span> <div class="order-step">Fix 2c–e <span>Retrain on real data</span></div> <span class="order-arrow">→</span> <div class="order-step">Fix 4 <span>Eval metrics</span></div> <span class="order-arrow">→</span> <div class="order-step">Fix 5 <span>Ablation write-up</span></div> <span class="order-arrow">→</span> <div class="order-step">Fix 6 <span>train.py parity</span></div> <span class="order-arrow">→</span> <div class="order-step">Fix 7 <span>Project report</span></div> <span class="order-arrow">→</span> <div class="order-step">Fix 8 <span>Literature</span></div> <span class="order-arrow">→</span> <div class="order-step">Fix 9 <span>Grad-CAM</span></div> <span class="order-arrow">→</span> <div class="order-step">Fix 10 <span>README</span></div> </div> </section>
<!-- ═════════════════════ Definition of Done ═════════════════════ --> <section id="done" style="margin-top:48px;"> <h2 style="font-size:20px;font-weight:800;margin-bottom:6px;color:#0f172a;">Definition of Done</h2> <p style="color:#64748b;font-size:14px;margin-bottom:20px;">Tick each item off as you complete it. Submission is ready only when all boxes are checked.</p> <ul class="checklist"> <li><input type="checkbox" id="c1"><label for="c1">Notebook runs end-to-end in Colab without errors (no missing functions)</label></li> <li><input type="checkbox" id="c2"><label for="c2">Notebook sections are numbered and ordered correctly (§1 through §10)</label></li> <li><input type="checkbox" id="c3"><label for="c3">Training uses real CASIA v2 data — not synthetic noise</label></li> <li><input type="checkbox" id="c4"><label for="c4">Accuracy is in a realistic range (75–92%) — <strong>not 100%</strong></label></li> <li><input type="checkbox" id="c5"><label for="c5">Class imbalance is handled via class weights in <code>model.fit()</code></label></li> <li><input type="checkbox" id="c6"><label for="c6">Evaluation section includes: confusion matrix, precision, recall, F1, ROC-AUC</label></li> <li><input type="checkbox" id="c7"><label for="c7">Ablation study table compares M1, M2, M3 across all metrics</label></li> <li><input type="checkbox" id="c8"><label for="c8">Literature comparison table present with at least two published baselines</label></li> <li><input type="checkbox" id="c9"><label for="c9"><code>train.py</code> trains all three models (M1, M2, M3)</label></li> <li><input type="checkbox" id="c10"><label for="c10"><code>M3_best.keras</code> in the repo was trained on real CASIA v2 data</label></li> <li><input type="checkbox" id="c11"><label for="c11"><code>Documents/</code> folder contains the project report</label></li> <li><input type="checkbox" id="c12"><label for="c12"><code>README.md</code> explains the Gradio vs Streamlit difference</label></li> <li><input type="checkbox" id="c13"><label for="c13">Hugging Face Space redeployed with the new model weights</label></li> </ul> </section>
</main>
</body></html>123version https://git-lfs.github.com/spec/v1oid sha256:39ffaa336055dc8cf27a970794c38afac258963d5d59016acde6d15b9386ab6bsize 34823123version https://git-lfs.github.com/spec/v1oid sha256:8a409f96d3131069ee9f2a5ccd09d8900506a768479a361278696317cc986854size 16882312345678gitgit-lfsffmpeglibsm6libxext6cmakersynclibgl112345678streamlit==1.35.0tensorflow==2.15.0opencv-python-headless==4.8.1.78pillow==10.0.0numpy==1.24.3scikit-learn==1.3.2matplotlib==3.8.0huggingface-hub==0.19.4123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172import osimport reimport ioimport randomimport numpy as npimport tensorflow as tfimport cv2from PIL import Image, ImageChops, ImageDrawfrom sklearn.model_selection import train_test_splitfrom tensorflow.keras import layers, models, applications
# ── Global configuration ──────────────────────────────────────────────────────SEED = 42IMG_SIZE = (224, 224)ELA_QUALITY = 90ELA_SCALE = 15BATCH_SIZE = 32EPOCHS = 5TARGET_DIR = "./casia_v2"
def set_reproducibility(seed=SEED): tf.random.set_seed(seed) np.random.seed(seed) random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed)
set_reproducibility()
def generate_robust_dataset(num_samples=120): if os.path.exists(TARGET_DIR): import shutil shutil.rmtree(TARGET_DIR) os.makedirs(TARGET_DIR)
print(f"Generating {num_samples} synthetic samples...") for i in range(num_samples): img_data = np.random.randint(100, 200, (256, 256, 3), dtype=np.uint8) img = Image.fromarray(img_data)
is_forged = i >= (num_samples // 2) if not is_forged: filename = f"Au_arc_000{i:02d}.jpg" else: draw = ImageDraw.Draw(img) draw.rectangle([50, 50, 150, 150], fill=(255, 0, 0)) filename = f"Tp_s_N_arc_000{i:02d}_00099_001.jpg"
img.save(os.path.join(TARGET_DIR, filename))
def compute_ela(image_path_or_pil, quality=ELA_QUALITY, scale=ELA_SCALE): if isinstance(image_path_or_pil, str): original = Image.open(image_path_or_pil).convert('RGB') else: original = image_path_or_pil.convert('RGB')
buf = io.BytesIO() original.save(buf, 'JPEG', quality=quality) buf.seek(0) compressed = Image.open(buf)
ela_image = ImageChops.difference(original, compressed) ela_image = ImageChops.multiply( ela_image, Image.new('RGB', ela_image.size, (scale, scale, scale)) ) return ela_image
class CASIAParser: @staticmethod def get_ids(filename): name = os.path.basename(filename) if name.startswith('Au_'): match = re.search(r'Au_[a-z]{3}_(\d+)', name) return [match.group(1)] if match else [] elif name.startswith('Tp_'): parts = name.split('_') return [parts[4], parts[5]] if len(parts) >= 6 else [] return []
def split_dataset(data_dir, train_ratio=0.8, val_ratio=0.1, test_ratio=0.1): all_images = [ os.path.join(data_dir, f) for f in os.listdir(data_dir) if f.lower().endswith(('.jpg', '.jpeg', '.png', '.tif')) ] unique_ids = sorted({i for p in all_images for i in CASIAParser.get_ids(p)}) if not unique_ids: unique_ids = [str(i) for i in range(len(all_images))] tr_ids, temp = train_test_split(unique_ids, train_size=train_ratio, random_state=SEED) v_ids, _ = train_test_split(temp, train_size=val_ratio / (val_ratio + test_ratio), random_state=SEED) tr_ids, v_ids = set(tr_ids), set(v_ids) splits = {'train': [], 'val': [], 'test': []} for p in all_images: ids = CASIAParser.get_ids(p) if not ids: splits['train'].append(p) if random.random() < 0.8 else splits['test'].append(p) continue if any(i in tr_ids for i in ids): splits['train'].append(p) elif any(i in v_ids for i in ids): splits['val'].append(p) else: splits['test'].append(p) return splits
def preload_images(paths, img_size=IMG_SIZE): rgb_list, ela_list, label_list = [], [], [] for p in paths: pil_img = Image.open(p).convert('RGB') rgb_list.append(np.array(pil_img.resize(img_size), dtype=np.float32)) ela_list.append(np.array(compute_ela(pil_img).resize(img_size), dtype=np.float32)) label_list.append(1 if os.path.basename(p).startswith('Tp_') else 0) return np.array(rgb_list), np.array(ela_list), np.array(label_list)
def make_dataset(rgb_arr, ela_arr, labels, batch_size=BATCH_SIZE, shuffle=False, repeat=True): ds = tf.data.Dataset.from_tensor_slices(((rgb_arr, ela_arr), labels)) if shuffle: ds = ds.shuffle(buffer_size=len(labels), seed=SEED, reshuffle_each_iteration=True) ds = ds.batch(batch_size, drop_remainder=False) if repeat: ds = ds.repeat() return ds.prefetch(tf.data.AUTOTUNE)
def get_rgb_branch(): base = applications.ResNet50( include_top=False, weights='imagenet', input_shape=(*IMG_SIZE, 3) ) base.trainable = False inputs = layers.Input(shape=(*IMG_SIZE, 3)) x = applications.resnet50.preprocess_input(inputs) x = base(x, training=False) return inputs, layers.GlobalAveragePooling2D()(x)
def get_ela_branch(): inputs = layers.Input(shape=(*IMG_SIZE, 3)) x = layers.Rescaling(1. / 255)(inputs) for filters in [32, 64, 128]: x = layers.Conv2D(filters, (3, 3), activation='relu', padding='same')(x) x = layers.BatchNormalization()(x) x = layers.MaxPooling2D((2, 2))(x) return inputs, layers.GlobalAveragePooling2D()(x)
def build_model(): rgb_in, rgb_f = get_rgb_branch() ela_in, ela_f = get_ela_branch() fused = layers.Concatenate()([rgb_f, ela_f]) out = layers.Dense(1, activation='sigmoid')( layers.Dropout(0.5)(layers.Dense(256, activation='relu')(fused)) ) return models.Model(inputs=[rgb_in, ela_in], outputs=out)
if __name__ == "__main__": generate_robust_dataset(120) splits = split_dataset(TARGET_DIR) train_rgb, train_ela, train_labels = preload_images(splits['train']) val_rgb, val_ela, val_labels = preload_images(splits['val'])
train_ds = make_dataset(train_rgb, train_ela, train_labels, shuffle=True) val_ds = make_dataset(val_rgb, val_ela, val_labels, shuffle=False)
model = build_model() model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
steps_per_epoch = max(1, int(np.ceil(len(train_labels) / BATCH_SIZE))) validation_steps = max(1, int(np.ceil(len(val_labels) / BATCH_SIZE)))
model.fit( train_ds, validation_data=val_ds, epochs=EPOCHS, steps_per_epoch=steps_per_epoch, validation_steps=validation_steps, verbose=1, ) model.save('M3_best.keras') print("Model saved as M3_best.keras").gitattributesAdded+3
.gitignoreAdded+43
CLAUDE.mdAdded+55
README.mdAdded+33
app.pyAdded+188
documents/Project_Report_Digital_Image_Forgery_Detector.docxAdded+3
documents/REMEDIATION_PLAN.mdAdded+450
documents/remediation_plan.htmlAdded+1084
notebooks/Image_Forgery_Detection_Colab_1.ipynbAdded+3
notebooks/Image_Forgery_Training_Notebook.ipynbAdded+3
packages.txtAdded+8
requirements.txtAdded+8
train.pyAdded+172