strelizi commited on
Commit
de923f4
·
verified ·
1 Parent(s): 8f10f73

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +196 -839
app.py CHANGED
@@ -1,4 +1,7 @@
1
-
 
 
 
2
 
3
  import torch
4
  import torch.nn as nn
@@ -9,928 +12,282 @@ from captum.attr import LayerGradCam
9
  import numpy as np
10
  import matplotlib.pyplot as plt
11
  from io import BytesIO
12
- import json, urllib.request
13
  from torch.nn.functional import interpolate
14
  import warnings
15
  warnings.filterwarnings('ignore')
16
 
 
 
 
17
 
18
  DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
19
- print(f"Running on: {DEVICE}")
20
-
21
 
22
  @torch.no_grad()
23
  def load_model_and_labels():
24
- print("Loading ResNet50...")
25
  model = models.resnet50(weights='IMAGENET1K_V2')
26
  model.eval()
27
  model = model.to(DEVICE)
28
-
29
- print("Loading ImageNet labels...")
30
- url = "https://raw.githubusercontent.com/anishathalye/imagenet-simple-labels/master/imagenet-simple-labels.json"
31
- labels = json.loads(urllib.request.urlopen(url).read())
32
- print(f"Model ready – {len(labels)} classes")
 
33
  return model, labels
34
 
35
  model, IMAGENET_LABELS = load_model_and_labels()
36
 
37
-
38
  target_layer = model.layer4[-1]
39
  gradcam = LayerGradCam(model, target_layer)
40
 
 
41
  transform = transforms.Compose([
42
  transforms.Resize((224, 224)),
43
  transforms.ToTensor(),
44
- transforms.Normalize(mean=[0.485, 0.456, 0.406],
45
- std=[0.229, 0.224, 0.225])
46
  ])
47
 
 
 
 
48
 
49
  def predict_and_explain(image):
50
  if image is None:
51
- return "Please upload an image", None
52
 
53
  try:
54
-
55
  img_tensor = transform(image).unsqueeze(0).to(DEVICE)
56
 
57
-
58
  with torch.no_grad():
59
  output = model(img_tensor)
60
- probabilities = torch.softmax(output, dim=1)
61
- top5_prob, top5_idx = torch.topk(probabilities, 5)
 
 
 
62
 
63
- pred_class = top5_idx[0][0].item()
64
- confidence = top5_prob[0][0].item()
65
 
66
-
67
  attributions = gradcam.attribute(img_tensor, target=pred_class)
68
  attr_resized = interpolate(attributions, size=(224, 224), mode='bilinear', align_corners=False)
69
  attr_np = attr_resized.squeeze().cpu().detach().numpy()
70
  attr_np = (attr_np - attr_np.min()) / (attr_np.max() - attr_np.min() + 1e-8)
71
 
72
-
73
- fig, axes = plt.subplots(1, 3, figsize=(15, 4.5))
74
  fig.patch.set_facecolor('#0a0a0a')
75
- plt.subplots_adjust(wspace=0.12, left=0.02, right=0.98, top=0.92, bottom=0.08)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
 
 
 
 
77
 
78
  axes[0].imshow(image)
79
- axes[0].set_title("Original", fontsize=13, fontweight='600', color='#e0e0e0', pad=12)
80
  axes[0].axis('off')
81
-
82
 
83
- im = axes[1].imshow(attr_np, cmap='viridis')
84
- axes[1].set_title("Grad-CAM", fontsize=13, fontweight='600', color='#e0e0e0', pad=12)
85
  axes[1].axis('off')
86
- cbar = plt.colorbar(im, ax=axes[1], fraction=0.046, pad=0.04)
87
- cbar.ax.tick_params(labelsize=9, colors='#a0a0a0')
88
- cbar.set_label('Focus', rotation=270, labelpad=15, color='#a0a0a0', fontsize=10)
89
-
90
-
91
  axes[2].imshow(image)
92
- axes[2].imshow(attr_np, cmap='viridis', alpha=0.5)
93
- axes[2].set_title("AI Focus", fontsize=13, fontweight='600', color='#e0e0e0', pad=12)
 
94
  axes[2].axis('off')
 
 
 
 
 
 
 
 
95
 
96
- buf = BytesIO()
97
- plt.savefig(buf, format='png', dpi=100, bbox_inches='tight', facecolor='#0a0a0a')
98
- buf.seek(0)
99
- result_image = Image.open(buf)
100
- plt.close(fig)
101
-
102
-
103
- if confidence > 0.8:
104
- badge = "high"
105
- badge_text = "High Confidence"
106
- badge_icon = "🎯"
107
- elif confidence > 0.5:
108
- badge = "medium"
109
- badge_text = "Medium Confidence"
110
- badge_icon = "⚡"
111
- else:
112
- badge = "low"
113
- badge_text = "Low Confidence"
114
- badge_icon = "⚠️"
115
 
116
-
117
  top5_html = "<div class='top5-grid'>"
118
  icons = ["🥇", "🥈", "🥉", "4️⃣", "5️⃣"]
119
- for i, (prob, idx) in enumerate(zip(top5_prob[0], top5_idx[0])):
120
  pct = prob.item() * 100
121
  top5_html += f"""
122
  <div class='top5-row'>
123
  <span class='rank'>{icons[i]}</span>
124
- <span class='label'>{IMAGENET_LABELS[idx.item()].title()}</span>
125
  <div class='bar-wrap'><div class='bar' style='width:{pct}%'></div></div>
126
- <span class='pct'>{pct:.1f}%</span>
127
- </div>
128
- """
129
  top5_html += "</div>"
130
 
131
-
132
  prediction_text = f"""
133
  <div class="result-card">
134
  <div class="pred-header">
135
- <h2 class="pred-label">{IMAGENET_LABELS[pred_class].title()}</h2>
136
  <div class="badge badge-{badge}">{badge_icon} {badge_text}</div>
137
  </div>
138
- <div class="conf-score">{confidence*100:.1f}%</div>
139
  <div class="divider"></div>
140
  {top5_html}
141
- </div>
142
- """
143
- return prediction_text, result_image
144
 
145
  except Exception as e:
146
- return f"<div class='error-msg'>⚠️ Error: {str(e)}</div>", None
147
 
 
 
 
148
 
