Update app.py
Browse files
app.py
CHANGED
|
@@ -2,36 +2,39 @@ import gradio as gr
|
|
| 2 |
import torch
|
| 3 |
import torchvision.transforms as transforms
|
| 4 |
from torchvision import models
|
|
|
|
| 5 |
from PIL import Image
|
| 6 |
import matplotlib.pyplot as plt
|
| 7 |
import numpy as np
|
| 8 |
import cv2
|
| 9 |
-
import pandas as pd
|
| 10 |
-
from datetime import datetime
|
| 11 |
from gtts import gTTS
|
| 12 |
import wikipedia
|
|
|
|
|
|
|
| 13 |
import os
|
| 14 |
|
| 15 |
# ===============================
|
| 16 |
-
# LOAD MODEL
|
| 17 |
# ===============================
|
| 18 |
-
|
|
|
|
| 19 |
model.eval()
|
| 20 |
|
| 21 |
# ===============================
|
| 22 |
# LABELS
|
| 23 |
# ===============================
|
| 24 |
-
import json, urllib.request
|
| 25 |
url = "https://s3.amazonaws.com/deep-learning-models/image-models/imagenet_class_index.json"
|
| 26 |
-
|
|
|
|
| 27 |
labels = [class_idx[str(k)][1] for k in range(len(class_idx))]
|
| 28 |
|
| 29 |
# ===============================
|
| 30 |
# TRANSFORM
|
| 31 |
# ===============================
|
| 32 |
transform = transforms.Compose([
|
| 33 |
-
transforms.Resize((224,224)),
|
| 34 |
-
transforms.ToTensor()
|
|
|
|
| 35 |
])
|
| 36 |
|
| 37 |
# ===============================
|
|
@@ -39,135 +42,176 @@ transform = transforms.Compose([
|
|
| 39 |
# ===============================
|
| 40 |
def get_wiki_info(query):
|
| 41 |
try:
|
|
|
|
| 42 |
return wikipedia.summary(query, sentences=2)
|
| 43 |
except:
|
| 44 |
-
return "No
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
|
| 46 |
# ===============================
|
| 47 |
# GRAD-CAM
|
| 48 |
# ===============================
|
| 49 |
def generate_gradcam(image):
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
features = []
|
| 54 |
-
|
|
|
|
|
|
|
| 55 |
features.append(output)
|
| 56 |
|
| 57 |
-
|
|
|
|
| 58 |
|
| 59 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
pred_class = output.argmax()
|
| 61 |
|
|
|
|
| 62 |
model.zero_grad()
|
| 63 |
output[0, pred_class].backward()
|
| 64 |
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
|
| 71 |
-
for i in
|
| 72 |
-
fmap[i,:,:]
|
| 73 |
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
|
| 78 |
-
|
| 79 |
-
heatmap = np.uint8(255 *
|
| 80 |
heatmap = cv2.applyColorMap(heatmap, cv2.COLORMAP_JET)
|
| 81 |
|
| 82 |
-
img_np = np.array(image
|
| 83 |
superimposed = heatmap * 0.4 + img_np
|
| 84 |
|
| 85 |
-
|
|
|
|
|
|
|
| 86 |
|
| 87 |
return superimposed.astype(np.uint8)
|
| 88 |
|
| 89 |
# ===============================
|
| 90 |
# PREDICT
|
| 91 |
# ===============================
|
| 92 |
-
def predict(image):
|
| 93 |
-
|
|
|
|
|
|
|
| 94 |
|
| 95 |
with torch.no_grad():
|
| 96 |
-
outputs = model(
|
| 97 |
probs = torch.nn.functional.softmax(outputs[0], dim=0)
|
| 98 |
|
| 99 |
top3 = torch.topk(probs, 3)
|
| 100 |
-
|
| 101 |
results = []
|
| 102 |
for i in range(3):
|
| 103 |
label = labels[top3.indices[i]]
|
| 104 |
-
conf = float(top3.values[i])*100
|
| 105 |
results.append((label, conf))
|
| 106 |
|
| 107 |
top_label = results[0][0]
|
| 108 |
-
|
| 109 |
-
# Wikipedia
|
| 110 |
wiki = get_wiki_info(top_label)
|
| 111 |
-
|
| 112 |
-
# Grad-CAM
|
|
|
|
| 113 |
heatmap = generate_gradcam(image)
|
| 114 |
|
| 115 |
# Graph
|
| 116 |
names = [r[0] for r in results]
|
| 117 |
values = [r[1] for r in results]
|
| 118 |
-
plt.figure()
|
| 119 |
-
plt.bar(names, values)
|
|
|
|
|
|
|
| 120 |
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
tts = gTTS(text=text)
|
| 124 |
-
tts.save("voice.mp3")
|
| 125 |
|
| 126 |
-
return
|
| 127 |
|
| 128 |
# ===============================
|
| 129 |
-
# REAL-TIME
|
| 130 |
# ===============================
|
| 131 |
def webcam_predict(frame):
|
|
|
|
| 132 |
image = Image.fromarray(frame)
|
| 133 |
-
|
| 134 |
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
(0,255,0), 2)
|
| 139 |
|
|
|
|
|
|
|
|
|
|
| 140 |
return frame
|
| 141 |
|
| 142 |
# ===============================
|
| 143 |
-
# PREMIUM UI
|
| 144 |
# ===============================
|
| 145 |
-
with gr.Blocks(theme=
|
| 146 |
-
|
| 147 |
gr.Markdown("# 🔥 Next-Gen AI Image Recognition System")
|
| 148 |
-
gr.Markdown("###
|
| 149 |
-
|
| 150 |
-
with gr.
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 165 |
)
|
| 166 |
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
webcam_output = gr.Image()
|
| 170 |
-
|
| 171 |
-
webcam.stream(webcam_predict, inputs=webcam, outputs=webcam_output)
|
| 172 |
-
|
| 173 |
-
demo.launch()
|
|
|
|
| 2 |
import torch
|
| 3 |
import torchvision.transforms as transforms
|
| 4 |
from torchvision import models
|
| 5 |
+
from torchvision.models import ResNet18_Weights
|
| 6 |
from PIL import Image
|
| 7 |
import matplotlib.pyplot as plt
|
| 8 |
import numpy as np
|
| 9 |
import cv2
|
|
|
|
|
|
|
| 10 |
from gtts import gTTS
|
| 11 |
import wikipedia
|
| 12 |
+
import json
|
| 13 |
+
import urllib.request
|
| 14 |
import os
|
| 15 |
|
| 16 |
# ===============================
|
| 17 |
+
# LOAD MODEL (Updated for Torchvision 0.13+)
|
| 18 |
# ===============================
|
| 19 |
+
weights = ResNet18_Weights.DEFAULT
|
| 20 |
+
model = models.resnet18(weights=weights)
|
| 21 |
model.eval()
|
| 22 |
|
| 23 |
# ===============================
|
| 24 |
# LABELS
|
| 25 |
# ===============================
|
|
|
|
| 26 |
url = "https://s3.amazonaws.com/deep-learning-models/image-models/imagenet_class_index.json"
|
| 27 |
+
with urllib.request.urlopen(url) as response:
|
| 28 |
+
class_idx = json.load(response)
|
| 29 |
labels = [class_idx[str(k)][1] for k in range(len(class_idx))]
|
| 30 |
|
| 31 |
# ===============================
|
| 32 |
# TRANSFORM
|
| 33 |
# ===============================
|
| 34 |
transform = transforms.Compose([
|
| 35 |
+
transforms.Resize((224, 224)),
|
| 36 |
+
transforms.ToTensor(),
|
| 37 |
+
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
|
| 38 |
])
|
| 39 |
|
| 40 |
# ===============================
|
|
|
|
| 42 |
# ===============================
|
| 43 |
def get_wiki_info(query):
|
| 44 |
try:
|
| 45 |
+
# Wikipedia sometimes needs specific search terms
|
| 46 |
return wikipedia.summary(query, sentences=2)
|
| 47 |
except:
|
| 48 |
+
return "No additional detailed information available on Wikipedia."
|
| 49 |
+
|
| 50 |
+
# ===============================
|
| 51 |
+
# NATURAL VOICE
|
| 52 |
+
# ===============================
|
| 53 |
+
def generate_speech(label, wiki_info, lang):
|
| 54 |
+
if lang == "Telugu":
|
| 55 |
+
text = f"ఈ చిత్రం {label} ను చూపిస్తుంది. {wiki_info}"
|
| 56 |
+
tts = gTTS(text=text, lang='te')
|
| 57 |
+
elif lang == "Hindi":
|
| 58 |
+
text = f"यह चित्र {label} दिखाता है। {wiki_info}"
|
| 59 |
+
tts = gTTS(text=text, lang='hi')
|
| 60 |
+
else:
|
| 61 |
+
text = f"This image appears to show a {label}. {wiki_info}"
|
| 62 |
+
tts = gTTS(text=text, lang='en')
|
| 63 |
+
|
| 64 |
+
audio_file = "voice.mp3"
|
| 65 |
+
tts.save(audio_file)
|
| 66 |
+
return audio_file
|
| 67 |
|
| 68 |
# ===============================
|
| 69 |
# GRAD-CAM
|
| 70 |
# ===============================
|
| 71 |
def generate_gradcam(image):
|
| 72 |
+
# Preprocess
|
| 73 |
+
img_tensor = transform(image).unsqueeze(0)
|
| 74 |
+
|
| 75 |
features = []
|
| 76 |
+
gradients = []
|
| 77 |
+
|
| 78 |
+
def forward_hook(module, input, output):
|
| 79 |
features.append(output)
|
| 80 |
|
| 81 |
+
def backward_hook(module, grad_in, grad_out):
|
| 82 |
+
gradients.append(grad_out[0])
|
| 83 |
|
| 84 |
+
# Register hooks on the last convolutional layer
|
| 85 |
+
handle_f = model.layer4.register_forward_hook(forward_hook)
|
| 86 |
+
handle_b = model.layer4.register_full_backward_hook(backward_hook)
|
| 87 |
+
|
| 88 |
+
# Forward pass
|
| 89 |
+
output = model(img_tensor)
|
| 90 |
pred_class = output.argmax()
|
| 91 |
|
| 92 |
+
# Backward pass
|
| 93 |
model.zero_grad()
|
| 94 |
output[0, pred_class].backward()
|
| 95 |
|
| 96 |
+
# Process CAM
|
| 97 |
+
fmap = features[0].detach()
|
| 98 |
+
grad = gradients[0].detach()
|
| 99 |
+
weights_cam = torch.mean(grad, dim=[2, 3])[0]
|
| 100 |
+
cam = torch.zeros(fmap.shape[2:], dtype=torch.float32)
|
| 101 |
|
| 102 |
+
for i, w in enumerate(weights_cam):
|
| 103 |
+
cam += w * fmap[0, i, :, :]
|
| 104 |
|
| 105 |
+
cam = np.maximum(cam.numpy(), 0)
|
| 106 |
+
if cam.max() > 0:
|
| 107 |
+
cam = cam / cam.max()
|
| 108 |
|
| 109 |
+
cam = cv2.resize(cam, (image.size[0], image.size[1]))
|
| 110 |
+
heatmap = np.uint8(255 * cam)
|
| 111 |
heatmap = cv2.applyColorMap(heatmap, cv2.COLORMAP_JET)
|
| 112 |
|
| 113 |
+
img_np = np.array(image)
|
| 114 |
superimposed = heatmap * 0.4 + img_np
|
| 115 |
|
| 116 |
+
# Cleanup hooks
|
| 117 |
+
handle_f.remove()
|
| 118 |
+
handle_b.remove()
|
| 119 |
|
| 120 |
return superimposed.astype(np.uint8)
|
| 121 |
|
| 122 |
# ===============================
|
| 123 |
# PREDICT
|
| 124 |
# ===============================
|
| 125 |
+
def predict(image, lang):
|
| 126 |
+
if image is None: return None, None, None, None, None
|
| 127 |
+
|
| 128 |
+
img_tensor = transform(image).unsqueeze(0)
|
| 129 |
|
| 130 |
with torch.no_grad():
|
| 131 |
+
outputs = model(img_tensor)
|
| 132 |
probs = torch.nn.functional.softmax(outputs[0], dim=0)
|
| 133 |
|
| 134 |
top3 = torch.topk(probs, 3)
|
|
|
|
| 135 |
results = []
|
| 136 |
for i in range(3):
|
| 137 |
label = labels[top3.indices[i]]
|
| 138 |
+
conf = float(top3.values[i]) * 100
|
| 139 |
results.append((label, conf))
|
| 140 |
|
| 141 |
top_label = results[0][0]
|
|
|
|
|
|
|
| 142 |
wiki = get_wiki_info(top_label)
|
| 143 |
+
|
| 144 |
+
# Temporarily enable grads for Grad-CAM
|
| 145 |
+
model.train(False)
|
| 146 |
heatmap = generate_gradcam(image)
|
| 147 |
|
| 148 |
# Graph
|
| 149 |
names = [r[0] for r in results]
|
| 150 |
values = [r[1] for r in results]
|
| 151 |
+
fig = plt.figure(figsize=(8, 4))
|
| 152 |
+
plt.bar(names, values, color='skyblue')
|
| 153 |
+
plt.title("Top 3 Predictions")
|
| 154 |
+
plt.ylabel("Confidence %")
|
| 155 |
|
| 156 |
+
audio = generate_speech(top_label, wiki, lang)
|
| 157 |
+
text_output = "\n".join([f"{r[0]} : {r[1]:.2f}%" for r in results])
|
|
|
|
|
|
|
| 158 |
|
| 159 |
+
return text_output, wiki, heatmap, fig, audio
|
| 160 |
|
| 161 |
# ===============================
|
| 162 |
+
# REAL-TIME WEBCAM
|
| 163 |
# ===============================
|
| 164 |
def webcam_predict(frame):
|
| 165 |
+
if frame is None: return None
|
| 166 |
image = Image.fromarray(frame)
|
| 167 |
+
img_tensor = transform(image).unsqueeze(0)
|
| 168 |
|
| 169 |
+
with torch.no_grad():
|
| 170 |
+
outputs = model(img_tensor)
|
| 171 |
+
probs = torch.nn.functional.softmax(outputs[0], dim=0)
|
|
|
|
| 172 |
|
| 173 |
+
label = labels[probs.argmax()]
|
| 174 |
+
cv2.putText(frame, f"Detected: {label}", (20, 50),
|
| 175 |
+
cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
|
| 176 |
return frame
|
| 177 |
|
| 178 |
# ===============================
|
| 179 |
+
# PREMIUM UI (Gradio 6.0 Compatibility)
|
| 180 |
# ===============================
|
| 181 |
+
with gr.Blocks(theme="soft") as demo:
|
|
|
|
| 182 |
gr.Markdown("# 🔥 Next-Gen AI Image Recognition System")
|
| 183 |
+
gr.Markdown("### Grad-CAM + Real-Time Detection + Wikipedia + Natural Voice")
|
| 184 |
+
|
| 185 |
+
with gr.Tab("Static Analysis"):
|
| 186 |
+
with gr.Row():
|
| 187 |
+
image_input = gr.Image(type="pil", label="Upload Image", sources=["upload", "clipboard"])
|
| 188 |
+
heatmap_output = gr.Image(label="Explainable AI (Grad-CAM)")
|
| 189 |
+
|
| 190 |
+
lang = gr.Dropdown(["English", "Telugu", "Hindi"], label="Voice Language", value="English")
|
| 191 |
+
btn = gr.Button("🔍 Analyze Image", variant="primary")
|
| 192 |
+
|
| 193 |
+
with gr.Row():
|
| 194 |
+
output_text = gr.Textbox(label="Predictions")
|
| 195 |
+
output_wiki = gr.Textbox(label="Wikipedia Info")
|
| 196 |
+
|
| 197 |
+
with gr.Row():
|
| 198 |
+
output_graph = gr.Plot(label="Confidence Graph")
|
| 199 |
+
output_audio = gr.Audio(label="Voice Explanation", autoplay=True)
|
| 200 |
+
|
| 201 |
+
with gr.Tab("Real-Time Webcam"):
|
| 202 |
+
gr.Markdown("## 🎥 Live Stream Detection")
|
| 203 |
+
# Gradio 6.x Streaming Setup
|
| 204 |
+
with gr.Row():
|
| 205 |
+
webcam_input = gr.Image(sources=["webcam"], streaming=True, label="Webcam Input")
|
| 206 |
+
webcam_output = gr.Image(label="Processed Feed")
|
| 207 |
+
|
| 208 |
+
webcam_input.stream(webcam_predict, inputs=[webcam_input], outputs=[webcam_output])
|
| 209 |
+
|
| 210 |
+
btn.click(
|
| 211 |
+
predict,
|
| 212 |
+
inputs=[image_input, lang],
|
| 213 |
+
outputs=[output_text, output_wiki, heatmap_output, output_graph, output_audio]
|
| 214 |
)
|
| 215 |
|
| 216 |
+
if __name__ == "__main__":
|
| 217 |
+
demo.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|