samuellimabraz commited on
Commit
a285eb6
·
unverified ·
1 Parent(s): 223da1b

feat: Add typings and english translation

Browse files
Files changed (1) hide show
  1. app.py +42 -45
app.py CHANGED
@@ -2,7 +2,9 @@ import os
2
 
3
  import gradio as gr
4
  import pandas as pd
 
5
  from PIL import Image
 
6
 
7
  from constants import MODEL_PATH, DATABASE_DIR, DATABASE_PATH
8
  from detector import SignatureDetector, download_model
@@ -51,7 +53,7 @@ def create_gradio_interface():
51
  }
52
  """
53
 
54
- def process_image(image, conf_thres, iou_thres):
55
  if image is None:
56
  return None, None, None, None, None, None
57
 
@@ -86,13 +88,13 @@ def create_gradio_interface():
86
  f"{metrics['times'][-1]:.2f}",
87
  )
88
 
89
- def process_folder(files_path, conf_thres, iou_thres):
90
- if not files_path:
91
  return None, None, None, None, None, None
92
 
93
  valid_extensions = [".jpg", ".jpeg", ".png"]
94
  image_files = [
95
- f for f in files_path if os.path.splitext(f.lower())[1] in valid_extensions
96
  ]
97
 
98
  if not image_files:
@@ -111,7 +113,7 @@ def create_gradio_interface():
111
  ) as iface:
112
  gr.HTML(
113
  """
114
- <h1>Tech4Humans - Detector de Assinaturas</h1>
115
 
116
  <div style="display: flex; align-items: center; gap: 10px;">
117
  <a href="https://huggingface.co/tech4humans/yolov8s-signature-detector">
@@ -128,40 +130,35 @@ def create_gradio_interface():
128
  )
129
  gr.Markdown(
130
  """
131
- Este sistema utiliza o modelo [**YOLOv8s**](https://huggingface.co/tech4humans/yolov8s-signature-detector), especialmente ajustado para a detecção de assinaturas manuscritas em imagens de documentos.
132
 
133
- Com este detector, é possível identificar assinaturas em documentos digitais com elevada precisão em tempo real, sendo ideal para
134
- aplicações que envolvem validação, organização e processamento de documentos.
135
 
136
  ---
137
  """
138
  )
139
 
140
  with gr.Row(equal_height=True, elem_classes="main-container"):
141
- # Coluna da esquerda para controles e informações
142
  with gr.Column(scale=1):
143
- with gr.Tab("Imagem Única"):
144
- input_image = gr.Image(
145
- label="Faça o upload do seu documento", type="pil"
146
- )
147
  with gr.Row():
148
- clear_single_btn = gr.ClearButton([input_image], value="Limpar")
149
  detect_single_btn = gr.Button(
150
- "Detectar", elem_classes="custom-button"
151
  )
152
 
153
- with gr.Tab("Pasta de Imagens"):
154
  input_folder = gr.File(
155
- label="Faça o upload de uma pasta com imagens",
156
  file_count="directory",
157
  type="filepath",
158
  )
159
  with gr.Row():
160
- clear_folder_btn = gr.ClearButton(
161
- [input_folder], value="Limpar"
162
- )
163
  detect_folder_btn = gr.Button(
164
- "Detectar", elem_classes="custom-button"
165
  )
166
 
167
  with gr.Group():
@@ -170,24 +167,24 @@ def create_gradio_interface():
170
  maximum=1.0,
171
  value=0.25,
172
  step=0.05,
173
- label="Limiar de Confiança",
174
- info="Ajuste a pontuação mínima de confiança necessária para detecção.",
175
  )
176
  iou_threshold = gr.Slider(
177
  minimum=0.0,
178
  maximum=1.0,
179
  value=0.5,
180
  step=0.05,
181
- label="Limiar de IoU",
182
- info="Ajuste o limiar de Interseção sobre União para Non Maximum Suppression (NMS).",
183
  )
184
 
185
  with gr.Column(scale=1):
186
- output_image = gr.Image(label="Resultados da Detecção")
187
 