149
  custom_css = """
150
  @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap');
151
-
152
- * {
153
- box-sizing: border-box;
154
- margin: 0;
155
- padding: 0;
156
- }
157
-
158
- body, .gradio-container {
159
- margin: 0 !important;
160
- padding: 0 !important;
161
- width: 100vw !important;
162
- min-height: 100vh !important;
163
- max-width: 100vw !important;
164
- background: linear-gradient(135deg, #0a0a0a 0%, #1a1a1a 50%, #0f0f0f 100%) !important;
165
- font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif !important;
166
- color: #e0e0e0 !important;
167
- overflow-x: hidden !important;
168
- }
169
-
170
  .gradio-container { padding: 0 !important; }
171
-
172
- body::before {
173
- content: '';
174
- position: fixed;
175
- top: 0;
176
- left: 0;
177
- width: 100%;
178
- height: 100%;
179
- opacity: 0.03;
180
- pointer-events: none;
181
- background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 400 400' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noiseFilter'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' /%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noiseFilter)' /%3E%3C/svg%3E");
182
- z-index: 1;
183
- }
184
-
185
- .main-wrapper {
186
- padding: 1.5rem;
187
- max-width: 1920px;
188
- margin: 0 auto;
189
- position: relative;
190
- z-index: 2;
191
- }
192
-
193
- .hero-header {
194
- text-align: center;
195
- padding: 2rem 1rem 1.5rem;
196
- margin-bottom: 1.5rem;
197
- position: relative;
198
- }
199
-
200
- .hero-header h1 {
201
- font-size: clamp(2rem, 5vw, 3.5rem);
202
- font-weight: 800;
203
- background: linear-gradient(135deg, #3b82f6 0%, #8b5cf6 50%, #3b82f6 100%);
204
- background-size: 200% 200%;
205
- -webkit-background-clip: text;
206
- -webkit-text-fill-color: transparent;
207
- margin: 0 0 0.5rem;
208
- letter-spacing: -1px;
209
- }
210
-
211
- .hero-header .subtitle {
212
- font-size: clamp(0.95rem, 2vw, 1.2rem);
213
- color: #808080;
214
- font-weight: 400;
215
- margin: 0;
216
- }
217
-
218
- .tab-nav {
219
- display: flex;
220
- gap: 2rem;
221
- justify-content: center;
222
- margin-bottom: 2rem;
223
- padding: 0.5rem;
224
- background: rgba(20, 20, 20, 0.6);
225
- border-radius: 16px;
226
- width: fit-content;
227
- margin-left: auto;
228
- margin-right: auto;
229
- border: 1px solid rgba(255, 255, 255, 0.1);
230
- }
231
-
232
- .gr-tab {
233
- background: transparent !important;
234
- border: none !important;
235
- border-radius: 12px !important;
236
- color: #a0a0a0 !important;
237
- font-weight: 600 !important;
238
- padding: 0.75rem 2rem !important;
239
- transition: all 0.3s ease !important;
240
- font-size: 1rem !important;
241
- cursor: pointer !important;
242
- }
243
-
244
- .gr-tab:hover {
245
- background: rgba(59, 130, 246, 0.1) !important;
246
- color: #e0e0e0 !important;
247
- }
248
-
249
- .gr-tab.selected {
250
- background: linear-gradient(135deg, #3b82f6, #8b5cf6) !important;
251
- color: white !important;
252
- box-shadow: 0 4px 15px rgba(59, 130, 246, 0.3) !important;
253
- }
254
-
255
- .top-section {
256
- display: grid;
257
- grid-template-columns: 400px 1fr;
258
- gap: 1.25rem;
259
- margin-bottom: 1.25rem;
260
- }
261
-
262
- .glass-card {
263
- background: rgba(20, 20, 20, 0.8);
264
- border: 1px solid rgba(255, 255, 255, 0.1);
265
- border-radius: 24px;
266
- padding: 1.5rem;
267
- backdrop-filter: blur(20px);
268
- box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);
269
- transition: all 0.3s ease;
270
- }
271
-
272
- .glass-card:hover {
273
- border-color: rgba(59, 130, 246, 0.3);
274
- box-shadow: 0 12px 40px rgba(59, 130, 246, 0.2);
275
- transform: translateY(-2px);
276
- }
277
-
278
- .upload-panel {
279
- background: rgba(20, 20, 20, 0.8);
280
- border: 1px solid rgba(255, 255, 255, 0.1);
281
- border-radius: 24px;
282
- padding: 1.5rem;
283
- backdrop-filter: blur(20px);
284
- box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);
285
- height: fit-content;
286
- }
287
-
288
- .section-label {
289
- font-size: 1.1rem;
290
- font-weight: 700;
291
- background: linear-gradient(135deg, #3b82f6, #8b5cf6);
292
- -webkit-background-clip: text;
293
- -webkit-text-fill-color: transparent;
294
- margin: 0 0 1rem;
295
- text-align: center;
296
- letter-spacing: 0.5px;
297
- }
298
-
299
- #input-image {
300
- border: 2px dashed rgba(59, 130, 246, 0.4) !important;
301
- border-radius: 20px !important;
302
- background: rgba(10, 10, 10, 0.6) !important;
303
- height: 320px !important;
304
- transition: all 0.3s ease;
305
- position: relative;
306
- overflow: hidden;
307
- }
308
-
309
- #input-image::before {
310
- display: none;
311
- }
312
-
313
- #input-image:hover {
314
- border-color: #3b82f6 !important;
315
- background: rgba(20, 20, 30, 0.8) !important;
316
- transform: scale(1.02);
317
- box-shadow: 0 0 30px rgba(59, 130, 246, 0.2);
318
- }
319
-
320
- .btn-row {
321
- display: flex;
322
- gap: 0.75rem;
323
- margin-top: 1rem;
324
- }
325
-
326
- .gr-button {
327
- border-radius: 14px !important;
328
- font-weight: 700 !important;
329
- height: 50px !important;
330
- font-size: 0.95rem !important;
331
- transition: all 0.3s ease !important;
332
- border: none !important;
333
- letter-spacing: 0.5px;
334
- text-transform: uppercase;
335
- }
336
-
337
- .gr-button-primary {
338
- background: linear-gradient(135deg, #3b82f6, #8b5cf6) !important;
339
- color: white !important;
340
- box-shadow: 0 4px 20px rgba(59, 130, 246, 0.4) !important;
341
- }
342
-
343
- .gr-button-primary:hover {
344
- transform: translateY(-3px) !important;
345
- box-shadow: 0 8px 30px rgba(59, 130, 246, 0.6) !important;
346
- }
347
-
348
- .gr-button-secondary {
349
- background: rgba(40, 40, 40, 0.8) !important;
350
- color: #a0a0a0 !important;
351
- border: 1px solid rgba(255, 255, 255, 0.1) !important;
352
- }
353
-
354
- .gr-button-secondary:hover {
355
- background: rgba(50, 50, 50, 0.9) !important;
356
- color: #e0e0e0 !important;
357
- }
358
-
359
- .results-panel {
360
- background: rgba(20, 20, 20, 0.8);
361
- border: 1px solid rgba(255, 255, 255, 0.1);
362
- border-radius: 24px;
363
- padding: 1.75rem;
364
- backdrop-filter: blur(20px);
365
- box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);
366
- }
367
-
368
- .result-card {
369
- padding: 0;
370
- }
371
-
372
- .pred-header {
373
- display: flex;
374
- align-items: center;
375
- justify-content: space-between;
376
- flex-wrap: wrap;
377
- gap: 1rem;
378
- margin-bottom: 0.75rem;
379
- }
380
-
381
- .pred-label {
382
- font-size: clamp(1.5rem, 3vw, 2rem);
383
- font-weight: 800;
384
- color: #ffffff;
385
- margin: 0;
386
- letter-spacing: -0.5px;
387
- }
388
-
389
- .badge {
390
- padding: 0.5rem 1.25rem;
391
- border-radius: 50px;
392
- font-size: 0.875rem;
393
- font-weight: 700;
394
- text-transform: uppercase;
395
- letter-spacing: 0.5px;
396
- box-shadow: 0 4px 15px rgba(0, 0, 0, 0.3);
397
- }
398
-
399
- .badge-high {
400
- background: linear-gradient(135deg, #10b981, #059669);
401
- color: white;
402
- }
403
- .badge-medium {
404
- background: linear-gradient(135deg, #f59e0b, #d97706);
405
- color: white;
406
- }
407
- .badge-low {
408
- background: linear-gradient(135deg, #ef4444, #dc2626);
409
- color: white;
410
- }
411
-
412
- .conf-score {
413
- font-size: clamp(2rem, 5vw, 3rem);
414
- font-weight: 900;
415
- background: linear-gradient(135deg, #3b82f6, #8b5cf6);
416
- -webkit-background-clip: text;
417
- -webkit-text-fill-color: transparent;
418
- margin-bottom: 1.25rem;
419
- letter-spacing: -1px;
420
- }
421
-
422
- .divider {
423
- height: 2px;
424
- background: linear-gradient(90deg, transparent, rgba(59, 130, 246, 0.3), transparent);
425
- margin: 1.5rem 0;
426
- }
427
-
428
- .top5-grid {
429
- display: flex;
430
- flex-direction: column;
431
- gap: 0.875rem;
432
- }
433
-
434
- .top5-row {
435
- display: grid;
436
- grid-template-columns: 40px 1fr auto 70px;
437
- align-items: center;
438
- gap: 0.875rem;
439
- font-size: 0.95rem;
440
- padding: 0.5rem;
441
- border-radius: 12px;
442
- background: rgba(30, 30, 30, 0.5);
443
- transition: all 0.3s ease;
444
- }
445
-
446
- .top5-row:hover {
447
- background: rgba(40, 40, 40, 0.7);
448
- transform: translateX(5px);
449
- }
450
-
451
- .rank {
452
- font-size: 1.5rem;
453
- text-align: center;
454
- }
455
-
456
- .label {
457
- color: #e0e0e0;
458
- font-weight: 600;
459
- white-space: nowrap;
460
- overflow: hidden;
461
- text-overflow: ellipsis;
462
- }
463
-
464
- .bar-wrap {
465
- background: rgba(40, 40, 40, 0.8);
466
- height: 10px;
467
- border-radius: 5px;
468
- overflow: hidden;
469
- min-width: 100px;
470
- box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.3);
471
- }
472
-
473
- .bar {
474
- background: linear-gradient(90deg, #3b82f6, #8b5cf6);
475
- height: 100%;
476
- transition: width 1s ease;
477
- border-radius: 5px;
478
- box-shadow: 0 0 10px rgba(59, 130, 246, 0.5);
479
- }
480
-
481
- .pct {
482
- color: #3b82f6;
483
- font-weight: 700;
484
- font-size: 0.9rem;
485
- text-align: right;
486
- }
487
-
488
- .viz-section {
489
- background: rgba(20, 20, 20, 0.8);
490
- border: 1px solid rgba(255, 255, 255, 0.1);
491
- border-radius: 24px;
492
- padding: 1.75rem;
493
- backdrop-filter: blur(20px);
494
- box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);
495
- }
496
-
497
- #result-image {
498
- border-radius: 16px !important;
499
- overflow: hidden;
500
- width: 100%;
501
- height: auto;
502
- box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5);
503
- }
504
-
505
- .about-content {
506
- max-width: 900px;
507
- margin: 0 auto;
508
- padding: 2rem;
509
- background: rgba(20, 20, 20, 0.6);
510
- border: 1px solid rgba(255, 255, 255, 0.1);
511
- border-radius: 20px;
512
- line-height: 1.8;
513
- }
514
-
515
- .placeholder {
516
- text-align: center;
517
- padding: 4rem 1.5rem;
518
- color: #606060;
519
- font-size: 1.1rem;
520
- line-height: 1.6;
521
- }
522
-
523
- .placeholder strong {
524
- color: #3b82f6;
525
- }
526
-
527
- .error-msg {
528
- color: #ef4444;
529
- background: rgba(239, 68, 68, 0.1);
530
- padding: 1.5rem;
531
- border-radius: 16px;
532
- text-align: center;
533
- border: 1px solid rgba(239, 68, 68, 0.3);
534
- }
535
-
536
- .gr-accordion {
537
- background: rgba(20, 20, 20, 0.8) !important;
538
- border: 1px solid rgba(255, 255, 255, 0.1) !important;
539
- border-radius: 20px !important;
540
- backdrop-filter: blur(20px);
541
- margin-top: 1.5rem;
542
- overflow: hidden;
543
- }
544
-
545
- .gr-accordion summary {
546
- color: #e0e0e0 !important;
547
- font-weight: 700 !important;
548
- padding: 1.25rem 1.5rem !important;
549
- font-size: 1.1rem !important;
550
- cursor: pointer;
551
- transition: all 0.3s ease;
552
- }
553
-
554
- .gr-accordion summary:hover {
555
- background: rgba(59, 130, 246, 0.1);
556
- }
557
-
558
- .gr-accordion[open] summary {
559
- border-bottom: 1px solid rgba(255, 255, 255, 0.1);
560
- }
561
-
562
- .gr-tab {
563
- background: rgba(20, 20, 20, 0.6) !important;
564
- border: 1px solid rgba(255, 255, 255, 0.1) !important;
565
- border-radius: 16px 16px 0 0 !important;
566
- color: #a0a0a0 !important;
567
- font-weight: 600 !important;
568
- transition: all 0.3s ease;
569
- }
570
-
571
- .gr-tab:hover {
572
- background: rgba(30, 30, 30, 0.8) !important;
573
- color: #e0e0e0 !important;
574
- }
575
-
576
- .gr-tab.selected {
577
- background: linear-gradient(135deg, #3b82f6, #8b5cf6) !important;
578
- color: white !important;
579
- border-bottom: none !important;
580
- }
581
-
582
- .gr-tabitem {
583
- background: transparent !important;
584
- border: none !important;
585
- padding: 0 !important;
586
- }
587
-
588
  footer, .footer { display: none !important; }
589
-
590
- ::-webkit-scrollbar {
591
- width: 10px;
592
- height: 10px;
593
- }
594
-
595
- ::-webkit-scrollbar-track {
596
- background: rgba(20, 20, 20, 0.5);
597
- }
598
-
599
- ::-webkit-scrollbar-thumb {
600
- background: rgba(59, 130, 246, 0.5);
601
- border-radius: 5px;
602
- }
603
-
604
- ::-webkit-scrollbar-thumb:hover {
605
- background: rgba(59, 130, 246, 0.7);
606
- }
607
-
608
- @media (max-width: 1024px) {
609
- .top-section {
610
- grid-template-columns: 360px 1fr;
611
- gap: 1rem;
612
- }
613
-
614
- #input-image {
615
- height: 280px !important;
616
- }
617
-
618
- .features-grid {
619
- grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
620
- }
621
- }
622
-
623
- @media (max-width: 768px) {
624
- .main-wrapper {
625
- padding: 1rem;
626
- }
627
-
628
- .hero-header {
629
- padding: 1.5rem 0.75rem;
630
- }
631
-
632
- .top-section {
633
- grid-template-columns: 1fr;
634
- gap: 1rem;
635
- }
636
-
637
- .upload-panel, .results-panel, .viz-section {
638
- width: 100%;
639
- }
640
-
641
- #input-image {
642
- height: 240px !important;
643
- }
644
-
645
- .top5-row {
646
- grid-template-columns: 35px 1fr 60px;
647
- gap: 0.625rem;
648
- }
649
-
650
- .bar-wrap {
651
- grid-column: 1 / -1;
652
- margin-top: 0.375rem;
653
- }
654
-
655
- .btn-row {
656
- flex-direction: column;
657
- }
658
-
659
- .gr-button {
660
- width: 100% !important;
661
- }
662
-
663
- .about-hero {
664
- padding: 2rem 1rem;
665
- }
666
-
667
- .use-case-item {
668
- flex-direction: column;
669
- gap: 1rem;
670
- }
671
- }
672
-
673
- @media (max-width: 480px) {
674
- .hero-header h1 {
675
- font-size: 1.75rem;
676
- }
677
-
678
- #input-image {
679
- height: 220px !important;
680
- }
681
-
682
- .pred-header {
683
- flex-direction: column;
684
- align-items: flex-start;
685
- }
686
-
687
- .gr-button {
688
- height: 46px !important;
689
- font-size: 0.875rem !important;
690
- }
691
-
692
- .feature-card {
693
- padding: 1.5rem;
694
- }
695
-
696
- .use-cases {
697
- padding: 1.5rem;
698
- }
699
- }
700
  """
