fcernafukuzaki commited on
Commit
7f4ae92
1 Parent(s): 507b8e0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -109
app.py CHANGED
@@ -20,153 +20,104 @@ Este Notebook se acelera opcionalmente con un entorno de ejecución de GPU
20
  import os
21
  import re
22
  import json
23
- import numpy as np
24
  import pandas as pd
25
  import gradio as gr
26
  import torch
27
  from PIL import Image
28
- from ultralytics import YOLO
29
- #from ultralyticsplus import render_result
30
 
31
  # Images
32
  torch.hub.download_url_to_file('https://huggingface.co/spaces/Municipalidad-de-Vicente-Lopez/Trampas_Barcelo/resolve/main/2024-03-11T10-50-27.jpg', 'ejemplo1.jpg')
33
  torch.hub.download_url_to_file('https://i.pinimg.com/originals/c2/ce/e0/c2cee05624d5477ffcf2d34ca77b47d1.jpg', 'ejemplo2.jpg')
34
 
35
- # Model
36
- class YOLODetect():
37
- def __init__(self, modelo):
38
- self.modelo = modelo
39
 
40
- def predecir(self, url):
41
- # conf float 0.25 umbral de confianza del objeto para la detección
42
- # iou float 0.7 umbral de intersección sobre unión (IoU) para NMS
43
- self.source = url
44
- self.results = self.modelo.predict(source=self.source, save=True, imgsz=640, conf=0.5, iou=0.40)
45
- return self.results
46
 
47
- def show(self):
48
- results = self.results[0]
49
- render = None #render_result(model=self.modelo, image=self.source, result=self.results[0])
50
- render = Image.open(f"runs/detect/predict/{results.path}")
51
- return render
52
 
53
- def to_json(self):
54
- results = self.results[0]
55
- img_size = results.orig_shape
56
- img_name = results.path
57
- array_numpy = results.boxes.cls.cpu().numpy().astype(np.int32)
58
-
59
- # Definir las clases y sus nombres correspondientes
60
- clases = {
61
- 0: "Aedes",
62
- 1: "Mosquitos",
63
- 2: "Moscas"
64
- }
65
-
66
- # Contabilizar las clases
67
- conteo_clases = np.bincount(array_numpy)
68
-
69
- self.json_result = [{'Especie': clases[i], 'Cantidad': str(conteo_clases[i]) if i < len(conteo_clases) else str(0)} for i in range(len(clases))]
70
- # Crear un diccionario con los elementos necesarios
71
- result_dict = {
72
- "image": str(img_name),
73
- "size": str(img_size),
74
- "detail": self.json_result
75
- }
76
-
77
- # Convertir el diccionario a una cadena JSON
78
- result_dict = json.dumps(result_dict)
79
- #print(f"{type(self.json_result)} - {self.json_result}")
80
-
81
- # Convertir la cadena JSON a un objeto Python (diccionario)
82
- result_dict = json.loads(result_dict)
83
- #print(f"{type(self.json_result)} - {self.json_result}")
84
-
85
- return result_dict
86
-
87
- def to_dataframe(self):
88
- return pd.DataFrame(self.json_result)
89
-
90
- modelo_yolo = YOLO('best.pt')
91
 
92
  def yolo(size, iou, conf, im):
93
  '''Wrapper fn for gradio'''
94
  g = (int(size) / max(im.size)) # gain
95
  im = im.resize((int(x * g) for x in im.size), Image.LANCZOS) # resize with antialiasing
96
 
97
-
98
- # model.iou = iou
99
 
100
- # model.conf = conf
101
-
 
102
 
103
- # results2 = model(im) # inference
104
- # #print(type(results2))
105
- print(type(im))
106
-
107
- source = im#Image.open(im)
108
- model = YOLODetect(modelo_yolo)
109
- results = model.predecir(source)
110
 
111
- result_json = model.to_json()
112
- print(result_json)
113
- result_df = model.to_dataframe()
114
- print(result_df)
115
- result_img = model.show()
116
-
117
- #result_img, result_df, result_json = source, None, None
118
- return result_img, result_df, result_json
119
 
120
  #------------ Interface-------------
121
 
 
 
 
 
122
 
123
-
124
- #in1 = gr.inputs.Radio(['640', '1280'], label="Tamaño de la imagen", type='value')
125
- #in2 = gr.inputs.Slider(minimum=0, maximum=1, step=0.05, label='NMS IoU threshold')
126
- #in3 = gr.inputs.Slider(minimum=0, maximum=1, step=0.05, label='Umbral o threshold')
127
- #in4 = gr.inputs.Image(type='pil', label="Original Image")
128
-
129
- #out2 = gr.outputs.Image(type="pil", label="YOLOv5")
130
- #out3 = gr.outputs.Dataframe(label="Cantidad_especie", headers=['Cantidad','Especie'], type="pandas")
131
- #out4 = gr.outputs.JSON(label="JSON")
132
- in1 = gr.Radio(['640', '1280'], label="Tamaño de la imagen", type='value')
133
- in2 = gr.Slider(minimum=0, maximum=1, step=0.05, label='NMS IoU threshold')
134
- in3 = gr.Slider(minimum=0, maximum=1, step=0.05, label='Umbral o threshold')
135
- in4 = gr.Image(type='pil', label="Original Image")
136
-
137
- out2 = gr.Image(type="pil", label="YOLOv5")
138
- out3 = gr.Dataframe(label="Cantidad_especie", headers=['Cantidad','Especie'], type="pandas")
139
- out4 = gr.JSON(label="JSON")
140
  #-------------- Text-----
