EduFalcao commited on
Commit
9231b08
·
verified ·
1 Parent(s): 38c3a23

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +33 -44
app.py CHANGED
@@ -1,55 +1,44 @@
1
- import json
2
- from tensorflow.keras.models import load_model
3
- from tensorflow.keras.preprocessing.image import img_to_array
4
- from PIL import ImageOps, Image
5
- import numpy as np
6
  import gradio as gr
 
 
7
 
8
- # ——————————————————————
9
- # 1) CARREGA O MAPEAMENTO EXATO de classes
10
- # no teu treino, geraste um label_map.json com:
11
- # json.dump(enc.classes_.tolist(), open("label_map.json","w"))
12
- # subiste esse label_map.json junto do modelo
13
- CLASS_ORDER = json.load(open("label_map.json"))
14
-
15
- # ——————————————————————
16
- # 2) PRÉ-PROCESSAMENTO robusto para fotos de telemóvel
17
- IMG_SIZE = (224, 224)
18
- MODEL_PATH= "cropvision_model.keras"
19
- model = load_model(MODEL_PATH)
20
- import hashlib, pathlib
21
- # debug: imprime MD5 e número de parâmetros
22
- md5 = hashlib.md5(pathlib.Path(MODEL_PATH).read_bytes()).hexdigest()
23
- print("📝 MD5 do modelo carregado:", md5)
24
- print("🔢 camadas:", len(model.layers), "-- params:", model.count_params())
25
 
 
 
26
 
27
  def predict(image: Image.Image):
28
- # corrige rotação EXIF e faz um crop centrado
29
- img = ImageOps.exif_transpose(image).convert("RGB")
30
- img = ImageOps.fit(img, IMG_SIZE, Image.Resampling.LANCZOS)
31
-
32
- # normaliza e infere
33
- arr = img_to_array(img)/255.0
34
- arr = np.expand_dims(arr, 0)
35
- probs = model.predict(arr)[0]
36
-
37
- # escolhe a classe e devolve também todas as probabilidades
38
- idx = int(np.argmax(probs))
39
- label = CLASS_ORDER[idx]
40
- mapping = {CLASS_ORDER[i]: float(probs[i]) for i in range(len(probs))}
41
-
42
- return label, f"{mapping}"
43
 
44
- # ——————————————————————
45
- # 3) Gradio UI
 
 
 
 
 
 
 
 
 
 
 
 
46
  demo = gr.Interface(
47
  fn=predict,
48
- inputs=gr.Image(type="pil", label="Carrega folha"),
49
- outputs=[gr.Textbox(label="Classe"), gr.Code(label="Probabilidades")],
50
- title="CropVision"
 
 
 
 
51
  )
52
 
53
- if __name__=="__main__":
54
  demo.launch()
55
-
 
 
 
 
 
 
1
  import gradio as gr
2
+ from PIL import Image
3
+ from transformers import pipeline
4
 
5
+ # 1) Cria o classificador zero‐shot com CLIP
6
+ classifier = pipeline(
7
+ task="zero-shot-image-classification",
8
+ model="openai/clip-vit-base-patch32"
9
+ )
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
+ # 2) Define as labels
12
+ LABELS = ["Healthy", "Leaf Blight", "Black Rot", "ESCA"]
13
 
14
  def predict(image: Image.Image):
15
+ # Opcional: corrige EXIF e redimensiona como antes
16
+ image = image.convert("RGB").resize((224,224))
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
+ # Zero‐shot classification
19
+ res = classifier(image, candidate_labels=LABELS)
20
+ # res é lista de dicts: [{"label":..., "score":...}, ...]
21
+
22
+ # Mapeia para texto ordenado
23
+ probs = {item["label"]: float(item["score"]) for item in res}
24
+ # Escolhe o mais provável
25
+ best = max(probs, key=probs.get)
26
+
27
+ # Formata saída
28
+ prob_lines = "\n".join(f"{lbl}: {probs[lbl]:.2f}" for lbl in LABELS)
29
+ return best, prob_lines
30
+
31
+ # 3) Interface Gradio
32
  demo = gr.Interface(
33
  fn=predict,
34
+ inputs=gr.Image(type="pil", label="Carrega a folha"),
35
+ outputs=[
36
+ gr.Textbox(label="Classe predita"),
37
+ gr.Textbox(label="Probabilidades (0–1)")
38
+ ],
39
+ title="CropVision (Backup CLIP Zero-Shot)",
40
+ description="Usa CLIP zero-shot para classificar folhas em Healthy, Leaf Blight, Black Rot ou ESCA"
41
  )
42
 
43
+ if __name__ == "__main__":
44
  demo.launch()