701
 
 
 
 
702
 
703
- with gr.Blocks(css=custom_css, theme=gr.themes.Base(), title="Explainable AI Classifier") as demo:
704
-
705
-
706
- gr.HTML("""
707
- <link rel="icon" href="https://res.cloudinary.com/ddn0xuwut/image/upload/v1761284764/encryption_hc0fxo.png" type="image/png">
708
- """)
709
-
710
- with gr.Tabs() as tabs:
711
-
712
- with gr.TabItem("🔮 Classifier", id=0):
713
- with gr.Column(elem_classes="main-wrapper"):
714
- gr.HTML("""
715
- <div class="hero-header">
716
- <h1>Explainable AI Classifier</h1>
717
- <p class="subtitle">See exactly what the AI sees – powered by ResNet50 + Grad-CAM</p>
718
- </div>
719
- """)
720
-
721
-
722
- with gr.Row(elem_classes="top-section"):
723
-
724
- with gr.Column(scale=0, min_width=400, elem_classes="upload-panel"):
725
- gr.HTML("<div class='section-label'>📤 Upload Image</div>")
726
-
727
- input_image = gr.Image(
728
- type="pil",
729
- label=None,
730
- elem_id="input-image",
731
- show_label=False,
732
- container=False
733
- )
734
-
735
- with gr.Row(elem_classes="btn-row"):
736
- predict_btn = gr.Button("🚀 Analyze", variant="primary", size="lg", scale=2)
737
- clear_btn = gr.ClearButton([input_image], value="🗑️ Clear", size="lg", scale=1)
738
-
739
- with gr.Accordion("💡 Tips for Best Results", open=False):
740
- gr.Markdown("""
741
- - Use **clear, well-lit photos**
742
- - **Center the main subject**
743
- - Avoid heavy filters or edits
744
- - Works best with **single objects**
745
- - Supports JPG, PNG, WebP formats
746
- """)
747
-
748
-
749
- with gr.Column(scale=1, elem_classes="results-panel"):
750
- output_text = gr.HTML(
751
- """<div class='placeholder'>
752
- <strong>👋 Welcome!</strong><br><br>
753
- Upload an image and click <strong>Analyze</strong> to see:<br>
754
- ✓ AI predictions with confidence scores<br>
755
- ✓ Visual explanations (what the AI focuses on)<br>
756
- ✓ Top 5 possible classifications
757
- </div>"""
758
- )
759
 