141
  title = 'Trampas Barceló'
142
- description = """
143
- <p>
144
- <center>
145
- Sistemas de Desarrollado por Subsecretaría de Modernización del Municipio de Vicente López. Advertencia solo usar fotos provenientes de las trampas Barceló, no de celular o foto de internet.
146
- <img src="https://www.vicentelopez.gov.ar/assets/images/logo-mvl.png" alt="logo" width="250"/>
147
- </center>
148
- </p>
149
- """
150
  article ="<p style='text-align: center'><a href='https://docs.google.com/presentation/d/1T5CdcLSzgRe8cQpoi_sPB4U170551NGOrZNykcJD0xU/edit?usp=sharing' target='_blank'>Para mas info, clik para ir al white paper</a></p><p style='text-align: center'><a href='https://drive.google.com/drive/folders/1owACN3HGIMo4zm2GQ_jf-OhGNeBVRS7l?usp=sharing ' target='_blank'>Google Colab Demo</a></p><p style='text-align: center'><a href='https://github.com/Municipalidad-de-Vicente-Lopez/Trampa_Barcelo' target='_blank'>Repo Github</a></p></center></p>"
151
 
152
- examples = [['640',0.45, 0.75,'ejemplo1.jpg'], ['640',0.45, 0.75,'ejemplo2.jpg']]
153
 
154
  iface = gr.Interface(yolo,
155
  inputs=[in1, in2, in3, in4],
156
- outputs=[out2,out3,out4], title=title,
157
- description=description,
158
- article=article,
159
- examples=examples,
160
  analytics_enabled=False,
161
  allow_flagging="manual",
162
  flagging_options=["Correcto", "Incorrecto", "Casi correcto", "Error", "Otro"],
163
  #flagging_callback=hf_writer
164
  )
165
 