188
- with gr.Accordion("Exemplos", open=True):
189
  gr.Examples(
190
- label="Exemplos de Imagens",
191
  examples=[
192
  ["assets/images/example_{i}.jpg".format(i=i)]
193
  for i in range(
@@ -204,20 +201,20 @@ def create_gradio_interface():
204
  with gr.Row(elem_classes="metrics-container"):
205
  with gr.Column(scale=1):
206
  total_inferences = gr.Textbox(
207
- label="Total de Inferências", show_copy_button=True, container=True
208
  )
209
- hist_plot = gr.Plot(label="Distribuição dos Tempos", container=True)
210
 
211
  with gr.Column(scale=1):
212
- line_plot = gr.Plot(label="Histórico de Tempos", container=True)
213
  with gr.Row(elem_classes="metrics-row"):
214
  avg_inference_time = gr.Textbox(
215
- label="Tempo Médio de Inferência (ms)",
216
  show_copy_button=True,
217
  container=True,
218
  )
219
  last_inference_time = gr.Textbox(
220
- label="Último Tempo de Inferência (ms)",
221
  show_copy_button=True,
222
  container=True,
223
  )
@@ -227,22 +224,22 @@ def create_gradio_interface():
227
  gr.Markdown(
228
  """
229
  ---
230
- ## Sobre o Projeto
231
 
232
- Este projeto utiliza o modelo YOLOv8s ajustado para detecção de assinaturas manuscritas em imagens de documentos. Ele foi treinado com dados provenientes dos conjuntos [Tobacco800](https://paperswithcode.com/dataset/tobacco-800) e [signatures-xc8up](https://universe.roboflow.com/roboflow-100/signatures-xc8up), passando por processos de pré-processamento e aumentação de dados.
233
 
234
- ### Principais Métricas:
235
- - **Precisão (Precision):** 94,74%
236
- - **Revocação (Recall):** 89,72%
237
- - **mAP@50:** 94,50%
238
- - **mAP@50-95:** 67,35%
239
- - **Tempo de Inferência (CPU):** 171,56 ms
240
 
241
- Os detalhes completos sobre os processos de treinamento, ajuste de hiperparâmetros, avaliação do modelo, construção do dataset e servidor de inferência podem ser consultados nos links abaixo.
242
 
243
  ---
244
 
245
- **Desenvolvido por [Tech4Humans](https://www.tech4h.com.br/)** | **Modelo:** [YOLOv8s](https://huggingface.co/tech4humans/yolov8s-signature-detector) | **Datasets:** [Tobacco800](https://paperswithcode.com/dataset/tobacco-800), [signatures-xc8up](https://universe.roboflow.com/roboflow-100/signatures-xc8up)
246
  """
247
  )
248
 
@@ -288,13 +285,13 @@ def create_gradio_interface():
288
  last_inference_time,
289
  ],
290
  )
291
-
292
  return iface
293
 
294
 
295
  if __name__ == "__main__":
296
  if not os.path.exists(DATABASE_PATH):
297
  os.makedirs(DATABASE_DIR, exist_ok=True)
298
-
299
  iface = create_gradio_interface()
300
  iface.launch()
 
2
 
3
  import gradio as gr
4
  import pandas as pd
5
+ import matplotlib.pyplot as plt
6
  from PIL import Image
7
+ from typing import Tuple, List
8
 
9
  from constants import MODEL_PATH, DATABASE_DIR, DATABASE_PATH
10
  from detector import SignatureDetector, download_model
 
53
  }
54
  """
55
 
56
+ def process_image(image: Image.Image, conf_thres: float, iou_thres: float) -> Tuple[Image.Image, str, plt.Figure, plt.Figure, str, str]:
57
  if image is None:
58
  return None, None, None, None, None, None
59
 
 
88
  f"{metrics['times'][-1]:.2f}",
89
  )
90
 
91
+ def process_folder(files_paths: List[str], conf_thres: float, iou_thres: float):
92
+ if not files_paths:
93
  return None, None, None, None, None, None
94
 
95
  valid_extensions = [".jpg", ".jpeg", ".png"]
96
  image_files = [
97
+ f for f in files_paths if os.path.splitext(f.lower())[1] in valid_extensions
98
  ]
99
 
100
  if not image_files:
 
113
  ) as iface:
114
  gr.HTML(
115
  """