760
-
761
- with gr.Column(elem_classes="viz-section"):
762
- gr.HTML("<div class='section-label'>🎯 Visual Explainability</div>")
763
- output_image = gr.Image(
764
- label=None,
765
- type="pil",
766
- show_label=False,
767
- elem_id="result-image",
768
- height=450
769
- )
770
 
771
- with gr.Accordion("📚 How It Works", open=False):
772
- gr.Markdown("""
773
- ### The Technology Behind This Tool
774
-
775
- **1. ResNet50 Neural Network**
776
- A deep learning model trained on 1,000+ categories from ImageNet dataset.
777
- Achieves 76%+ accuracy on real-world images.
778
-
779
- **2. Grad-CAM (Gradient-weighted Class Activation Mapping)**
780
- Developed by researchers at Georgia Tech, Grad-CAM highlights which regions
781
- of the image were most important for the AI's decision.
782
-
783
- **3. Real-Time Inference**
784
- Your image is processed locally in this interface – we never store your uploads.
785
-
786
- ### Why This Matters
787
- - **Transparency**: See *why* the AI made its decision
788
- - **Trust**: Verify the AI is focusing on relevant features
789
- - **Debugging**: Understand when and why predictions fail
790
- - **Compliance**: Meet explainability requirements (EU AI Act, GDPR)
791
- """)
792
 
