EduFalcao commited on
Commit
6eb8d8f
·
verified ·
1 Parent(s): f840a1c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +42 -50
app.py CHANGED
@@ -1,57 +1,49 @@
1
- import gradio as gr
 
2
  from PIL import Image, ImageOps
3
- import torch
4
- from transformers import CLIPProcessor, CLIPModel
5
-
6
- # ─── 1) Carrega modelo e processor CLIP fine-tuned ───
7
- MODEL_ID = "Keetawan/clip-vit-large-patch14-plant-disease-finetuned"
8
- processor = CLIPProcessor.from_pretrained(MODEL_ID)
9
- model = CLIPModel.from_pretrained(MODEL_ID)
10
-
11
- # ─── 2) Labels que o modelo conhece ───
12
- HF_LABELS = [
13
- "Grape leaf with Black rot",
14
- "Grape leaf with Esca (Black Measles)",
15
- "Grape leaf with Leaf blight (Isariopsis Leaf Spot)",
16
- "Healthy Grape leaf"
17
- ]
18
- # Mapeamento para as tuas classes curtas
19
- MAP = {
20
- "Grape leaf with Black rot": "Black Rot",
21
- "Grape leaf with Esca (Black Measles)": "ESCA",
22
- "Grape leaf with Leaf blight (Isariopsis Leaf Spot)": "Leaf Blight",
23
- "Healthy Grape leaf": "Healthy"
24
- }
25
-
26
- def predict(img: Image.Image):
27
- # Pré-processamento igual ao notebook
28
- img = ImageOps.exif_transpose(img).convert("RGB")
29
- img = img.resize((224,224))
30
-
31
- # Zero-shot inference CLIP
32
- inputs = processor(text=HF_LABELS, images=img, return_tensors="pt", padding=True)
33
- outputs = model(**inputs)
34
- probs = outputs.logits_per_image.softmax(dim=1)[0].tolist()
35
-
36
- # Constrói dicionário label→prob
37
- mapping = { MAP[HF_LABELS[i]]: probs[i] for i in range(len(probs)) }
38
- # Escolhe a classe de maior probabilidade
39
- best = max(mapping, key=mapping.get)
40
-
41
- # Formata as probabilidades
42
- prob_lines = "\n".join(f"{lbl}: {mapping[lbl]:.2f}" for lbl in ["Healthy","Leaf Blight","Black Rot","ESCA"])
43
- return best, prob_lines
44
-
45
- # ─── 3) UI Gradio ───────────────────────────────────────
46
  demo = gr.Interface(
47
  fn=predict,
48
  inputs=gr.Image(type="pil", label="Carrega uma folha"),
49
- outputs=[
50
- gr.Textbox(label="Classe predita"),
51
- gr.Textbox(label="Probabilidades")
52
- ],
53
- title="CropVision – CLIP Zero-Shot Fine-Tuned",
54
- description="Healthy / Leaf Blight / Black Rot / ESCA"
55
  )
56
 
57
  if __name__ == "__main__":
 
1
+ import json
2
+ import numpy as np
3
  from PIL import Image, ImageOps
4
+ import gradio as gr
5
+ from tensorflow.keras.models import load_model
6
+ from tensorflow.keras.preprocessing.image import img_to_array
7
+
8
+ # —————————————————————————————————
9
+ # 1) Carregar o modelo e o label_map
10
+ MODEL_PATH = "cropvision_model.keras" # ou ".h5" se for esse o caso
11
+ CLASS_ORDER = json.load(open("label_map.json"))
12
+
13
+ model = load_model(MODEL_PATH)
14
+
15
+ # —————————————————————————————————
16
+ # 2) Função de prediction
17
+ IMG_SIZE = (224, 224)
18
+
19
+ def predict(image: Image.Image):
20
+ # 2.1 Corrige rotação EXIF e dimensiona
21
+ img = ImageOps.exif_transpose(image).convert("RGB")
22
+ img = ImageOps.fit(img, IMG_SIZE, Image.Resampling.LANCZOS)
23
+
24
+ # 2.2 Converte para array e normaliza
25
+ arr = img_to_array(img) / 255.0
26
+ arr = np.expand_dims(arr, 0) # shape (1,224,224,3)
27
+
28
+ # 2.3 Inferência
29
+ probs = model.predict(arr)[0] # array de 4 valores
30
+ idx = int(np.argmax(probs))
31
+ label = CLASS_ORDER[idx]
32
+
33
+ # 2.4 Mapeia todas as probabilidades
34
+ mapping = {CLASS_ORDER[i]: float(probs[i]) for i in range(len(probs))}
35
+ # Formata saída
36
+ prob_lines = "\n".join(f"{lbl}: {mapping[lbl]:.2f}" for lbl in CLASS_ORDER)
37
+ return label, prob_lines
38
+
39
+ # —————————————————————————————————
40
+ # 3) Interface Gradio
 
 
 
 
 
 
41
  demo = gr.Interface(
42
  fn=predict,
43
  inputs=gr.Image(type="pil", label="Carrega uma folha"),
44
+ outputs=[gr.Textbox(label="Classe"), gr.Textbox(label="Probabilidades")],
45
+ title="CropVision",
46
+ description="Classifica folhas de videira em Healthy, Leaf Blight, Black Rot ou ESCA"
 
 
 
47
  )
48
 
49
  if __name__ == "__main__":