File size: 11,053 Bytes
ace7187
 
 
 
a285eb6
ace7187
a285eb6
e17c6a5
eaa7aa4
 
e17c6a5
b6c3e5f
e17c6a5
 
 
 
b6c3e5f
e17c6a5
 
b6c3e5f
371a8c3
 
 
 
 
 
 
 
b6c3e5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53fda1d
 
 
 
 
371a8c3
 
a285eb6
b6c3e5f
53fda1d
b6c3e5f
 
 
 
8c88f9c
1b1427d
 
 
 
b6c3e5f
 
8c88f9c
 
 
b6c3e5f
 
 
4014f2e
b6c3e5f
 
 
 
ca0a0e9
b6c3e5f
 
 
 
53fda1d
 
b6c3e5f
 
a285eb6
 
53fda1d
ace7187
 
 
a285eb6
ace7187
 
 
53fda1d
ace7187
 
 
 
 
 
371a8c3
b6c3e5f
 
371a8c3
b6c3e5f
371a8c3
34097f1
371a8c3
a285eb6
34097f1
5eed01e
 
 
 
 
 
 
 
 
 
 
34097f1
 
 
 
a285eb6
b6c3e5f
a285eb6
951da42
 
 
371a8c3
 
b6c3e5f
a285eb6
b6c3e5f
a285eb6
 
ace7187
a285eb6
ace7187
a285eb6
ace7187
 
a285eb6
ace7187
a285eb6
ace7187
 
 
 
a285eb6
ace7187
a285eb6
ace7187
b6c3e5f
 
 
 
 
 
 
a285eb6
 
b6c3e5f
 
 
 
 
 
a285eb6
 
b6c3e5f
 
 
a285eb6
b6c3e5f
a285eb6
b6c3e5f
a285eb6
b6c3e5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a285eb6
371a8c3
a285eb6
371a8c3
b6c3e5f
a285eb6
53fda1d
 
a285eb6
53fda1d
 
 
 
a285eb6
53fda1d
 
 
371a8c3
b6c3e5f
951da42
b6c3e5f
 
 
a285eb6
951da42
a285eb6
951da42
a285eb6
 
 
 
 
 
951da42
a285eb6
b44b79d
b6c3e5f
 
a285eb6
b6c3e5f
 
 
ace7187
 
b6c3e5f
ace7187
b6c3e5f
 
53fda1d
 
 
 
 
 
 
 
371a8c3
b6c3e5f
ace7187
 
 
53fda1d
 
 
 
 
 
 
 
ace7187
 
4014f2e
 
 
 
53fda1d
 
 
 
 
 
 
 
4014f2e
a285eb6
e17c6a5
 
b6c3e5f
e17c6a5
485b371
 
a285eb6
e17c6a5
60b9dfe
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
import os

import gradio as gr
import pandas as pd
import matplotlib.pyplot as plt
from PIL import Image
from typing import Tuple, List

from constants import MODEL_PATH, DATABASE_DIR, DATABASE_PATH
from detector import SignatureDetector, download_model