793
-
794
- with gr.TabItem("ℹ️ About", id=1):
795
- with gr.Column(elem_classes="main-wrapper about-page"):
796
- gr.HTML("""
797
- <div class="about-hero">
798
- <h1>About Explainable AI</h1>
799
- <p>Making artificial intelligence transparent, interpretable, and trustworthy for everyone</p>
800
- </div>
801
- """)
802
-
803
- gr.HTML("""
804
- <div class="features-grid">
805
- <div class="feature-card">
806
- <span class="feature-icon">🔍</span>
807
- <h3>Transparency</h3>
808
- <p>No more "black box" decisions. See exactly which parts of your image influenced the AI's prediction with visual heatmaps.</p>
809
- </div>
810
-
811
- <div class="feature-card">
812
- <span class="feature-icon">🛡️</span>
813
- <h3>Trust & Safety</h3>
814
- <p>Verify that AI models are making decisions based on relevant features, not spurious correlations or biases.</p>
815
- </div>
816
-
817
- <div class="feature-card">
818
- <span class="feature-icon">⚖️</span>
819
- <h3>Regulatory Compliance</h3>
820
- <p>Meet requirements from EU AI Act, GDPR, FDA guidelines for medical AI, and other global regulations.</p>
821
- </div>
822
-
823
- <div class="feature-card">
824
- <span class="feature-icon">🎓</span>
825
- <h3>Educational</h3>
826
- <p>Learn how deep learning works by visualizing what neural networks "see" when processing images.</p>
827
- </div>
828
-
829
- <div class="feature-card">
830
- <span class="feature-icon">🚀</span>
831
- <h3>Production-Ready</h3>
832
- <p>Built with PyTorch and Captum (Meta's interpretability library), this tool uses industry-standard techniques.</p>
833
- </div>
834
-
835
- <div class="feature-card">
836
- <span class="feature-icon">🌐</span>
837
- <h3>Open Source Spirit</h3>
838
- <p>Based on open research and publicly available models. Knowledge should be accessible to all.</p>
839
- </div>
840
- </div>
841
-
842
- <div class="use-cases">
843
- <h2>Real-World Applications</h2>
844
-
845
- <div class="use-case-item">
846
- <span class="use-case-icon">🏥</span>
847
- <div class="use-case-content">
848
- <h3>Healthcare & Medical Imaging</h3>
849
- <p><strong>Problem:</strong> Radiologists need to trust AI diagnostic tools.<br>
850
- <strong>Solution:</strong> Grad-CAM shows if the AI is focusing on tumors, lesions, or irrelevant artifacts. This builds trust and helps doctors make informed decisions.</p>
851
- </div>
852
- </div>
853
-
854
- <div class="use-case-item">
855
- <span class="use-case-icon">🚗</span>
856
- <div class="use-case-content">
857
- <h3>Autonomous Vehicles</h3>
858
- <p><strong>Problem:</strong> Self-driving cars must explain their perception to passengers and regulators.<br>
859
- <strong>Solution:</strong> Visual explanations confirm the AI detected pedestrians, traffic signs, and road boundaries – not random patterns.</p>
860
- </div>
861
- </div>
862
-
863
- <div class="use-case-item">
864
- <span class="use-case-icon">💰</span>
865
- <div class="use-case-content">
866
- <h3>Financial Services</h3>
867
- <p><strong>Problem:</strong> Banks must explain loan approval/denial decisions (Fair Lending Act).<br>
868
- <strong>Solution:</strong> Explainable AI shows which factors (income, credit score, employment) influenced the decision, ensuring fairness.</p>
869
- </div>
870
- </div>
871
-
872
- <div class="use-case-item">
873
- <span class="use-case-icon">🔒</span>
874
- <div class="use-case-content">
875
- <h3>Security & Surveillance</h3>
876
- <p><strong>Problem:</strong> Facial recognition and threat detection systems face scrutiny over bias.<br>
877
- <strong>Solution:</strong> Grad-CAM reveals if the system is using facial features appropriately or making decisions based on background elements.</p>
878
- </div>
879
- </div>
880
-
881
- <div class="use-case-item">
882
- <span class="use-case-icon">🌾</span>
883
- <div class="use-case-content">
884
- <h3>Agriculture & Environment</h3>
885
- <p><strong>Problem:</strong> Farmers need to verify AI crop disease detection accuracy.<br>
886
- <strong>Solution:</strong> Visual explanations show if the AI identified actual disease symptoms (leaf discoloration, spots) or environmental factors.</p>
887
- </div>
888
- </div>
889
-
890
- <div class="use-case-item">
891
- <span class="use-case-icon">🛒</span>
892
- <div class="use-case-content">
893
- <h3>E-Commerce & Retail</h3>
894
- <p><strong>Problem:</strong> Product recognition systems must be reliable for inventory and checkout.<br>
895
- <strong>Solution:</strong> Explainability helps debug failures – did the AI misidentify a product because of lighting, angle, or packaging?</p>
896
- </div>
897
- </div>
898
- </div>
899
- """)
900
-
901
- gr.Markdown("""
902
- ## Why Explainability is the Future
903
-
904
- As AI becomes more integrated into critical decision-making processes, **explainability is no longer optional**:
905
-
906
- - **EU AI Act (2024)**: High-risk AI systems must provide explanations
907
- - **GDPR Right to Explanation**: Users can demand explanations for automated decisions
908
- - **FDA Guidelines**: Medical AI must demonstrate interpretability
909
- - **Ethical AI Standards**: Leading tech companies committed to transparency
910
-
911
- ---
912
-
913
- ## Technical Stack
914
-
915
- This tool is built with:
916
- - **PyTorch**: Deep learning framework
917
- - **torchvision**: Pre-trained ResNet50 model
918
- - **Captum**: Meta's interpretability library
919
- - **Gradio**: Interactive web interface
920
- - **Grad-CAM**: Visual explanation technique
921
-
922
- ---
923
-
924
-
925
- """)
926
 
 
 
 
927
 
928
- predict_btn.click(
929
- fn=predict_and_explain,
930
- inputs=[input_image],
931
- outputs=[output_text, output_image]
932
- )
933
 
 
934
 
935
  if __name__ == "__main__":
936
  demo.launch(share=False, show_error=True)
 
1
+ """
2
+ Explainable AI Image Classifier - Optimized Production Version
3
+ ===============================================================
4
+ """
5
 
6
  import torch
7
  import torch.nn as nn
 
12
  import numpy as np
13
  import matplotlib.pyplot as plt
14
  from io import BytesIO
15
+ import urllib.request
16
  from torch.nn.functional import interpolate
17
  import warnings
18
  warnings.filterwarnings('ignore')
