GDDO commited on
Commit
6f0ee4c
·
verified ·
1 Parent(s): cdf6d6f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +28 -27
app.py CHANGED
@@ -1,7 +1,9 @@
1
  import gradio as gr
2
  import tensorflow as tf
3
  import numpy as np
4
- from PIL import Image
 
 
5
 
6
  # Carregar o modelo .tflite
7
  interpreter = tf.lite.Interpreter(model_path="model_unquant.tflite")
@@ -12,41 +14,40 @@ output_details = interpreter.get_output_details()
12
 
13
  classes = ['Bastonete', 'Basófilo']
14
 
15
- def recognize_image(file):
16
- try:
17
- # Abrir o arquivo recebido
18
- image = Image.open(file).convert("RGB")
 
19
 
20
- # Redimensionar a imagem para o tamanho esperado pelo modelo
21
- image = image.resize((224, 224))
22
 
23
- # Converter a imagem para um array NumPy e normalizar os valores
24
- image_array = np.array(image).astype(np.float32) / 255.0
 
25
 
26
- # Adicionar uma dimensão extra para o batch size
27
- image_input = np.expand_dims(image_array, axis=0)
28
 
29
- # Fazer a inferência no modelo
30
- interpreter.set_tensor(input_details[0]['index'], image_input)
31
- interpreter.invoke()
32
 
33
- # Obter o resultado da inferência
34
- output_data = interpreter.get_tensor(output_details[0]['index'])
35
 
36
- # Obter o índice da classe com maior probabilidade
37
- predicted_class_index = np.argmax(output_data)
38
- predicted_class_name = classes[predicted_class_index]
39
- predicted_confidence = output_data[0][predicted_class_index] * 100
40
 
41
- return f"Classe: {predicted_class_name} (Confiança: {predicted_confidence:.2f}%)"
42
- except Exception as e:
43
- return f"Erro ao processar a imagem: {str(e)}"
44
 
45
- # Configuração do Gradio
46
  interface = gr.Interface(
47
  fn=recognize_image,
48
- inputs=gr.File(type="file"), # Recebe o arquivo como entrada
49
- outputs="text" # Resultado em formato de texto
50
  )
51
 
52
- interface.launch()
 
1
  import gradio as gr
2
  import tensorflow as tf
3
  import numpy as np
4
+ from PIL import Image as PILImage
5
+ import requests
6
+ import os
7
 
8
  # Carregar o modelo .tflite
9
  interpreter = tf.lite.Interpreter(model_path="model_unquant.tflite")
 
14
 
15
  classes = ['Bastonete', 'Basófilo']
16
 
17
+ def recognize_image(image):
18
+ # Verificar se a entrada é uma URL
19
+ if isinstance(image, str) and image.startswith("http"):
20
+ response = requests.get(image)
21
+ image = PILImage.open(BytesIO(response.content))
22
 
23
+ # Redimensionar a imagem para 224x224 (o tamanho esperado pelo modelo)
24
+ image = PILImage.fromarray(image).resize((224, 224))
25
 
26
+ # Converter para array NumPy e normalizar os valores
27
+ image_array = np.array(image).astype(np.float32)
28
+ image_array /= 255.0 # Normalizar para o intervalo [0, 1]
29
 
30
+ # Adicionar uma dimensão extra para o batch size (necessário para o modelo)
31
+ image_input = np.expand_dims(image_array, axis=0)
32
 
33
+ # Fazer a inferência no modelo
34
+ interpreter.set_tensor(input_details[0]['index'], image_input)
35
+ interpreter.invoke()
36
 
37
+ # Obter o resultado da inferência
38
+ output_data = interpreter.get_tensor(output_details[0]['index'])
39
 
40
+ # Obter o índice da classe com maior probabilidade
41
+ predicted_class_index = np.argmax(output_data)
42
+ predicted_class_name = classes[predicted_class_index]
43
+ predicted_confidence = output_data[0][predicted_class_index] * 100 # Converter para %
44
 
45
+ return f"Classe: {predicted_class_name} (Confiança: {predicted_confidence:.2f}%)"
 
 
46
 
 
47
  interface = gr.Interface(
48
  fn=recognize_image,
49
+ inputs=[gr.Image(), gr.Textbox(label="Caminho ou URL (opcional)")],
50
+ outputs="text"
51
  )
52
 
53
+ interface.launch(share=True)