116
+ <h1>Tech4Humans - Signature Detector</h1>
117
 
118
  <div style="display: flex; align-items: center; gap: 10px;">
119
  <a href="https://huggingface.co/tech4humans/yolov8s-signature-detector">
 
130
  )
131
  gr.Markdown(
132
  """
133
+ This system uses the [**YOLOv8s**](https://huggingface.co/tech4humans/yolov8s-signature-detector) model, specially fine-tuned for detecting handwritten signatures in document images.
134
 
135
+ 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.
 
136
 
137
  ---
138
  """
139
  )
140
 
141
  with gr.Row(equal_height=True, elem_classes="main-container"):
142
+ # Left column for controls and information
143
  with gr.Column(scale=1):
144
+ with gr.Tab("Single Image"):
145
+ input_image = gr.Image(label="Upload your document", type="pil")
 
 
146
  with gr.Row():
147
+ clear_single_btn = gr.ClearButton([input_image], value="Clear")
148
  detect_single_btn = gr.Button(
149
+ "Detect", elem_classes="custom-button"
150
  )
151
 
152
+ with gr.Tab("Image Folder"):
153
  input_folder = gr.File(
154
+ label="Upload a folder with images",
155
  file_count="directory",
156
  type="filepath",
157
  )
158
  with gr.Row():
159
+ clear_folder_btn = gr.ClearButton([input_folder], value="Clear")
 
 
160
  detect_folder_btn = gr.Button(
161
+ "Detect", elem_classes="custom-button"
162
  )
163
 
164
  with gr.Group():
 
167
  maximum=1.0,
168
  value=0.25,
169
  step=0.05,
170
+ label="Confidence Threshold",
171
+ info="Adjust the minimum confidence score required for detection.",
172
  )
173
  iou_threshold = gr.Slider(
174
  minimum=0.0,
175
  maximum=1.0,
176
  value=0.5,
177
  step=0.05,
178
+ label="IoU Threshold",
179
+ info="Adjust the Intersection over Union threshold for Non-Maximum Suppression (NMS).",
180
  )
181
 
182
  with gr.Column(scale=1):
183
+ output_image = gr.Image(label="Detection Results")
184
 
185
+ with gr.Accordion("Examples", open=True):
186
  gr.Examples(
187
+ label="Image Examples",
188
  examples=[
189
  ["assets/images/example_{i}.jpg".format(i=i)]
190
  for i in range(
 
201
  with gr.Row(elem_classes="metrics-container"):
202
  with gr.Column(scale=1):
203
  total_inferences = gr.Textbox(
204
+ label="Total Inferences", show_copy_button=True, container=True
205
  )
206
+ hist_plot = gr.Plot(label="Time Distribution", container=True)
207
 
208
  with gr.Column(scale=1):
209
+ line_plot = gr.Plot(label="Time History", container=True)
210
  with gr.Row(elem_classes="metrics-row"):
211
  avg_inference_time = gr.Textbox(
212
+ label="Average Inference Time (ms)",
213
  show_copy_button=True,
214
  container=True,
215
  )
216
  last_inference_time = gr.Textbox(
217
+ label="Last Inference Time (ms)",
218
  show_copy_button=True,
219
  container=True,
220
  )
 
224
  gr.Markdown(
225
  """
226
  ---
227
+ ## About the Project
228
 
229
+ 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.
230
 
231
+ ### Key Metrics:
232
+ - **Precision:** 94.74%
233
+ - **Recall:** 89.72%
234
+ - **mAP@50:** 94.50%
235
+ - **mAP@50-95:** 67.35%
236
+ - **Inference Time (CPU):** 171.56 ms
237
 
238
+ Complete details on the training process, hyperparameter tuning, model evaluation, dataset creation, and inference server can be found in the links below.
239
 
240
  ---
241
 
242
+ **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)
243
  """
244
  )
245
 
 
285
  last_inference_time,
286
  ],
287
  )
288
+
289
  return iface
290
 
291
 
292
  if __name__ == "__main__":
293
  if not os.path.exists(DATABASE_PATH):
294
  os.makedirs(DATABASE_DIR, exist_ok=True)
295
+
296
  iface = create_gradio_interface()
297
  iface.launch()