19
 
20
+ # ============================================================================
21
+ # CONFIGURATION & MODEL LOADING
22
+ # ============================================================================
23
 
24
  DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
 
 
25
 
26
  @torch.no_grad()
27
  def load_model_and_labels():
28
+ """Load ResNet50 with optimized settings"""
29
  model = models.resnet50(weights='IMAGENET1K_V2')
30
  model.eval()
31
  model = model.to(DEVICE)
32
+
33
+ # Load cleaner ImageNet labels
34
+ url = "https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt"
35
+ response = urllib.request.urlopen(url)
36
+ labels = [line.decode('utf-8').strip() for line in response.readlines()]
37
+
38
  return model, labels
39
 
40
  model, IMAGENET_LABELS = load_model_and_labels()
41
 
42
+ # Setup Grad-CAM
43
  target_layer = model.layer4[-1]
44
  gradcam = LayerGradCam(model, target_layer)
45
 
46
+ # Optimized preprocessing
47
  transform = transforms.Compose([
48
  transforms.Resize((224, 224)),
49
  transforms.ToTensor(),
50
+ transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
 
51
  ])
52
 
53
+ # ============================================================================
54
+ # OPTIMIZED PREDICTION FUNCTION
55
+ # ============================================================================
56
 
57
  def predict_and_explain(image):
58
  if image is None:
59
+ return "Please upload an image", None, None
60
 
61
  try:
62
+ # Preprocess
63
  img_tensor = transform(image).unsqueeze(0).to(DEVICE)
64
 
65
+ # Predict with temperature scaling for better confidence
66
  with torch.no_grad():
67
  output = model(img_tensor)
68
+ # Apply temperature scaling (makes confidence more realistic)
69
+ temperature = 1.0 # Adjust between 0.8-1.5 if needed
70
+ scaled_output = output / temperature
71
+ probabilities = torch.softmax(scaled_output, dim=1)
72
+ top10_prob, top10_idx = torch.topk(probabilities, 10)
73
 
74
+ pred_class = top10_idx[0][0].item()
75
+ confidence = top10_prob[0][0].item()
76
 
77
+ # Generate Grad-CAM
78
  attributions = gradcam.attribute(img_tensor, target=pred_class)
79
  attr_resized = interpolate(attributions, size=(224, 224), mode='bilinear', align_corners=False)
80
  attr_np = attr_resized.squeeze().cpu().detach().numpy()
81
  attr_np = (attr_np - attr_np.min()) / (attr_np.max() - attr_np.min() + 1e-8)
82
 
83
+ # Create enhanced visualization (LARGER SIZE)
84
+ fig = plt.figure(figsize=(20, 12)) # Increased from 18x10 to 20x12
85
  fig.patch.set_facecolor('#0a0a0a')
86
+
87
+ gs = fig.add_gridspec(2, 3, height_ratios=[2, 1], hspace=0.25, wspace=0.12) # More space for images
88
+
89
+ # Top row: Larger image panels
90
+ ax1 = fig.add_subplot(gs[0, 0])
91
+ ax2 = fig.add_subplot(gs[0, 1])
92
+ ax3 = fig.add_subplot(gs[0, 2])
93
+ ax4 = fig.add_subplot(gs[1, :])
94
+
95
+ # Panel 1: Original
96
+ ax1.imshow(image)
97
+ ax1.set_title("Original Image", fontsize=15, fontweight='600', color='#e0e0e0', pad=15)
98
+ ax1.axis('off')
99
+
100
+ # Panel 2: Detailed Heatmap
101
+ im = ax2.imshow(attr_np, cmap='jet', interpolation='bilinear')
102
+ ax2.set_title("Grad-CAM Heatmap", fontsize=15, fontweight='600', color='#e0e0e0', pad=15)
103
+ ax2.axis('off')
104
+ cbar = plt.colorbar(im, ax=ax2, fraction=0.046, pad=0.04)
105
+ cbar.ax.tick_params(labelsize=10, colors='#a0a0a0')
106
+ cbar.set_label('Importance', rotation=270, labelpad=20, color='#e0e0e0', fontsize=11, fontweight='600')
107
+
108
+ # Panel 3: Overlay
109
+ ax3.imshow(image)
110
+ ax3.imshow(attr_np, cmap='jet', alpha=0.5, interpolation='bilinear')
111
+ ax3.set_title(f"AI Focus: {IMAGENET_LABELS[pred_class]}", fontsize=15, fontweight='600', color='#e0e0e0', pad=15)
112
+ ax3.axis('off')
113
+
114
+ # Panel 4: Bar Graph
115
+ top10_labels = [IMAGENET_LABELS[idx.item()] for idx in top10_idx[0]]
116
+ top10_probs = [prob.item() * 100 for prob in top10_prob[0]]
117
+
118
+ colors = ['#10b981' if i == 9 else '#3b82f6' if i >= 7 else '#8b5cf6' for i in range(10)]
119
+ bars = ax4.barh(range(10), top10_probs[::-1], color=colors[::-1], edgecolor='#1a1a1a', linewidth=1.5)
120
+
121
+ ax4.set_yticks(range(10))
122
+ ax4.set_yticklabels(top10_labels[::-1], fontsize=12, color='#e0e0e0')
123
+ ax4.set_xlabel('Confidence (%)', fontsize=13, color='#e0e0e0', fontweight='600')
124
+ ax4.set_title('Top 10 Predictions', fontsize=16, fontweight='700', color='#e0e0e0', pad=15)
125
+ ax4.set_xlim([0, 100])
126
+ ax4.grid(axis='x', alpha=0.2, color='#404040', linestyle='--')
127
+ ax4.set_facecolor('#0a0a0a')
128
+ ax4.spines['top'].set_visible(False)
129
+ ax4.spines['right'].set_visible(False)
130
+ ax4.spines['left'].set_color('#404040')
131
+ ax4.spines['bottom'].set_color('#404040')
132
+ ax4.tick_params(colors='#a0a0a0', labelsize=11)
133
+
134
+ # Add percentage labels
135
+ for bar, prob in zip(bars, top10_probs[::-1]):
136
+ ax4.text(prob + 1.5, bar.get_y() + bar.get_height()/2,
137
+ f'{prob:.1f}%', va='center', fontsize=11, color='#e0e0e0', fontweight='600')
138
+
139
+ plt.tight_layout()
140
+
141
+ buf = BytesIO()
142
+ plt.savefig(buf, format='png', dpi=120, bbox_inches='tight', facecolor='#0a0a0a')
143
+ buf.seek(0)
144
+ result_image = Image.open(buf)
145
+ plt.close(fig)
146
 
