File size: 10,134 Bytes
c70e012
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4d1a283
 
c70e012
c566fa5
 
 
 
 
 
 
 
 
 
 
c70e012
 
c566fa5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4d1a283
 
bc42890
4d1a283
 
 
c70e012
bb9a613
4d1a283
c566fa5
c70e012
c566fa5
 
 
c70e012
c566fa5
 
c70e012
c566fa5
 
 
 
 
 
 
 
 
4d1a283
 
c566fa5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c70e012
38d3d04
c566fa5
38d3d04
c566fa5
38d3d04
c566fa5
 
c70e012
38d3d04
 
c70e012
c566fa5
 
 
 
 
 
 
 
 
 
 
 
c70e012
c566fa5
 
 
 
 
4d1a283
 
c566fa5
10b2c2b
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
# import gradio as gr
# from ultralytics import YOLO
# import os
# import torch

# # --- DOCUMENTATION STRINGS (Coin Detector App) ---

# GUIDELINE_SETUP = """
# ## 1. Quick Start Guide: Detection and Filtering

# This application uses a trained YOLO model to automatically detect coins in an image and allows you to filter the results based on detection confidence.

# 1.  **Upload Image:** Upload the image you want to analyze in the 'Input Image' box.
# 2.  **Adjust Threshold:** Use the 'Confidence Threshold' slider to set the minimum certainty required for a coin to be displayed.
# 3.  **Review:** The output image will show bounding boxes around all detections that meet or exceed the set threshold.
# """

# GUIDELINE_INPUT = """
# ## 2. Expected Inputs and Parameters

# | Input Field | Purpose | Requirement |
# | :--- | :--- | :--- |
# | **Input Image** | The photograph containing the coins you wish to detect. | Must be an image file (e.g., JPG, PNG). |
# | **Confidence Threshold** | Filters the model's predictions. Only detections with a confidence score equal to or higher than this value will be shown. | Slider range: 0.0 (least strict) to 1.0 (most strict). Default is 0.5. |

# **Tip:** If you see too many false positives (non-coins being detected), raise the threshold. If the model misses coins you know are there, try lowering the threshold.
# """

# GUIDELINE_OUTPUT = """
# ## 3. Expected Outputs (Annotated Image)

# The output is a single image component displaying the **Annotated Frame**.

# *   **Content:** This image is the original input image with colored bounding boxes drawn around every coin detected by the model that passed the `Confidence Threshold` filter.
# *   **Bounding Boxes:** Each box confirms a coin detection and is usually accompanied by a label (e.g., 'coin') and the confidence score (e.g., 0.95).
# """

# # Load the YOLO model
# # NOTE: The model file 'best1.pt' must exist in the same directory or accessible path.
# model = YOLO('best1.pt')

# def predict(img, confidence_threshold):
#     # Perform inference
#     # Note: Using verbose=False to keep the interface clean during prediction
#     results = model(img, verbose=False) 
    
#     # Filter predictions based on the confidence threshold
#     # The results[0].boxes.data contains the detection results, including confidence scores
    
#     # We filter the bounding boxes data array based on the confidence score (index 4)
#     # Then we must convert the filtered list back to a tensor format expected by the plotting function.
    
#     filtered_data = [box.cpu() for box in results[0].boxes.data if box[4] >= confidence_threshold]
    
#     if filtered_data:
#         filtered_tensor = torch.stack(filtered_data)
        
#         # Create a deep copy of the original results object to manipulate its boxes data
#         filtered_results = results[0].cpu()
#         filtered_results.boxes.data = filtered_tensor
        
#         # Plot the results using the filtered results object
#         annotated_frame = filtered_results.plot()
#     else:
#         # If no coins pass the filter, plot the original image without boxes
#         annotated_frame = results[0].plot()
        
#     return annotated_frame

# # Create the Gradio interface using gr.Blocks to allow for documentation placement
# with gr.Blocks(title="Coin Detector") as iface:
    
#     gr.Markdown("# Coin Detector")
#     gr.Markdown("Upload an image to detect coins. Adjust the confidence threshold to filter results.")
    
#     # 1. Guidelines Section
#     with gr.Accordion("User Guidelines and Documentation", open=False):
#         gr.Markdown(GUIDELINE_SETUP)
#         gr.Markdown("---")
#         gr.Markdown(GUIDELINE_INPUT)
#         gr.Markdown("---")
#         gr.Markdown(GUIDELINE_OUTPUT)
        
#     gr.Markdown("---")

#     # 2. Input/Output Layout
#     with gr.Row():
#         with gr.Column(scale=2):
#             gr.Markdown("## Step 1: Upload an Image ")
#             input_img = gr.Image(label="Input Image", type="filepath")
#             gr.Markdown("## Step 2: Adjest Confidence Threshold (Optional) ")
#             confidence_slider = gr.Slider(minimum=0, maximum=1, value=0.5, label="Confidence Threshold", step=0.01)
#             gr.Markdown("## Step 3: Click Detect Coins ")
#             submit_btn = gr.Button("Detect Coins", variant="primary")
            
#         with gr.Column(scale=1):
#             gr.Markdown("## Result ")
#             output_img = gr.Image(label="Output Image")

