EmanHassan26 commited on
Commit
53311eb
·
verified ·
1 Parent(s): 0cf89df

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -33
app.py CHANGED
@@ -1,18 +1,24 @@
1
  import gradio as gr
2
  from transformers import pipeline
 
3
 
4
  # 1. Initialize your custom pipeline
5
- # Replace with your exact Hugging Face model ID (e.g., "username/your-model")
6
  model_id = "google/vit-base-patch16-224"
7
  classifier = pipeline("image-classification", model=model_id)
8
 
9
- # 2. Shared prediction function
10
  def predict_image(image, min_confidence):
11
  if image is None:
12
- return {}
13
 
14
- # Run the model
 
15
  predictions = classifier(image)
 
 
 
 
 
16
 
17
  # Filter and format results based on the slider value
18
  filtered_results = {}
@@ -21,35 +27,43 @@ def predict_image(image, min_confidence):
21
  if score >= min_confidence:
22
  filtered_results[pred["label"]] = score
23
 
24
- return filtered_results
25
 
26
- # 3. Custom Gradio Layout with Tabs
27
- with gr.Blocks(title="Advanced Image Classifier") as demo:
28
- gr.Markdown("# 🖼️ Multi-Input Image Classification")
29
- gr.Markdown("Choose your input method, adjust the threshold, and click classify.")
 
 
 
 
 
 
 
 
 
 
30
 
31
  with gr.Row():
32
  with gr.Column(scale=1):
33
 
34
  # --- TABBED INPUT SECTION ---
35
  with gr.Tabs():
36
- with gr.TabItem("Upload File"):
37
- upload_input = gr.Image(type="pil", label="Upload Image")
38
- # We create separate submit buttons per tab for clear UX
39
- submit_upload = gr.Button("Classify Uploaded Image", variant="primary")
 
 
 
40
 
41
- # Examples only apply nicely to the upload field
42
- gr.Examples(
43
- examples=[["example_dog.jpg"], ["example_car.jpg"]],
44
- inputs=upload_input,
45
- label="Click an example to test"
46
- )
47
 
48
- with gr.TabItem("Use Webcam"):
49
- webcam_input = gr.Image(sources=["webcam"], type="pil", label="Take a Snapshot")
50
- submit_webcam = gr.Button("Classify Webcam Image", variant="primary")
51
 
52
- # --- SHARED PARAMETERS ---
53
  threshold_slider = gr.Slider(
54
  minimum=0.0,
55
  maximum=1.0,
@@ -59,22 +73,35 @@ with gr.Blocks(title="Advanced Image Classifier") as demo:
59
  )
60
 
61
  with gr.Column(scale=1):
62
- # --- OUTPUT SECTION ---
63
  output_labels = gr.Label(num_top_classes=5, label="Predictions")
64
 
65
- # 4. Wire up events for both input sources
66
- submit_upload.click(
67
- fn=predict_image,
68
- inputs=[upload_input, threshold_slider],
69
- outputs=output_labels
 
 
 
 
 
70
  )
71
 
72
- submit_webcam.click(
 
 
 
 
 
 
 
 
73
  fn=predict_image,
74
- inputs=[webcam_input, threshold_slider],
75
- outputs=output_labels
76
  )
77
 
78
- # 5. Launch the application
79
  if __name__ == "__main__":
80
  demo.launch()
 
1
  import gradio as gr
2
  from transformers import pipeline
3
+ import time
4
 
5
  # 1. Initialize your custom pipeline
 
6
  model_id = "google/vit-base-patch16-224"
7
  classifier = pipeline("image-classification", model=model_id)
8
 
9
+ # 2. Optimized prediction function that measures latency
10
  def predict_image(image, min_confidence):
11
  if image is None:
12
+ return {}, "0 ms"
13
 
14
+ # Start the clock right before the model processes the frame
15
+ start_time = time.perf_counter()
16
  predictions = classifier(image)
17
+ end_time = time.perf_counter()
18
+
19
+ # Calculate inference latency in milliseconds
20
+ latency_ms = int((end_time - start_time) * 1000)
21
+ latency_text = f"{latency_ms} ms"
22
 
23
  # Filter and format results based on the slider value
24
  filtered_results = {}
 
27
  if score >= min_confidence:
28
  filtered_results[pred["label"]] = score
29
 
30
+ return filtered_results, latency_text
31
 
32
+ # 3. Snapshot utility to save live images
33
+ def save_snapshot(image):
34
+ if image is None:
35
+ return "No image captured to save."
36
+
37
+ # Generate a unique timestamped file name
38
+ filename = f"snapshot_{int(time.time())}.jpg"
39
+ image.save(filename)
40
+ return f"✅ Snapshot successfully saved as '{filename}' inside Space directory!"
41
+
42
+ # 4. Custom Layout Layout
43
+ with gr.Blocks(title="Real-Time Analytics Classifier") as demo:
44
+ gr.Markdown("# ⚡ Real-Time Webcam Analytics")
45
+ gr.Markdown("Stream live video to measure pipeline inference speeds and save high-scoring frames.")
46
 
47
  with gr.Row():
48
  with gr.Column(scale=1):
49
 
50
  # --- TABBED INPUT SECTION ---
51
  with gr.Tabs():
52
+ with gr.TabItem("Live Webcam Stream"):
53
+ webcam_input = gr.Image(sources="webcam", type="pil", label="Live Stream Feed")
54
+
55
+ # Performance tracking row added inside the tab view
56
+ with gr.Row():
57
+ latency_box = gr.Textbox(label="Model Inference Speed", value="0 ms", interactive=False)
58
+ snapshot_btn = gr.Button("📸 Save Current Frame", variant="secondary")
59
 
60
+ snapshot_status = gr.Markdown("") # Status feedback text block
 
 
 
 
 
61
 
62
+ with gr.TabItem("Upload File"):
63
+ upload_input = gr.Image(type="pil", label="Static File Upload")
64
+ submit_upload = gr.Button("Classify Uploaded Image", variant="primary")
65
 
66
+ # --- SHARED CONFIGURATIONS ---
67
  threshold_slider = gr.Slider(
68
  minimum=0.0,
69
  maximum=1.0,
 
73
  )
74
 
75
  with gr.Column(scale=1):
76
+ # --- REAL-TIME LABEL OUTPUT ---
77
  output_labels = gr.Label(num_top_classes=5, label="Predictions")
78
 
79
+ # 5. --- LIVE EVENT ROUTING ---
80
+
81
+ # Live streaming updates predictions and latency counters concurrently
82
+ webcam_input.stream(
83
+ fn=predict_image,
84
+ inputs=[webcam_input, threshold_slider],
85
+ outputs=[output_labels, latency_box],
86
+ stream_every=0.2,
87
+ time_limit=300,
88
+ concurrency_limit=5
89
  )
90
 
91
+ # Saves a snapshot of whatever is currently on screen
92
+ snapshot_btn.click(
93
+ fn=save_snapshot,
94
+ inputs=[webcam_input],
95
+ outputs=[snapshot_status]
96
+ )
97
+
98
+ # Manual submit routing for standard file uploads
99
+ submit_upload.click(
100
  fn=predict_image,
101
+ inputs=[upload_input, threshold_slider],
102
+ outputs=[output_labels, latency_box]
103
  )
104
 
105
+ # 6. Launch the application
106
  if __name__ == "__main__":
107
  demo.launch()