147
+ # Create detailed heatmap panel
148
+ fig2, axes = plt.subplots(1, 3, figsize=(18, 6)) # Increased from 15x5 to 18x6
149
+ fig2.patch.set_facecolor('#0a0a0a')
150
 
151
  axes[0].imshow(image)
152
+ axes[0].set_title("Original", fontsize=14, fontweight='600', color='#e0e0e0', pad=12)
153
  axes[0].axis('off')
 
154
 
155
+ im2 = axes[1].imshow(attr_np, cmap='viridis', interpolation='gaussian')
156
+ axes[1].set_title("High-Res Heatmap", fontsize=14, fontweight='600', color='#e0e0e0', pad=12)
157
  axes[1].axis('off')
158
+ cbar2 = plt.colorbar(im2, ax=axes[1], fraction=0.046, pad=0.04)
159
+ cbar2.ax.tick_params(labelsize=10, colors='#a0a0a0')
160
+
 
 
161
  axes[2].imshow(image)
162
+ axes[2].imshow(attr_np, cmap='hot', alpha=0.6, interpolation='bilinear')
163
+ axes[2].contour(attr_np, levels=5, colors='white', linewidths=1.5, alpha=0.8)
164
+ axes[2].set_title("Contour Analysis", fontsize=14, fontweight='600', color='#e0e0e0', pad=12)
165
  axes[2].axis('off')
166
+
167
+ plt.tight_layout()
168
+
169
+ buf2 = BytesIO()
170
+ plt.savefig(buf2, format='png', dpi=110, bbox_inches='tight', facecolor='#0a0a0a')
171
+ buf2.seek(0)
172
+ detailed_heatmap = Image.open(buf2)
173
+ plt.close(fig2)
174
 
175
+ # Generate HTML output
176
+ badge = "high" if confidence > 0.8 else "medium" if confidence > 0.5 else "low"
177
+ badge_text = "High Confidence" if confidence > 0.8 else "Medium Confidence" if confidence > 0.5 else "Low Confidence"
178
+ badge_icon = "🎯" if confidence > 0.8 else "⚡" if confidence > 0.5 else "⚠️"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
179
 
 
180
  top5_html = "<div class='top5-grid'>"
181
  icons = ["🥇", "🥈", "🥉", "4️⃣", "5️⃣"]
182
+ for i, (prob, idx) in enumerate(zip(top10_prob[0][:5], top10_idx[0][:5])):
183
  pct = prob.item() * 100
184
  top5_html += f"""
185
  <div class='top5-row'>
186
  <span class='rank'>{icons[i]}</span>
187
+ <span class='label'>{IMAGENET_LABELS[idx.item()]}</span>
188
  <div class='bar-wrap'><div class='bar' style='width:{pct}%'></div></div>
189
+ <span class='pct'>{pct:.2f}%</span>
190
+ </div>"""
 
191
  top5_html += "</div>"
192
 
 
193
  prediction_text = f"""
194
  <div class="result-card">
195
  <div class="pred-header">
196
+ <h2 class="pred-label">{IMAGENET_LABELS[pred_class]}</h2>
197
  <div class="badge badge-{badge}">{badge_icon} {badge_text}</div>
198
  </div>
199
+ <div class="conf-score">{confidence*100:.2f}%</div>
200
  <div class="divider"></div>
201
  {top5_html}
202
+ </div>"""
203
+
204
+ return prediction_text, result_image, detailed_heatmap
205
 
206
  except Exception as e:
207
+ return f"<div class='error-msg'>⚠️ Error: {str(e)}</div>", None, None
208
 
209
+ # ============================================================================
210
+ # STREAMLINED CSS
211
+ # ============================================================================
212
 