#     # 3. Example Data (if available, added here for completeness)
#     # Note: Since no examples were provided, this is commented out or left as placeholders.
#     gr.Markdown("## Examples ")
#     gr.Examples(
#         examples=[["./sample_data/coin.jpeg", 0.5], ["./sample_data/Test21.png", 0.4]],
#         inputs=[input_img, confidence_slider],
#         outputs=output_img,
#         fn=predict,
#         cache_examples=False
#     )

#     # 4. Event Handler
#     submit_btn.click(
#         fn=predict,
#         inputs=[input_img, confidence_slider],
#         outputs=output_img
#     )

# # Launch the Gradio interface
# iface.queue()
# iface.launch(share=True)



import gradio as gr
from ultralytics import YOLO
import torch 
import os

# --- DOCUMENTATION STRINGS (Coin Detector App) ---

GUIDELINE_SETUP = """
## 1. Quick Start Guide: Detection and Filtering

This application uses a trained YOLO model to automatically detect coins in an image and allows you to filter the results based on detection confidence.

1.  **Upload Image:** Upload the image you want to analyze in the 'Input Image' box.
2.  **Adjust Threshold:** Use the 'Confidence Threshold' slider to set the minimum certainty required for a coin to be displayed.
3.  **Run:** Click the **"Detect Coins"** button.
4.  **Review:** The output image will show bounding boxes around all detections that meet or exceed the set threshold.
"""

GUIDELINE_INPUT = """
## 2. Expected Inputs and Parameters

| Input Field | Purpose | Requirement |
| :--- | :--- | :--- |
| **Input Image** | The photograph containing the coins you wish to detect. | Must be an image file (e.g., JPG, PNG). |
| **Confidence Threshold** | Filters the model's predictions. Only detections with a confidence score equal to or higher than this value will be shown. | Slider range: 0.0 (least strict) to 1.0 (most strict). Default is 0.5. |

**Tip:** If you see too many false positives (non-coins being detected), raise the threshold. If the model misses coins you know are there, try lowering the threshold.
"""

GUIDELINE_OUTPUT = """
## 3. Expected Outputs (Annotated Image)

The output is a single image component displaying the **Annotated Frame**.

*   **Content:** This image is the original input image with colored bounding boxes drawn around every coin detected by the model that passed the `Confidence Threshold` filter.
*   **Bounding Boxes:** Each box confirms a coin detection and is usually accompanied by a label (e.g., 'coin') and the confidence score (e.g., 0.95).
"""

# Load the YOLO model
model = YOLO('best1.pt')

def predict(img, confidence_threshold):
    # Perform inference
    # Using verbose=False to suppress unnecessary console output during inference
    results = model(img, verbose=True) 
    
    # We filter the bounding boxes data array based on the confidence score (index 4)
    # Filter predictions based on the confidence threshold
    filtered_data = [box.cpu() for box in results[0].boxes.data if box[4] >= confidence_threshold]
    
    if filtered_data:
        # Stack the filtered tensors back into a single tensor
        filtered_tensor = torch.stack(filtered_data)
        
        # Create a results object to plot only the filtered boxes
        filtered_results = results[0].cpu()
        filtered_results.boxes.data = filtered_tensor
        
        # Plot the results using the filtered results object
        annotated_frame = filtered_results.plot()
    else:
        # If no coins pass the filter, plot the original image without boxes
        annotated_frame = results[0].plot()
        
    return annotated_frame

# Create the Gradio interface using gr.Blocks to allow for documentation placement
with gr.Blocks(title="Coin Detector") as iface:
    
    gr.Markdown("# Coin Detector")
    gr.Markdown("Upload an image to detect coins. Adjust the confidence threshold to filter results.")
    
    # 1. Guidelines Section
    with gr.Accordion("User Guidelines and Documentation", open=False):
        gr.Markdown(GUIDELINE_SETUP)
        gr.Markdown("---")
        gr.Markdown(GUIDELINE_INPUT)
        gr.Markdown("---")
        gr.Markdown(GUIDELINE_OUTPUT)
        
    gr.Markdown("---")

    # 2. Input/Output Layout
    with gr.Row():
        with gr.Column(scale=1):
            gr.Markdown("## Step 1: Upload an Image Having Coin")
            input_img = gr.Image(label="Input Image", type="filepath")
            gr.Markdown("## Step 2: Set the Confidence Threshold (Optional) ")
            confidence_slider = gr.Slider(minimum=0, maximum=1, value=0.5, label="Confidence Threshold", step=0.01)
            gr.Markdown("## Step 3: Click Detect Coins Button")
            submit_btn = gr.Button("Detect Coins", variant="primary")
            
        with gr.Column(scale=2):
            gr.Markdown("## Result ")
            output_img = gr.Image(label="Detected Coins ")


    # 3. Example Data (if available, added here for completeness)
    # Note: Since no examples were provided, this is commented out or left as placeholders.
    gr.Markdown("## Examples ")
    gr.Examples(
        examples=[["./sample_data/coin.jpeg", 0.5], ["./sample_data/Test21.png", 0.4]],
        inputs=[input_img, confidence_slider],
        outputs=output_img,
        fn=predict,
        cache_examples=False
    )

    # 3. Event Handler
    submit_btn.click(
        fn=predict,
        inputs=[input_img, confidence_slider],
        outputs=output_img
    )

# Launch the Gradio interface
iface.queue()
iface.launch(
    server_name="0.0.0.0",
    server_port=7860,
    share=True
)