166
- #iface.launch(enable_queue=True, debug=True)
167
- iface.queue()
168
- iface.launch(debug=True)
169
-
170
  """For YOLOv5 PyTorch Hub inference with **PIL**, **OpenCV**, **Numpy** or **PyTorch** inputs please see the full [YOLOv5 PyTorch Hub Tutorial](https://github.com/ultralytics/yolov5/issues/36).
171
  ## Citation
172
  [![DOI](https://zenodo.org/badge/264818686.svg)](https://zenodo.org/badge/latestdoi/264818686)
 
20
  import os
21
  import re
22
  import json
 
23
  import pandas as pd
24
  import gradio as gr
25
  import torch
26
  from PIL import Image
 
 
27
 
28
  # Images
29
  torch.hub.download_url_to_file('https://huggingface.co/spaces/Municipalidad-de-Vicente-Lopez/Trampas_Barcelo/resolve/main/2024-03-11T10-50-27.jpg', 'ejemplo1.jpg')
30
  torch.hub.download_url_to_file('https://i.pinimg.com/originals/c2/ce/e0/c2cee05624d5477ffcf2d34ca77b47d1.jpg', 'ejemplo2.jpg')
31
 
32
+ # model = torch.hub.load('ultralytics/yolov9', 'custom', path='best.pt', force_reload=True, autoshape=True, trust_repo=True)
33
+ model = torch.hub.load('yolov9', 'custom', path='best.pt', source='local', force_reload=True, autoshape=True) # load on CPU
 
 
34
 
 
 
 
 
 
 
35
 
36
+ #HF_TOKEN = os.getenv("ZIKA_TOKEN_WRITE")
37
+ #hf_writer = gr.HuggingFaceDatasetSaver(HF_TOKEN, "demo-iazika-flags")
 
 
 
38
 
39
+ def getQuantity(string):
40
+ contador_raw = ''.join(string.split(" ")[3:])
41
+
42
+ resultado_especie_1 = 'Aedes'
43
+ resultado_especie_2 = 'Mosquito'
44
+ resultado_especie_3 = 'Mosca'
45
+ resultado_cantidad_1 = ''.join(re.findall(r'\d+',''.join(re.findall(r'\d+'+resultado_especie_1, contador_raw))))
46
+ resultado_cantidad_2 = ''.join(re.findall(r'\d+',''.join(re.findall(r'\d+'+resultado_especie_2, contador_raw))))
47
+ resultado_cantidad_3 = ''.join(re.findall(r'\d+',''.join(re.findall(r'\d+'+resultado_especie_3, contador_raw))))
48
+ resultado_cantidad_1 = resultado_cantidad_1 if len(resultado_cantidad_1) > 0 else "0"
49
+ resultado_cantidad_2 = resultado_cantidad_2 if len(resultado_cantidad_2) > 0 else "0"
50
+ resultado_cantidad_3 = resultado_cantidad_3 if len(resultado_cantidad_3) > 0 else "0"
51
+
52
+ resultado_lista = [[resultado_cantidad_1,resultado_especie_1],
53
+ [resultado_cantidad_2,resultado_especie_2],
54
+ [resultado_cantidad_3,resultado_especie_3]]
55
+
56
+ return resultado_lista
57
+
58
+ def listJSON(resultado):
59
+ resultado_lista = getQuantity(resultado)
60
+ img_name = " ".join(resultado.split(" ")[0:2])
61
+ img_size = "".join(resultado.split(" ")[2])
62
+ strlista = ""
63
+ for resultado_lista, description in resultado_lista:
64
+ strlista += '{"quantity":"'+resultado_lista+'","description":"'+description+'"},'
65
+ strlista = strlista[:-1]
66
+ str_resultado_lista = '{"image":"'+str(img_name)+'","size":"'+str(img_size)+'","detail":['+strlista+']}'
67
+ json_string = json.loads(str_resultado_lista)
68
+ return json_string
69
+
70
+ def arrayLista(resultado):
71
+ resultado_lista = getQuantity(resultado)
72
+ df = pd.DataFrame(resultado_lista,columns=['Cantidad','Especie'])
73
+ return df
 
 
 
74
 
75
  def yolo(size, iou, conf, im):
76
  '''Wrapper fn for gradio'''
77
  g = (int(size) / max(im.size)) # gain
78
  im = im.resize((int(x * g) for x in im.size), Image.LANCZOS) # resize with antialiasing
79
 
80
+ model.iou = iou
 
81
 
82
+ model.conf = conf
83
+
84
+ results2 = model(im) # inference
85
 
86
+ results2.render() # updates results.imgs with boxes and labels
 
 
 
 
 
 
87
 
88
+ results_detail = str(results2)
89
+ lista = listJSON(results_detail)
90
+ lista2 = arrayLista(results_detail)
91
+ return Image.fromarray(results2.ims[0]), lista2, lista
 
 
 
 
92
 
93
  #------------ Interface-------------
94
 
95
+ in1 = gr.inputs.Radio(['640', '1280'], label="Tamaño de la imagen", default='640', type='value')
96
+ in2 = gr.inputs.Slider(minimum=0, maximum=1, step=0.05, default=0.25, label='NMS IoU threshold')
97
+ in3 = gr.inputs.Slider(minimum=0, maximum=1, step=0.05, default=0.50, label='Umbral o threshold')
98
+ in4 = gr.inputs.Image(type='pil', label="Original Image")
99
 
100
+ out2 = gr.outputs.Image(type="pil", label="YOLOv5")
101
+ out3 = gr.outputs.Dataframe(label="Cantidad_especie", headers=['Cantidad','Especie'], type="pandas")
102
+ out4 = gr.outputs.JSON(label="JSON")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
  #-------------- Text-----
104
  title = 'Trampas Barceló'
105
+ description = '<p><center>Sistemas de Desarrollado por Subsecretaría de Modernización del Municipio de Vicente López. Advertencia solo usar fotos provenientes de las trampas Barceló, no de celular o foto de internet.<img src="https://www.vicentelopez.gov.ar/assets/images/logo-mvl.png" alt="logo" width="250"/></center></p>'
106
+
 
 
 
 
 
 
107
  article ="<p style='text-align: center'><a href='https://docs.google.com/presentation/d/1T5CdcLSzgRe8cQpoi_sPB4U170551NGOrZNykcJD0xU/edit?usp=sharing' target='_blank'>Para mas info, clik para ir al white paper</a></p><p style='text-align: center'><a href='https://drive.google.com/drive/folders/1owACN3HGIMo4zm2GQ_jf-OhGNeBVRS7l?usp=sharing ' target='_blank'>Google Colab Demo</a></p><p style='text-align: center'><a href='https://github.com/Municipalidad-de-Vicente-Lopez/Trampa_Barcelo' target='_blank'>Repo Github</a></p></center></p>"
108
 
109
+ examples = [['640',0.25, 0.5,'ejemplo1.jpg'], ['640',0.25, 0.5,'ejemplo2.jpg']]
110
 
111
  iface = gr.Interface(yolo,
112
  inputs=[in1, in2, in3, in4],
113
+ examples=examples,
 
 
 
114
  analytics_enabled=False,
115
  allow_flagging="manual",
116
  flagging_options=["Correcto", "Incorrecto", "Casi correcto", "Error", "Otro"],
117
  #flagging_callback=hf_writer
118
  )
119
 
120
+ iface.launch(enable_queue=True, debug=True)
 
 
 
121
  """For YOLOv5 PyTorch Hub inference with **PIL**, **OpenCV**, **Numpy** or **PyTorch** inputs please see the full [YOLOv5 PyTorch Hub Tutorial](https://github.com/ultralytics/yolov5/issues/36).
122
  ## Citation
123
  [![DOI](https://zenodo.org/badge/264818686.svg)](https://zenodo.org/badge/latestdoi/264818686)