Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -2,40 +2,54 @@ import gradio as gr
|
|
2 |
import tensorflow as tf
|
3 |
import numpy as np
|
4 |
import cv2
|
5 |
-
import datetime
|
6 |
|
7 |
-
#
|
8 |
-
|
9 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
10 |
|
11 |
class_labels = ["Normal", "Cataract"]
|
12 |
|
13 |
-
def
|
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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2 |
import tensorflow as tf
|
3 |
import numpy as np
|
4 |
import cv2
|
|
|
5 |
|
6 |
+
# Load the pre-trained ResNet-18 model from PyTorch
|
7 |
+
import torch
|
8 |
+
import requests
|
9 |
+
from torchvision import transforms
|
10 |
+
|
11 |
+
resnet_model = torch.hub.load('pytorch/vision:v0.6.0', 'resnet18', pretrained=True).eval()
|
12 |
+
response = requests.get("https://git.io/JJkYN")
|
13 |
+
labels = response.text.split("\n")
|
14 |
+
|
15 |
+
# Load the TensorFlow model
|
16 |
+
tf_model_path = 'modelo_treinado.h5'
|
17 |
+
tf_model = tf.keras.models.load_model(tf_model_path)
|
18 |
|
19 |
class_labels = ["Normal", "Cataract"]
|
20 |
|
21 |
+
def predict(inp):
|
22 |
+
# First, use the ResNet-18 model to predict labels
|
23 |
+
inp_resized = transforms.ToTensor()(inp).unsqueeze(0)
|
24 |
+
with torch.no_grad():
|
25 |
+
prediction_resnet = torch.nn.functional.softmax(resnet_model(inp_resized)[0], dim=0)
|
26 |
+
confidences_resnet = {labels[i]: float(prediction_resnet[i]) for i in range(1000)}
|
27 |
+
|
28 |
+
# Then, use the TensorFlow model to predict Normal or Cataract
|
29 |
+
img_array = cv2.cvtColor(np.array(inp), cv2.COLOR_RGB2BGR)
|
30 |
+
img_array = cv2.resize(img_array, (224, 224)) # Resize to match the input size expected by the TF model
|
31 |
+
img_array = img_array / 255.0 # Normalize pixel values
|
32 |
+
img_array = np.expand_dims(img_array, axis=0) # Add batch dimension
|
33 |
+
|
34 |
+
prediction_tf = tf_model.predict(img_array)
|
35 |
+
label_index = np.argmax(prediction_tf)
|
36 |
+
confidence_tf = float(prediction_tf[0, label_index])
|
37 |
+
|
38 |
+
# Combine the ResNet-18 and TensorFlow predictions
|
39 |
+
resnet_label = max(confidences_resnet, key=confidences_resnet.get)
|
40 |
+
if confidence_tf >= 0.5:
|
41 |
+
final_label = class_labels[label_index]
|
42 |
+
confidence = confidence_tf
|
43 |
+
else:
|
44 |
+
final_label = resnet_label
|
45 |
+
confidence = confidences_resnet[resnet_label]
|
46 |
+
|
47 |
+
return final_label, confidence
|
48 |
+
|
49 |
+
demo = gr.Interface(
|
50 |
+
fn=predict,
|
51 |
+
inputs=gr.inputs.Image(type="pil"),
|
52 |
+
outputs=["label", "number"]
|
53 |
+
)
|
54 |
+
|
55 |
+
demo.launch()
|