Preyanshz commited on
Commit
b0fdc1a
·
verified ·
1 Parent(s): 9bfe85b

Update app.py

Browse files

added Progress bar, ETA and multiple images in Inference tool

Files changed (1) hide show
  1. app.py +68 -55
app.py CHANGED
@@ -17,73 +17,86 @@ def yolo_inference_tool():
17
  Single-model, single-image inference subpage (example).
18
  """
19
  st.header("YOLO Model Inference Tool")
20
- st.write("Upload an image and a YOLO model (.pt) file to run inference and view detailed results.")
21
-
22
- image_file = st.file_uploader("Upload Image", type=["jpg", "jpeg", "png"], key="inference_image")
 
23
  model_file = st.file_uploader("Upload YOLO model (.pt)", type=["pt"], key="inference_model")
24
-
25
  if st.button("Submit (Single-Model Inference)"):
26
- if not image_file or not model_file:
27
- st.error("Please upload both an image and a model.")
28
  return
29
 
30
- # Save files
31
- image_path = save_uploaded_file(image_file)
32
  model_path = save_uploaded_file(model_file)
33
-
34
- # Load image
35
- try:
36
- image = Image.open(image_file).convert("RGB")
37
- except Exception as e:
38
- st.error(f"Error reading image: {e}")
39
- return
40
-
41
- st.subheader("Image Details")
42
- st.write(f"**Image Size:** {image.size[0]} x {image.size[1]}")
43
- st.write(f"**File Type:** {image_file.type}")
44
-
45
- # Load model
46
  try:
47
  model = YOLO(model_path)
48
  except Exception as e:
49
  st.error(f"Error loading model: {e}")
50
  return
51
 
52
- # Inference
53
- st.subheader("Inference Results")
54
- try:
55
- results = model(np.array(image))
56
- except Exception as e:
57
- st.error(f"Inference error: {e}")
58
- return
59
 
60
- r = results[0]
61
- boxes_data = []
62
- if r.boxes is not None and len(r.boxes) > 0:
63
- for i in range(len(r.boxes)):
64
- coords = r.boxes.xyxy[i].cpu().numpy() if hasattr(r.boxes.xyxy[i], "cpu") else r.boxes.xyxy[i]
65
- conf = r.boxes.conf[i].cpu().numpy() if hasattr(r.boxes.conf[i], "cpu") else r.boxes.conf[i]
66
- cls_idx = int(r.boxes.cls[i].cpu().numpy()) if hasattr(r.boxes.cls[i], "cpu") else int(r.boxes.cls[i])
67
- class_name = r.names.get(cls_idx, "Unknown")
68
- boxes_data.append({
69
- "Box": i + 1,
70
- "Coordinates": f"[{coords[0]:.1f}, {coords[1]:.1f}, {coords[2]:.1f}, {coords[3]:.1f}]",
71
- "Confidence": f"{conf:.2f}",
72
- "Class": class_name
73
- })
74
- df_boxes = pd.DataFrame(boxes_data)
75
- st.subheader("Detected Objects")
76
- st.dataframe(df_boxes, use_container_width=True)
77
- else:
78
- st.write("No objects detected.")
79
-
80
- # Annotated image
81
- try:
82
- annotated_img_pil = r.plot(conf=True, boxes=True, labels=True, pil=True)
83
- st.subheader("Annotated Image")
84
- st.image(annotated_img_pil, caption="Inference Output", use_container_width=True)
85
- except Exception as e:
86
- st.error(f"Error generating annotated image: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
 
88
  def yolo_model_comparison_tool():
89
  """
 
17
  Single-model, single-image inference subpage (example).
18
  """
19
  st.header("YOLO Model Inference Tool")
20
+ st.write("Upload one or more images and a YOLO model (.pt) file to run inference and view detailed results.")
21
+
22
+ # Allow multiple images upload
23
+ images = st.file_uploader("Upload Images", type=["jpg", "jpeg", "png"], key="inference_images", accept_multiple_files=True)
24
  model_file = st.file_uploader("Upload YOLO model (.pt)", type=["pt"], key="inference_model")
25
+
26
  if st.button("Submit (Single-Model Inference)"):
27
+ if not images or not model_file:
28
+ st.error("Please upload at least one image and a model.")
29
  return
30
 
31
+ # Save and load the model file
 
32
  model_path = save_uploaded_file(model_file)
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  try:
34
  model = YOLO(model_path)
35
  except Exception as e:
36
  st.error(f"Error loading model: {e}")
37
  return
38
 
39
+ total_images = len(images)
40
+ progress_bar = st.progress(0)
41
+ eta_placeholder = st.empty()
42
+ start_time = time.time()
43
+ steps_done = 0
 
 
44
 
45
+ # Dictionaries to store inference results and metrics
46
+ image_results = {}
47
+ metrics = []
48
+
49
+ for img_file in images:
50
+ steps_done += 1
51
+ fraction_done = steps_done / total_images
52
+ progress_bar.progress(fraction_done)
53
+
54
+ elapsed_time = time.time() - start_time
55
+ time_per_step = elapsed_time / steps_done
56
+ remaining_steps = total_images - steps_done
57
+ eta_seconds = remaining_steps * time_per_step
58
+ eta_placeholder.info(f"Progress: {fraction_done:.1%}. ETA: ~{eta_seconds:.1f} s")
59
+
60
+ try:
61
+ pil_img = Image.open(img_file).convert("RGB")
62
+ except Exception as e:
63
+ st.error(f"Error reading image {img_file.name}: {e}")
64
+ continue
65
+
66
+ try:
67
+ result = model(np.array(pil_img))
68
+ except Exception as e:
69
+ st.error(f"Inference error on image {img_file.name}: {e}")
70
+ continue
71
+
72
+ r = result[0]
73
+ image_results[img_file.name] = r
74
+
75
+ # Collect basic metrics if available (e.g., inference time and detections)
76
+ inference_time = r.speed.get('inference', None) if isinstance(r.speed, dict) else None
77
+ detection_count = len(r.boxes) if r.boxes is not None else 0
78
+ metrics.append({
79
+ "Image": img_file.name,
80
+ "Inference Time (ms)": inference_time if inference_time is not None else "N/A",
81
+ "Detections": detection_count
82
+ })
83
+
84
+ eta_placeholder.empty()
85
+
86
+ # Display per-image metrics if collected
87
+ st.subheader("Inference Metrics")
88
+ if metrics:
89
+ df_metrics = pd.DataFrame(metrics)
90
+ st.dataframe(df_metrics, use_container_width=True)
91
+
92
+ # Display annotated images (using pil=True to ensure RGB output)
93
+ st.subheader("Annotated Images")
94
+ for img_name, r in image_results.items():
95
+ try:
96
+ annotated_img = r.plot(conf=True, boxes=True, labels=True, pil=True)
97
+ st.image(annotated_img, caption=img_name, use_container_width=True)
98
+ except Exception as e:
99
+ st.error(f"Error generating annotated image for {img_name}: {e}")
100
 
101
  def yolo_model_comparison_tool():
102
  """