priyansh-nagar commited on
Commit
7b238e7
·
verified ·
1 Parent(s): 0642643
Files changed (7) hide show
  1. README.md +40 -17
  2. app.py +45 -0
  3. feedback/db.py +24 -0
  4. model/heatmap.py +9 -0
  5. model/predict.py +27 -0
  6. requirements.txt +5 -3
  7. train/retrain.py +36 -0
README.md CHANGED
@@ -1,20 +1,43 @@
1
- ---
2
- title: DeepTrust
3
- emoji: 🚀
4
- colorFrom: red
5
- colorTo: red
6
- sdk: docker
7
- app_port: 8501
8
- tags:
9
- - streamlit
10
- pinned: false
11
- short_description: Streamlit template space
12
- license: mit
13
- ---
14
 
15
- # Welcome to Streamlit!
 
 
 
16
 
17
- Edit `/src/streamlit_app.py` to customize this app to your heart's desire. :heart:
 
 
 
 
 
18
 
19
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
20
- forums](https://discuss.streamlit.io).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🛡️ DeepTrust – Explainable AI Deepfake Detection
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
+ ## Overview
4
+ DeepTrust is an explainable AI system for detecting AI-generated images.
5
+ It focuses on accuracy, transparency, and long-term learning using
6
+ human feedback.
7
 
8
+ ## Why DeepTrust?
9
+ - Uses verified research-grade pretrained models
10
+ - No black-box APIs
11
+ - Visual explanations (heatmaps)
12
+ - Trust Score for user clarity
13
+ - Designed for long-term deployment
14
 
15
+ ## How It Works
16
+ 1. Upload an image
17
+ 2. Pretrained deepfake model analyzes artifacts
18
+ 3. Trust Score (0–100) is generated
19
+ 4. Heatmap shows suspicious regions
20
+ 5. User feedback improves the model
21
+
22
+ ## Model Loading (Important)
23
+ DeepTrust uses Torch Hub to automatically load a verified pretrained
24
+ deepfake detection model on first run.
25
+ - No manual model download required
26
+ - Model is cached locally after first use
27
+ - Fully legal and reproducible
28
+
29
+ ## Tech Stack
30
+ - Python
31
+ - Streamlit
32
+ - PyTorch
33
+ - EfficientNet
34
+ - SQLite
35
+
36
+ ## Future Scope
37
+ - Video deepfake detection
38
+ - Face-level analysis
39
+ - Browser extension
40
+
41
+ ## Disclaimer
42
+ DeepTrust is a decision-support system and should not be used as the sole
43
+ authority for forensic conclusions.
app.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st, uuid, os, shutil
2
+ from PIL import Image
3
+ from model.predict import predict
4
+ from model.heatmap import cam_heatmap
5
+ from feedback.db import init_db, save
6
+
7
+ init_db()
8
+ st.set_page_config("DeepTrust", "🛡️")
9
+ st.title("🛡️ DeepTrust – AI Image Deepfake Detector")
10
+ st.caption("Building trust in digital media using explainable AI")
11
+
12
+ file = st.file_uploader("Upload an image", ["jpg","png","jpeg"])
13
+
14
+ if file:
15
+ img = Image.open(file).convert("RGB")
16
+ st.image(img, use_container_width=True)
17
+
18
+ label, conf, trust, tensor, model = predict(img)
19
+
20
+ st.metric("Trust Score", f"{trust}/100")
21
+ st.progress(trust/100)
22
+
23
+ result = "AI-Generated ❌" if label else "Real Image ✅"
24
+ st.subheader(result)
25
+
26
+ os.makedirs("data/uploads", exist_ok=True)
27
+ path = f"data/uploads/{uuid.uuid4()}.jpg"
28
+ img.save(path)
29
+
30
+ if st.checkbox("Show explanation"):
31
+ heat = cam_heatmap(model, tensor, img)
32
+ st.image(heat, caption="Model Attention Areas")
33
+
34
+ col1, col2 = st.columns(2)
35
+ if col1.button("Correct"):
36
+ save(path, label, label)
37
+ st.success("Feedback saved")
38
+
39
+ if col2.button("Wrong"):
40
+ correct = 0 if label else 1
41
+ save(path, label, correct)
42
+ target = "fake" if correct else "real"
43
+ os.makedirs(f"data/labeled/{target}", exist_ok=True)
44
+ shutil.copy(path, f"data/labeled/{target}/")
45
+ st.warning("Saved for retraining")
feedback/db.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sqlite3, os
2
+ os.makedirs("feedback", exist_ok=True)
3
+
4
+ def init_db():
5
+ conn = sqlite3.connect("feedback/feedback.db")
6
+ c = conn.cursor()
7
+ c.execute("""
8
+ CREATE TABLE IF NOT EXISTS feedback(
9
+ id INTEGER PRIMARY KEY,
10
+ image TEXT,
11
+ predicted INTEGER,
12
+ correct INTEGER
13
+ )
14
+ """)
15
+ conn.commit()
16
+ conn.close()
17
+
18
+ def save(image, predicted, correct):
19
+ conn = sqlite3.connect("feedback/feedback.db")
20
+ c = conn.cursor()
21
+ c.execute("INSERT INTO feedback VALUES(NULL,?,?,?)",
22
+ (image, predicted, correct))
23
+ conn.commit()
24
+ conn.close()
model/heatmap.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from pytorch_grad_cam import GradCAM
3
+ from pytorch_grad_cam.utils.image import show_cam_on_image
4
+
5
+ def cam_heatmap(model, tensor, image):
6
+ cam = GradCAM(model=model, target_layers=[model.blocks[-1]])
7
+ grayscale = cam(input_tensor=tensor)[0]
8
+ img = np.array(image).astype(float)/255
9
+ return show_cam_on_image(img, grayscale, use_rgb=True)
model/predict.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torchvision import transforms
3
+
4
+ device = "cuda" if torch.cuda.is_available() else "cpu"
5
+
6
+ model = torch.hub.load(
7
+ "selimsef/dfdc_deepfake_challenge",
8
+ "efficientnet_b0",
9
+ pretrained=True
10
+ ).to(device).eval()
11
+
12
+ transform = transforms.Compose([
13
+ transforms.Resize((224,224)),
14
+ transforms.ToTensor(),
15
+ transforms.Normalize([0.485,0.456,0.406],
16
+ [0.229,0.224,0.225])
17
+ ])
18
+
19
+ def predict(image):
20
+ tensor = transform(image).unsqueeze(0).to(device)
21
+ with torch.no_grad():
22
+ out = model(tensor)
23
+ prob = torch.softmax(out, 1)
24
+ conf, pred = torch.max(prob, 1)
25
+
26
+ trust_score = int(conf.item()*100 if pred.item()==0 else (1-conf.item())*100)
27
+ return pred.item(), conf.item(), trust_score, tensor, model
requirements.txt CHANGED
@@ -1,3 +1,5 @@
1
- altair
2
- pandas
3
- streamlit
 
 
 
1
+ torch==2.0.1
2
+ torchvision==0.15.2
3
+ pytorch-grad-cam
4
+ opencv-python-headless
5
+ streamlit==1.31.0
train/retrain.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torchvision import datasets, transforms
3
+ from torch.utils.data import DataLoader
4
+ import torch.nn as nn, torch.optim as optim
5
+
6
+ device = "cuda" if torch.cuda.is_available() else "cpu"
7
+
8
+ transform = transforms.Compose([
9
+ transforms.Resize((224,224)),
10
+ transforms.ToTensor(),
11
+ transforms.Normalize([0.485,0.456,0.406],
12
+ [0.229,0.224,0.225])
13
+ ])
14
+
15
+ dataset = datasets.ImageFolder("data/labeled", transform)
16
+ loader = DataLoader(dataset, batch_size=8, shuffle=True)
17
+
18
+ model = torch.hub.load(
19
+ "selimsef/dfdc_deepfake_challenge",
20
+ "efficientnet_b0",
21
+ pretrained=True
22
+ ).to(device)
23
+
24
+ loss_fn = nn.CrossEntropyLoss()
25
+ opt = optim.Adam(model.parameters(), lr=1e-4)
26
+
27
+ for epoch in range(3):
28
+ for x,y in loader:
29
+ x,y = x.to(device), y.to(device)
30
+ opt.zero_grad()
31
+ loss = loss_fn(model(x), y)
32
+ loss.backward()
33
+ opt.step()
34
+
35
+ torch.save(model.state_dict(), "deeptrust_finetuned.pth")
36
+ print("Model retrained and saved")