JKrishnanandhaa commited on
Commit
93ae4b7
·
verified ·
1 Parent(s): c38d472

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -22
app.py CHANGED
@@ -13,6 +13,7 @@ import json
13
  from pathlib import Path
14
  import sys
15
  from typing import Dict, List, Tuple
 
16
 
17
  # Add src to path
18
  sys.path.insert(0, str(Path(__file__).parent))
@@ -52,6 +53,37 @@ MODEL_METRICS = {
52
  }
53
 
54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  class ForgeryDetector:
56
  """Main forgery detection pipeline"""
57
 
@@ -85,12 +117,11 @@ class ForgeryDetector:
85
  """
86
  Detect forgeries in document image or PDF
87
 
88
- Args:
89
- image: PIL Image, numpy array, or path to PDF file
90
-
91
  Returns:
92
  original_image: Original uploaded image
93
  overlay_image: Image with detection overlay
 
 
94
  results_html: Detection results as HTML
95
  """
96
  # Handle PDF files
@@ -174,10 +205,14 @@ class ForgeryDetector:
174
  # Create visualization
175
  overlay = self._create_overlay(original_image, results)
176
 
 
 
 
 
177
  # Create HTML response
178
  results_html = self._create_html_report(results)
179
 
180
- return original_image, overlay, results_html
181
 
182
  def _create_overlay(self, image, results):
183
  """Create overlay visualization"""
@@ -236,10 +271,6 @@ class ForgeryDetector:
236
  • Regions detected: {num_detections}<br>
237
  • Average confidence: {avg_confidence*100:.1f}%<br><br>
238
 
239
- <b>Model Performance:</b><br>
240
- • Segmentation Dice: {MODEL_METRICS['segmentation']['dice']*100:.1f}%<br>
241
- • Classification Accuracy: {MODEL_METRICS['classification']['overall_accuracy']*100:.1f}%<br><br>
242
-
243
  <b>Detections:</b><br>
244
  """
245
 
@@ -253,7 +284,7 @@ class ForgeryDetector:
253
  color_hex = f"#{color_rgb[0]:02x}{color_rgb[1]:02x}{color_rgb[2]:02x}"
254
 
255
  html += f"""
256
- <div style='margin:8px 0; padding:8px; border-left:3px solid {color_hex}; background:#f9f9f9;'>
257
  <b>Region {i}:</b> {forgery_type} ({confidence*100:.1f}%)<br>
258
  <small>Location: ({bbox[0]}, {bbox[1]}) | Size: {bbox[2]}×{bbox[3]}px</small>
259
  </div>
@@ -274,19 +305,20 @@ def detect_forgery(file):
274
  """Gradio interface function"""
275
  try:
276
  if file is None:
277
- return None, None, "<div style='padding:12px; border:1px solid #d9534f; border-radius:8px;'>❌ <b>No file uploaded.</b></div>"
 
278
 
279
  # Get file path
280
  file_path = file.name if hasattr(file, 'name') else file
281
 
282
  # Check if PDF
283
  if file_path.lower().endswith('.pdf'):
284
- original, overlay, results_html = detector.detect(file_path)
285
  else:
286
  image = Image.open(file_path)
287
- original, overlay, results_html = detector.detect(image)
288
 
289
- return original, overlay, results_html
290
 
291
  except Exception as e:
292
  import traceback
@@ -297,7 +329,7 @@ def detect_forgery(file):
297
  ❌ <b>Error:</b> {str(e)}
298
  </div>
299
  """
300
- return None, None, error_html
301
 
302
 
303
  # Custom CSS - subtle styling
@@ -348,14 +380,17 @@ with gr.Blocks(css=custom_css) as demo:
348
  """
349
  )
350
 
351
- with gr.Column(scale=1):
352
- gr.Markdown("### Original Image")
353
- original_image = gr.Image(label="Uploaded Document", type="numpy")
 
 
354
 
355
  with gr.Row():
356
  with gr.Column(scale=1):
357
- gr.Markdown("### Detection Result")
358
- output_image = gr.Image(label="Annotated Document", type="numpy")
 
359
 
360
  with gr.Column(scale=1):
361
  gr.Markdown("### Analysis Report")
@@ -377,13 +412,13 @@ with gr.Blocks(css=custom_css) as demo:
377
  analyze_btn.click(
378
  fn=detect_forgery,
379
  inputs=[input_file],
380
- outputs=[original_image, output_image, output_html]
381
  )
382
 
383
  clear_btn.click(
384
- fn=lambda: (None, None, None, "<i>No analysis yet. Upload a document and click Analyze.</i>"),
385
  inputs=None,
386
- outputs=[input_file, original_image, output_image, output_html]
387
  )
388
 
389
 
 
13
  from pathlib import Path
14
  import sys
15
  from typing import Dict, List, Tuple
16
+ import plotly.graph_objects as go
17
 
18
  # Add src to path
19
  sys.path.insert(0, str(Path(__file__).parent))
 
53
  }
54
 
55
 