def create_gradio_interface():
    # Download model if it doesn't exist
    if not os.path.exists(MODEL_PATH):
        download_model()

    # Initialize the detector
    detector = SignatureDetector(MODEL_PATH)

    css = """
    .custom-button {
        background-color: #b0ffb8 !important;
        color: black !important;
    }
    .custom-button:hover {
        background-color: #b0ffb8b3 !important;
    }
    .container {
        max-width: 1200px !important;
        margin: auto !important;
    }
    .main-container {
        gap: 20px !important;
    }
    .metrics-container {
        padding: 1.5rem !important;
        border-radius: 0.75rem !important;
        background-color: #1f2937 !important;
        margin: 1rem 0 !important;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1) !important;
    }
    .metrics-title {
        font-size: 1.25rem !important;
        font-weight: 600 !important;
        color: #1f2937 !important;
        margin-bottom: 1rem !important;
    }
    .metrics-row {
        display: flex !important;
        gap: 1rem !important;
        margin-top: 0.5rem !important;
    }
    """

    def process_image(image: Image.Image, conf_thres: float, iou_thres: float) -> Tuple[Image.Image, str, plt.Figure, plt.Figure, str, str]:
        if image is None:
            return None, None, None, None, None, None

        output_image, metrics = detector.detect(image, conf_thres, iou_thres)

        # Create plots data
        hist_data = pd.DataFrame({"Time (ms)": metrics["times"]})
        indices = range(
            metrics["start_index"], metrics["start_index"] + len(metrics["times"])
        )

        line_data = pd.DataFrame(
            {
                "Inference": indices,
                "Time (ms)": metrics["times"],
                "Mean": [metrics["avg_time"]] * len(metrics["times"]),
            }
        )

        hist_fig, line_fig = detector.create_plots(hist_data, line_data)

        return (
            output_image,
            gr.update(
                value=f"{metrics['total_inferences']}",
                container=True,
            ),
            hist_fig,
            line_fig,
            f"{metrics['avg_time']:.2f}",
            f"{metrics['times'][-1]:.2f}",
        )

    def process_folder(files_paths: List[str], conf_thres: float, iou_thres: float):
        if not files_paths:
            return None, None, None, None, None, None

        valid_extensions = [".jpg", ".jpeg", ".png"]
        image_files = [
            f for f in files_paths if os.path.splitext(f.lower())[1] in valid_extensions
        ]

        if not image_files:
            return None, None, None, None, None, None

        for img_file in image_files:
            image = Image.open(img_file)

            yield process_image(image, conf_thres, iou_thres)

    with gr.Blocks(
        theme=gr.themes.Soft(
            primary_hue="indigo", secondary_hue="gray", neutral_hue="gray"
        ),
        css=css,
    ) as iface:
        gr.HTML(
            """
            <h1>Tech4Humans - Signature Detector</h1>
    
            <div style="display: flex; align-items: center; gap: 10px;">
                <a href="https://huggingface.co/tech4humans/yolov8s-signature-detector">
                    <img src="https://huggingface.co/datasets/huggingface/badges/resolve/main/model-on-hf-md-dark.svg" alt="Model on HF">
                </a>
                <a href="https://huggingface.co/datasets/tech4humans/signature-detection">
                    <img src="https://huggingface.co/datasets/huggingface/badges/resolve/main/dataset-on-hf-md-dark.svg" alt="Dataset on HF">
                </a>
                <a href="https://github.com/tech4ai/t4ai-signature-detect-server">
                    <img src="https://img.shields.io/badge/github-%23121011.svg?style=for-the-badge&logo=github&logoColor=white" alt="GitHub">
                </a>
            </div>
            """
        )
        gr.Markdown(
            """
            This system uses the [**YOLOv8s**](https://huggingface.co/tech4humans/yolov8s-signature-detector) model, specially fine-tuned for detecting handwritten signatures in document images.
           
            With this detector, it is possible to identify signatures in digital documents with high accuracy in real time, making it ideal for applications involving validation, organization, and document processing.
            
            ---
            """
        )

        with gr.Row(equal_height=True, elem_classes="main-container"):
            # Left column for controls and information
            with gr.Column(scale=1):
                with gr.Tab("Single Image"):
                    input_image = gr.Image(label="Upload your document", type="pil")
                    with gr.Row():
                        clear_single_btn = gr.ClearButton([input_image], value="Clear")
                        detect_single_btn = gr.Button(
                            "Detect", elem_classes="custom-button"
                        )

                with gr.Tab("Image Folder"):
                    input_folder = gr.File(
                        label="Upload a folder with images",
                        file_count="directory",
                        type="filepath",
                    )
                    with gr.Row():
                        clear_folder_btn = gr.ClearButton([input_folder], value="Clear")
                        detect_folder_btn = gr.Button(
                            "Detect", elem_classes="custom-button"
                        )

                with gr.Group():
                    confidence_threshold = gr.Slider(
                        minimum=0.0,
                        maximum=1.0,
                        value=0.25,
                        step=0.05,
                        label="Confidence Threshold",
                        info="Adjust the minimum confidence score required for detection.",
                    )
                    iou_threshold = gr.Slider(
                        minimum=0.0,
                        maximum=1.0,
                        value=0.5,
                        step=0.05,
                        label="IoU Threshold",
                        info="Adjust the Intersection over Union threshold for Non-Maximum Suppression (NMS).",
                    )

            with gr.Column(scale=1):
                output_image = gr.Image(label="Detection Results")

                with gr.Accordion("Examples", open=True):
                    gr.Examples(
                        label="Image Examples",
                        examples=[
                            ["assets/images/example_{i}.jpg".format(i=i)]
                            for i in range(
                                0, len(os.listdir(os.path.join("assets", "images")))
                            )
                        ],
                        inputs=input_image,
                        outputs=output_image,
                        fn=detector.detect_example,
                        cache_examples=True,
                        cache_mode="lazy",
                    )

        with gr.Row(elem_classes="metrics-container"):
            with gr.Column(scale=1):
                total_inferences = gr.Textbox(
                    label="Total Inferences", show_copy_button=True, container=True
                )
                hist_plot = gr.Plot(label="Time Distribution", container=True)

            with gr.Column(scale=1):
                line_plot = gr.Plot(label="Time History", container=True)
                with gr.Row(elem_classes="metrics-row"):
                    avg_inference_time = gr.Textbox(
                        label="Average Inference Time (ms)",
                        show_copy_button=True,
                        container=True,
                    )
                    last_inference_time = gr.Textbox(
                        label="Last Inference Time (ms)",
                        show_copy_button=True,
                        container=True,
                    )

        with gr.Row(elem_classes="container"):

            gr.Markdown(
                """
                ---
                ## About the Project

                This project uses the YOLOv8s model fine-tuned for detecting handwritten signatures in document images. It was trained with data from the [Tobacco800](https://paperswithcode.com/dataset/tobacco-800) and [signatures-xc8up](https://universe.roboflow.com/roboflow-100/signatures-xc8up) datasets, undergoing preprocessing and data augmentation processes.

                ### Key Metrics:
                - **Precision:** 94.74%
                - **Recall:** 89.72%
                - **mAP@50:** 94.50%
                - **mAP@50-95:** 67.35%
                - **Inference Time (CPU):** 171.56 ms

                Complete details on the training process, hyperparameter tuning, model evaluation, dataset creation, and inference server can be found in the links below.
                
                ---

                **Developed by [Tech4Humans](https://www.tech4h.com.br/)** | **Model:** [YOLOv8s](https://huggingface.co/tech4humans/yolov8s-signature-detector) | **Dataset:** [Tobacco800 + signatures-xc8up](https://huggingface.co/datasets/tech4humans/signature-detection)
                """
            )

        clear_single_btn.add([output_image])
        clear_folder_btn.add([output_image])

        detect_single_btn.click(
            fn=process_image,
            inputs=[input_image, confidence_threshold, iou_threshold],
            outputs=[
                output_image,
                total_inferences,
                hist_plot,
                line_plot,
                avg_inference_time,
                last_inference_time,
            ],
        )

        detect_folder_btn.click(
            fn=process_folder,
            inputs=[input_folder, confidence_threshold, iou_threshold],
            outputs=[
                output_image,
                total_inferences,
                hist_plot,
                line_plot,
                avg_inference_time,
                last_inference_time,
            ],
        )

        # Carregar métricas iniciais ao carregar a página
        iface.load(
            fn=detector.load_initial_metrics,
            inputs=None,
            outputs=[
                output_image,
                total_inferences,
                hist_plot,
                line_plot,
                avg_inference_time,
                last_inference_time,
            ],
        )
    
    return iface


if __name__ == "__main__":
    if not os.path.exists(DATABASE_PATH):
        os.makedirs(DATABASE_DIR, exist_ok=True)
    
    iface = create_gradio_interface()
    iface.launch(ssr_mode=False)