213
  custom_css = """
214
  @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap');
215
+ * { box-sizing: border-box; margin: 0; padding: 0; }
216
+ body, .gradio-container { margin: 0 !important; padding: 0 !important; width: 100vw !important; min-height: 100vh !important; max-width: 100vw !important; background: linear-gradient(135deg, #0a0a0a 0%, #1a1a1a 50%, #0f0f0f 100%) !important; font-family: 'Inter', sans-serif !important; color: #e0e0e0 !important; overflow-x: hidden !important; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
217
  .gradio-container { padding: 0 !important; }
218
+ .main-wrapper { padding: 1.5rem; max-width: 1920px; margin: 0 auto; position: relative; z-index: 2; }
219
+ .hero-header { text-align: center; padding: 2rem 1rem 1.5rem; margin-bottom: 1.5rem; }
220
+ .hero-header h1 { font-size: clamp(2rem, 5vw, 3.5rem); font-weight: 800; background: linear-gradient(135deg, #3b82f6 0%, #8b5cf6 50%, #3b82f6 100%); -webkit-background-clip: text; -webkit-text-fill-color: transparent; margin: 0 0 0.5rem; letter-spacing: -1px; }
221
+ .hero-header .subtitle { font-size: clamp(0.95rem, 2vw, 1.2rem); color: #808080; font-weight: 400; margin: 0; }
222
+ .top-section { display: grid; grid-template-columns: 400px 1fr; gap: 1.25rem; margin-bottom: 1.25rem; }
223
+ .upload-panel, .results-panel, .viz-section { background: rgba(20, 20, 20, 0.8); border: 1px solid rgba(255, 255, 255, 0.1); border-radius: 24px; padding: 1.5rem; backdrop-filter: blur(20px); box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4); }
224
+ .section-label { font-size: 1.1rem; font-weight: 700; background: linear-gradient(135deg, #3b82f6, #8b5cf6); -webkit-background-clip: text; -webkit-text-fill-color: transparent; margin: 0 0 1rem; text-align: center; letter-spacing: 0.5px; }
225
+ #input-image { border: 2px dashed rgba(59, 130, 246, 0.4) !important; border-radius: 20px !important; background: rgba(10, 10, 10, 0.6) !important; height: 320px !important; transition: all 0.3s ease; }
226
+ #input-image:hover { border-color: #3b82f6 !important; background: rgba(20, 20, 30, 0.8) !important; transform: scale(1.02); box-shadow: 0 0 30px rgba(59, 130, 246, 0.2); }
227
+ .btn-row { display: flex; gap: 0.75rem; margin-top: 1rem; }
228
+ .gr-button { border-radius: 14px !important; font-weight: 700 !important; height: 50px !important; font-size: 0.95rem !important; transition: all 0.3s ease !important; border: none !important; letter-spacing: 0.5px; text-transform: uppercase; }
229
+ .gr-button-primary { background: linear-gradient(135deg, #3b82f6, #8b5cf6) !important; color: white !important; box-shadow: 0 4px 20px rgba(59, 130, 246, 0.4) !important; }
230
+ .gr-button-primary:hover { transform: translateY(-3px) !important; box-shadow: 0 8px 30px rgba(59, 130, 246, 0.6) !important; }
231
+ .gr-button-secondary { background: rgba(40, 40, 40, 0.8) !important; color: #a0a0a0 !important; border: 1px solid rgba(255, 255, 255, 0.1) !important; }
232
+ .pred-header { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 1rem; margin-bottom: 0.75rem; }
233
+ .pred-label { font-size: clamp(1.5rem, 3vw, 2rem); font-weight: 800; color: #ffffff; margin: 0; letter-spacing: -0.5px; }
234
+ .badge { padding: 0.5rem 1.25rem; border-radius: 50px; font-size: 0.875rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px; box-shadow: 0 4px 15px rgba(0, 0, 0, 0.3); }
235
+ .badge-high { background: linear-gradient(135deg, #10b981, #059669); color: white; }
236
+ .badge-medium { background: linear-gradient(135deg, #f59e0b, #d97706); color: white; }
237
+ .badge-low { background: linear-gradient(135deg, #ef4444, #dc2626); color: white; }
238
+ .conf-score { font-size: clamp(2rem, 5vw, 3rem); font-weight: 900; background: linear-gradient(135deg, #3b82f6, #8b5cf6); -webkit-background-clip: text; -webkit-text-fill-color: transparent; margin-bottom: 1.25rem; letter-spacing: -1px; }
239
+ .divider { height: 2px; background: linear-gradient(90deg, transparent, rgba(59, 130, 246, 0.3), transparent); margin: 1.5rem 0; }
240
+ .top5-grid { display: flex; flex-direction: column; gap: 0.875rem; }
241
+ .top5-row { display: grid; grid-template-columns: 40px 1fr auto 80px; align-items: center; gap: 0.875rem; font-size: 0.95rem; padding: 0.5rem; border-radius: 12px; background: rgba(30, 30, 30, 0.5); transition: all 0.3s ease; }
242
+ .top5-row:hover { background: rgba(40, 40, 40, 0.7); transform: translateX(5px); }
243
+ .rank { font-size: 1.5rem; text-align: center; }
244
+ .label { color: #e0e0e0; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
245
+ .bar-wrap { background: rgba(40, 40, 40, 0.8); height: 10px; border-radius: 5px; overflow: hidden; min-width: 100px; box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.3); }
246
+ .bar { background: linear-gradient(90deg, #3b82f6, #8b5cf6); height: 100%; transition: width 1s ease; border-radius: 5px; box-shadow: 0 0 10px rgba(59, 130, 246, 0.5); }
247
+ .pct { color: #3b82f6; font-weight: 700; font-size: 0.9rem; text-align: right; }
248
+ #result-image, #detailed-heatmap { border-radius: 16px !important; overflow: hidden; width: 100%; height: auto; box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5); }
249
+ .placeholder { text-align: center; padding: 4rem 1.5rem; color: #606060; font-size: 1.1rem; line-height: 1.6; }
250
+ .placeholder strong { color: #3b82f6; }
251
+ .error-msg { color: #ef4444; background: rgba(239, 68, 68, 0.1); padding: 1.5rem; border-radius: 16px; text-align: center; border: 1px solid rgba(239, 68, 68, 0.3); }
252
+ .gr-accordion { background: rgba(20, 20, 20, 0.8) !important; border: 1px solid rgba(255, 255, 255, 0.1) !important; border-radius: 20px !important; margin-top: 1.5rem; }
253
+ .gr-accordion summary { color: #e0e0e0 !important; font-weight: 700 !important; padding: 1.25rem 1.5rem !important; font-size: 1.1rem !important; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
254
  footer, .footer { display: none !important; }
255
+ ::-webkit-scrollbar { width: 10px; }
256
+ ::-webkit-scrollbar-track { background: rgba(20, 20, 20, 0.5); }
257
+ ::-webkit-scrollbar-thumb { background: rgba(59, 130, 246, 0.5); border-radius: 5px; }
258
+ @media (max-width: 768px) { .top-section { grid-template-columns: 1fr; } #input-image { height: 240px !important; } .top5-row { grid-template-columns: 35px 1fr 70px; } .bar-wrap { grid-column: 1 / -1; margin-top: 0.375rem; } }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
259
  """
260
 
261
+ # ============================================================================
262
+ # STREAMLINED INTERFACE
263
+ # ============================================================================
264
 
265
+ with gr.Blocks(css=custom_css, theme=gr.themes.Base(), title="Explainable AI") as demo:
266
+ gr.HTML('<link rel="icon" href="https://res.cloudinary.com/ddn0xuwut/image/upload/v1761284764/encryption_hc0fxo.png" type="image/png">')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
267
 
268
+ with gr.Column(elem_classes="main-wrapper"):
269
+ gr.HTML('<div class="hero-header"><h1>Explainable AI Classifier</h1><p class="subtitle">See exactly what the AI sees – powered by ResNet50 + Grad-CAM</p></div>')
 
 
 
 
 
 
 
 
270
 
271
+ with gr.Row(elem_classes="top-section"):
272
+ with gr.Column(scale=0, min_width=400, elem_classes="upload-panel"):
273
+ gr.HTML("<div class='section-label'>📤 Upload Image</div>")
274
+ input_image = gr.Image(type="pil", label=None, elem_id="input-image", show_label=False, container=False)
275
+ with gr.Row(elem_classes="btn-row"):
276
+ predict_btn = gr.Button("🚀 Analyze", variant="primary", size="lg", scale=2)
277
+ clear_btn = gr.ClearButton([input_image], value="🗑️ Clear", size="lg", scale=1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
278
 
279
+ with gr.Column(scale=1, elem_classes="results-panel"):
280
+ output_text = gr.HTML('<div class="placeholder"><strong>👋 Welcome!</strong><br><br>Upload an image and click <strong>Analyze</strong></div>')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
281
 
282
+ with gr.Column(elem_classes="viz-section"):
283
+ gr.HTML("<div class='section-label'>🎯 Visual Explainability (Includes Bar Graph)</div>")
284
+ output_image = gr.Image(label=None, type="pil", show_label=False, elem_id="result-image", height=700)
285
 
286
+ with gr.Column(elem_classes="viz-section"):
287
+ gr.HTML("<div class='section-label'>🔬 Advanced Heatmap Analysis</div>")
288
+ detailed_heatmap = gr.Image(label=None, type="pil", show_label=False, elem_id="detailed-heatmap", height=500)
 
 
289
 
290
+ predict_btn.click(fn=predict_and_explain, inputs=[input_image], outputs=[output_text, output_image, detailed_heatmap])
291
 
292
  if __name__ == "__main__":
293
  demo.launch(share=False, show_error=True)