56
+ def create_gauge_chart(value: float, title: str, max_value: float = 1.0) -> go.Figure:
57
+ """Create a subtle radial gauge chart"""
58
+ fig = go.Figure(go.Indicator(
59
+ mode="gauge+number",
60
+ value=value * 100,
61
+ domain={'x': [0, 1], 'y': [0, 1]},
62
+ title={'text': title, 'font': {'size': 14}},
63
+ number={'suffix': '%', 'font': {'size': 24}},
64
+ gauge={
65
+ 'axis': {'range': [0, 100], 'tickwidth': 1},
66
+ 'bar': {'color': '#4169E1', 'thickness': 0.7},
67
+ 'bgcolor': 'rgba(0,0,0,0)',
68
+ 'borderwidth': 0,
69
+ 'steps': [
70
+ {'range': [0, 50], 'color': 'rgba(217, 83, 79, 0.1)'},
71
+ {'range': [50, 75], 'color': 'rgba(240, 173, 78, 0.1)'},
72
+ {'range': [75, 100], 'color': 'rgba(92, 184, 92, 0.1)'}
73
+ ]
74
+ }
75
+ ))
76
+
77
+ fig.update_layout(
78
+ paper_bgcolor='rgba(0,0,0,0)',
79
+ plot_bgcolor='rgba(0,0,0,0)',
80
+ height=200,
81
+ margin=dict(l=20, r=20, t=40, b=20)
82
+ )
83
+
84
+ return fig
85
+
86
+
87
  class ForgeryDetector:
88
  """Main forgery detection pipeline"""
89
 
 
117
  """
118
  Detect forgeries in document image or PDF
119
 
 
 
 
120
  Returns:
121
  original_image: Original uploaded image
122
  overlay_image: Image with detection overlay
123
+ gauge_dice: Dice score gauge
124
+ gauge_accuracy: Accuracy gauge
125
  results_html: Detection results as HTML
126
  """
127
  # Handle PDF files
 
205
  # Create visualization
206
  overlay = self._create_overlay(original_image, results)
207
 
208
+ # Create gauge charts
209
+ gauge_dice = create_gauge_chart(MODEL_METRICS['segmentation']['dice'], 'Segmentation Dice')
210
+ gauge_accuracy = create_gauge_chart(MODEL_METRICS['classification']['overall_accuracy'], 'Classification Accuracy')
211
+
212
  # Create HTML response
213
  results_html = self._create_html_report(results)
214
 
215
+ return original_image, overlay, gauge_dice, gauge_accuracy, results_html
216
 
217
  def _create_overlay(self, image, results):
218
  """Create overlay visualization"""
 
271
  • Regions detected: {num_detections}<br>
272
  • Average confidence: {avg_confidence*100:.1f}%<br><br>
273
 
 
 
 
 
274
  <b>Detections:</b><br>
275
  """
276
 
 
284
  color_hex = f"#{color_rgb[0]:02x}{color_rgb[1]:02x}{color_rgb[2]:02x}"
285
 
286
  html += f"""
287
+ <div style='margin:8px 0; padding:8px; border-left:3px solid {color_hex}; background:rgba(0,0,0,0.02);'>
288
  <b>Region {i}:</b> {forgery_type} ({confidence*100:.1f}%)<br>
289
  <small>Location: ({bbox[0]}, {bbox[1]}) | Size: {bbox[2]}×{bbox[3]}px</small>
290
  </div>
 
305
  """Gradio interface function"""
306
  try:
307
  if file is None:
308
+ empty_html = "<div style='padding:12px; border:1px solid #d9534f; border-radius:8px;'>❌ <b>No file uploaded.</b></div>"
309
+ return None, None, None, None, empty_html
310
 
311
  # Get file path
312
  file_path = file.name if hasattr(file, 'name') else file
313
 
314
  # Check if PDF
315
  if file_path.lower().endswith('.pdf'):
316
+ original, overlay, gauge_dice, gauge_acc, results_html = detector.detect(file_path)
317
  else:
318
  image = Image.open(file_path)
319
+ original, overlay, gauge_dice, gauge_acc, results_html = detector.detect(image)
320
 
321
+ return original, overlay, gauge_dice, gauge_acc, results_html
322
 
323
  except Exception as e:
324
  import traceback
 
329
  ❌ <b>Error:</b> {str(e)}
330
  </div>
331
  """
332
+ return None, None, None, None, error_html
333
 
334
 
335
  # Custom CSS - subtle styling
 
380
  """
381
  )
382
 
383
+ with gr.Column(scale=2):
384
+ gr.Markdown("### Detection Results")
385
+ with gr.Row():
386
+ original_image = gr.Image(label="Original Document", type="numpy")
387
+ output_image = gr.Image(label="Detected Forgeries", type="numpy")
388
 
389
  with gr.Row():
390
  with gr.Column(scale=1):
391
+ gr.Markdown("### Model Performance")
392
+ gauge_dice = gr.Plot(label="Segmentation Dice Score")
393
+ gauge_accuracy = gr.Plot(label="Classification Accuracy")
394
 
395
  with gr.Column(scale=1):
396
  gr.Markdown("### Analysis Report")
 
412
  analyze_btn.click(
413
  fn=detect_forgery,
414
  inputs=[input_file],
415
+ outputs=[original_image, output_image, gauge_dice, gauge_accuracy, output_html]
416
  )
417
 
418
  clear_btn.click(
419
+ fn=lambda: (None, None, None, None, None, "<i>No analysis yet. Upload a document and click Analyze.</i>"),
420
  inputs=None,
421
+ outputs=[input_file, original_image, output_image, gauge_dice, gauge_accuracy, output_html]
422
  )
423
 
424