cesar commited on
Commit
b65d9fe
1 Parent(s): a5312a2

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +152 -0
app.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """Deploy Barcelo demo.ipynb
3
+
4
+ Automatically generated by Colaboratory.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/1FxaL8DcYgvjPrWfWruSA5hvk3J81zLY9
8
+
9
+ ![ ](https://www.vicentelopez.gov.ar/assets/images/logo-mvl.png)
10
+
11
+ # Modelo
12
+
13
+ YOLO es una familia de modelos de detecci贸n de objetos a escala compuesta entrenados en COCO dataset, e incluye una funcionalidad simple para Test Time Augmentation (TTA), model ensembling, hyperparameter evolution, and export to ONNX, CoreML and TFLite.
14
+
15
+
16
+ ## Gradio Inferencia
17
+
18
+ ![](https://i.ibb.co/982NS6m/header.png)
19
+
20
+ Este Notebook se acelera opcionalmente con un entorno de ejecuci贸n de GPU
21
+
22
+
23
+ ----------------------------------------------------------------------
24
+
25
+ YOLOv5 Gradio demo
26
+
27
+ *Author: Ultralytics LLC and Gradio*
28
+
29
+ # C贸digo
30
+ """
31
+
32
+ #!pip install -qr https://raw.githubusercontent.com/ultralytics/yolov5/master/requirements.txt gradio # install dependencies
33
+
34
+ import os
35
+ import re
36
+ import json
37
+ import pandas as pd
38
+ import gradio as gr
39
+ import torch
40
+ from PIL import Image
41
+
42
+ # Images
43
+ torch.hub.download_url_to_file('https://i.pinimg.com/originals/7f/5e/96/7f5e9657c08aae4bcd8bc8b0dcff720e.jpg', 'ejemplo1.jpg')
44
+ torch.hub.download_url_to_file('https://i.pinimg.com/originals/c2/ce/e0/c2cee05624d5477ffcf2d34ca77b47d1.jpg', 'ejemplo2.jpg')
45
+
46
+ # Model
47
+ #model = torch.hub.load('ultralytics/yolov5', 'yolov5s') # force_reload=True to update
48
+
49
+ #model = torch.hub.load('ultralytics/yolov5', 'custom', path='best.pt') # local model o google colab
50
+ model = torch.hub.load('ultralytics/yolov5', 'custom', path='best.pt', force_reload=True, autoshape=True) # local model o google colab
51
+ #model = torch.hub.load('path/to/yolov5', 'custom', path='/content/yolov56.pt', source='local') # local repo
52
+
53
+ def getQuantity(string):
54
+ contador_raw = ''.join(string.split(" ")[3:])
55
+
56
+ resultado_especie_1 = 'Aedes'
57
+ resultado_especie_2 = 'Mosquito'
58
+ resultado_especie_3 = 'Mosca'
59
+ resultado_cantidad_1 = ''.join(re.findall(r'\d+',''.join(re.findall(r'\d+'+resultado_especie_1, contador_raw))))
60
+ resultado_cantidad_2 = ''.join(re.findall(r'\d+',''.join(re.findall(r'\d+'+resultado_especie_2, contador_raw))))
61
+ resultado_cantidad_3 = ''.join(re.findall(r'\d+',''.join(re.findall(r'\d+'+resultado_especie_3, contador_raw))))
62
+ resultado_cantidad_1 = resultado_cantidad_1 if len(resultado_cantidad_1) > 0 else "0"
63
+ resultado_cantidad_2 = resultado_cantidad_2 if len(resultado_cantidad_2) > 0 else "0"
64
+ resultado_cantidad_3 = resultado_cantidad_3 if len(resultado_cantidad_3) > 0 else "0"
65
+
66
+ resultado_lista = [[resultado_cantidad_1,resultado_especie_1],
67
+ [resultado_cantidad_2,resultado_especie_2],
68
+ [resultado_cantidad_3,resultado_especie_3]]
69
+
70
+ return resultado_lista
71
+
72
+ def listJSON(resultado):
73
+ resultado_lista = getQuantity(resultado)
74
+ img_name = " ".join(resultado.split(" ")[0:2])
75
+ img_size = "".join(resultado.split(" ")[2])
76
+ strlista = ""
77
+ for resultado_lista, description in resultado_lista:
78
+ strlista += '{"quantity":"'+resultado_lista+'","description":"'+description+'"},'
79
+ strlista = strlista[:-1]
80
+ str_resultado_lista = '{"image":"'+str(img_name)+'","size":"'+str(img_size)+'","detail":['+strlista+']}'
81
+ json_string = json.loads(str_resultado_lista)
82
+ return json_string
83
+
84
+ def arrayLista(resultado):
85
+ resultado_lista = getQuantity(resultado)
86
+ df = pd.DataFrame(resultado_lista,columns=['Cantidad','Especie'])
87
+ return df
88
+
89
+ def yolo(size, iou, conf, im):
90
+ '''Wrapper fn for gradio'''
91
+ g = (int(size) / max(im.size)) # gain
92
+ im = im.resize((int(x * g) for x in im.size), Image.ANTIALIAS) # resize
93
+
94
+ model.iou = iou
95
+
96
+ model.conf = conf
97
+
98
+
99
+ results2 = model(im) # inference
100
+
101
+ results2.render() # updates results.imgs with boxes and labels
102
+
103
+ results_detail = str(results2)
104
+ lista = listJSON(results_detail)
105
+ lista2 = arrayLista(results_detail)
106
+ return Image.fromarray(results2.ims[0]), lista2, lista
107
+
108
+ #------------ Interface-------------
109
+
110
+
111
+
112
+ in1 = gr.inputs.Radio(['640', '1280'], label="Tama帽o de la imagen", default='640', type='value')
113
+ in2 = gr.inputs.Slider(minimum=0, maximum=1, step=0.05, default=0.45, label='NMS IoU threshold')
114
+ in3 = gr.inputs.Slider(minimum=0, maximum=1, step=0.05, default=0.50, label='Umbral o threshold')
115
+ in4 = gr.inputs.Image(type='pil', label="Original Image")
116
+
117
+ out2 = gr.outputs.Image(type="pil", label="YOLOv5")
118
+ out3 = gr.outputs.Dataframe(label="Descripci贸n", headers=['Cantidad','Especie'])
119
+ out4 = gr.outputs.JSON(label="JSON")
120
+ #-------------- Text-----
121
+ title = 'Trampas Barcel贸'
122
+ description = """
123
+ <p>
124
+ <center>
125
+ Sistemas de Desarrollado por Subsecretar铆a de Innovaci贸n del Municipio de Vicente L贸pez. Advertencia solo usar fotos provenientes de las trampas Barcel贸, no de celular o foto de internet.
126
+ <img src="https://www.vicentelopez.gov.ar/assets/images/logo-mvl.png" alt="logo" width="250"/>
127
+ </center>
128
+ </p>
129
+ """
130
+ 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>"
131
+
132
+ examples = [['640',0.45, 0.75,'ejemplo1.jpg'], ['640',0.45, 0.75,'ejemplo2.jpg']]
133
+
134
+ iface = gr.Interface(yolo,
135
+ inputs=[in1, in2, in3, in4],
136
+ outputs=[out2,out3,out4], title=title,
137
+ description=description,
138
+ article=article,
139
+ examples=examples,
140
+ theme="huggingface",
141
+ analytics_enabled=False
142
+ ).launch(debug=True)
143
+
144
+ iface.launch()
145
+
146
+ """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).
147
+
148
+
149
+ ## Citation
150
+
151
+ [![DOI](https://zenodo.org/badge/264818686.svg)](https://zenodo.org/badge/latestdoi/264818686)
152
+ """