Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
@@ -1,171 +1,166 @@
|
|
1 |
import gradio as gr
|
2 |
import torch
|
3 |
-
from transformers import
|
|
|
|
|
|
|
4 |
from PIL import Image
|
5 |
-
import pandas as pd
|
6 |
import numpy as np
|
7 |
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
NUTRITION_DB = {
|
14 |
-
"arroz": {"calorias": 130, "proteinas": 2.7, "carboidratos": 28, "gorduras": 0.3},
|
15 |
-
"feijão": {"calorias": 77, "proteinas": 5.2, "carboidratos": 13.6, "gorduras": 0.5},
|
16 |
-
"carne": {"calorias": 250, "proteinas": 26, "carboidratos": 0, "gorduras": 17},
|
17 |
-
"batata frita": {"calorias": 312, "proteinas": 3.4, "carboidratos": 41, "gorduras": 15},
|
18 |
-
"salada": {"calorias": 15, "proteinas": 1.4, "carboidratos": 2.9, "gorduras": 0.2}
|
19 |
-
}
|
20 |
-
|
21 |
-
def process_image(image, progress=gr.Progress()):
|
22 |
-
"""Processa a imagem usando Emu3-Gen"""
|
23 |
-
try:
|
24 |
-
progress(0.3, desc="Processando imagem...")
|
25 |
-
|
26 |
-
# Prepara a imagem
|
27 |
-
if isinstance(image, str):
|
28 |
-
image = Image.open(image)
|
29 |
-
elif isinstance(image, np.ndarray):
|
30 |
-
image = Image.fromarray(image)
|
31 |
-
|
32 |
-
# Prompt específico para análise de alimentos
|
33 |
-
prompt = "Describe in detail all the foods present in this image, including their preparation methods."
|
34 |
-
|
35 |
-
progress(0.6, desc="Analisando conteúdo...")
|
36 |
-
# Processa a imagem
|
37 |
-
inputs = processor(
|
38 |
-
images=image,
|
39 |
-
text=prompt,
|
40 |
-
return_tensors="pt"
|
41 |
-
).to(model.device)
|
42 |
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
|
|
50 |
)
|
51 |
-
|
52 |
-
description = processor.decode(outputs[0], skip_special_tokens=True)
|
53 |
-
|
54 |
-
progress(1.0, desc="Concluído!")
|
55 |
-
return description
|
56 |
-
|
57 |
-
except Exception as e:
|
58 |
-
raise gr.Error(f"Erro no processamento: {str(e)}")
|
59 |
-
|
60 |
-
def analyze_nutrition(description):
|
61 |
-
"""Analisa nutrientes baseado na descrição"""
|
62 |
-
found_foods = []
|
63 |
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
"
|
74 |
-
"gorduras": 0
|
75 |
-
}
|
76 |
-
|
77 |
-
for food in found_foods:
|
78 |
-
for nutrient, value in NUTRITION_DB[food].items():
|
79 |
-
total_nutrients[nutrient] += value
|
80 |
|
81 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
82 |
|
83 |
-
def analyze_image(image):
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
109 |
|
110 |
-
|
111 |
-
|
112 |
-
{description}
|
113 |
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
### 📊 Informação Nutricional:
|
118 |
-
• Calorias: {total_nutrients['calorias']:.1f} kcal
|
119 |
-
• Proteínas: {total_nutrients['proteinas']:.1f}g
|
120 |
-
• Carboidratos: {total_nutrients['carboidratos']:.1f}g
|
121 |
-
• Gorduras: {total_nutrients['gorduras']:.1f}g
|
122 |
-
|
123 |
-
### 💡 Recomendações:
|
124 |
-
{"⚠️ Alto valor calórico" if total_nutrients['calorias'] > 800 else "✅ Calorias adequadas"}
|
125 |
-
{"⚠️ Considere reduzir carboidratos" if total_nutrients['carboidratos'] > 60 else "✅ Carboidratos adequados"}
|
126 |
-
{"⚠️ Alto teor de gorduras" if total_nutrients['gorduras'] > 20 else "✅ Gorduras adequadas"}
|
127 |
-
"""
|
128 |
-
|
129 |
-
return analysis, table_data, plot_data
|
130 |
-
|
131 |
-
except Exception as e:
|
132 |
-
return str(e), None, None
|
133 |
|
134 |
# Interface Gradio
|
135 |
with gr.Blocks(theme=gr.themes.Soft()) as iface:
|
136 |
-
gr.Markdown("
|
|
|
|
|
|
|
137 |
|
138 |
with gr.Row():
|
139 |
with gr.Column():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
140 |
image_input = gr.Image(
|
141 |
type="pil",
|
142 |
-
label="
|
143 |
-
sources=["upload", "webcam"]
|
144 |
)
|
145 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
146 |
|
147 |
with gr.Column():
|
148 |
-
|
|
|
|
|
|
|
149 |
|
150 |
-
with gr.
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
)
|
162 |
|
|
|
163 |
analyze_btn.click(
|
164 |
-
fn=analyze_image,
|
165 |
-
inputs=[image_input],
|
166 |
-
outputs=
|
167 |
)
|
168 |
|
169 |
if __name__ == "__main__":
|
170 |
-
print(f"
|
171 |
-
iface.launch(
|
|
|
1 |
import gradio as gr
|
2 |
import torch
|
3 |
+
from transformers import (
|
4 |
+
Blip2Processor, Blip2ForConditionalGeneration,
|
5 |
+
AutoProcessor, AutoModelForCausalLM, AutoModelForVision2Seq
|
6 |
+
)
|
7 |
from PIL import Image
|
|
|
8 |
import numpy as np
|
9 |
|
10 |
+
class ModelManager:
|
11 |
+
def __init__(self):
|
12 |
+
self.current_model = None
|
13 |
+
self.current_processor = None
|
14 |
+
self.model_name = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
15 |
|
16 |
+
def load_blip2(self):
|
17 |
+
"""Carrega modelo BLIP-2"""
|
18 |
+
self.model_name = "Salesforce/blip2-opt-2.7b"
|
19 |
+
self.current_processor = Blip2Processor.from_pretrained(self.model_name)
|
20 |
+
self.current_model = Blip2ForConditionalGeneration.from_pretrained(
|
21 |
+
self.model_name,
|
22 |
+
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
|
23 |
+
device_map="auto"
|
24 |
)
|
25 |
+
return "BLIP-2 carregado com sucesso!"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
26 |
|
27 |
+
def load_llava(self):
|
28 |
+
"""Carrega modelo LLaVA"""
|
29 |
+
self.model_name = "llava-hf/llava-1.5-7b-hf"
|
30 |
+
self.current_processor = AutoProcessor.from_pretrained(self.model_name)
|
31 |
+
self.current_model = AutoModelForVision2Seq.from_pretrained(
|
32 |
+
self.model_name,
|
33 |
+
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
|
34 |
+
device_map="auto"
|
35 |
+
)
|
36 |
+
return "LLaVA carregado com sucesso!"
|
|
|
|
|
|
|
|
|
|
|
|
|
37 |
|
38 |
+
def load_git(self):
|
39 |
+
"""Carrega modelo GIT"""
|
40 |
+
self.model_name = "microsoft/git-base-coco"
|
41 |
+
self.current_processor = AutoProcessor.from_pretrained(self.model_name)
|
42 |
+
self.current_model = AutoModelForCausalLM.from_pretrained(
|
43 |
+
self.model_name,
|
44 |
+
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
|
45 |
+
device_map="auto"
|
46 |
+
)
|
47 |
+
return "GIT carregado com sucesso!"
|
48 |
|
49 |
+
def analyze_image(self, image, question, model_choice):
|
50 |
+
"""Analisa imagem com o modelo selecionado"""
|
51 |
+
try:
|
52 |
+
# Carrega o modelo apropriado se necessário
|
53 |
+
if model_choice == "BLIP-2" and (self.model_name != "Salesforce/blip2-opt-2.7b"):
|
54 |
+
status = self.load_blip2()
|
55 |
+
elif model_choice == "LLaVA" and (self.model_name != "llava-hf/llava-1.5-7b-hf"):
|
56 |
+
status = self.load_llava()
|
57 |
+
elif model_choice == "GIT" and (self.model_name != "microsoft/git-base-coco"):
|
58 |
+
status = self.load_git()
|
59 |
+
|
60 |
+
# Prepara a imagem
|
61 |
+
if isinstance(image, str):
|
62 |
+
image = Image.open(image)
|
63 |
+
elif isinstance(image, np.ndarray):
|
64 |
+
image = Image.fromarray(image)
|
65 |
+
|
66 |
+
# Processa a entrada
|
67 |
+
inputs = self.current_processor(
|
68 |
+
images=image,
|
69 |
+
text=question,
|
70 |
+
return_tensors="pt"
|
71 |
+
).to(self.current_model.device)
|
72 |
+
|
73 |
+
# Gera a resposta
|
74 |
+
outputs = self.current_model.generate(
|
75 |
+
**inputs,
|
76 |
+
max_new_tokens=150,
|
77 |
+
num_beams=5,
|
78 |
+
temperature=0.7,
|
79 |
+
top_p=0.9
|
80 |
+
)
|
81 |
+
|
82 |
+
response = self.current_processor.decode(outputs[0], skip_special_tokens=True)
|
83 |
+
return response
|
84 |
|
85 |
+
except Exception as e:
|
86 |
+
return f"Erro na análise: {str(e)}"
|
|
|
87 |
|
88 |
+
# Cria instância do gerenciador de modelos
|
89 |
+
model_manager = ModelManager()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
90 |
|
91 |
# Interface Gradio
|
92 |
with gr.Blocks(theme=gr.themes.Soft()) as iface:
|
93 |
+
gr.Markdown("""
|
94 |
+
# 🤖 Análise Visual Multi-Modelo
|
95 |
+
Escolha o modelo que deseja usar para analisar sua imagem
|
96 |
+
""")
|
97 |
|
98 |
with gr.Row():
|
99 |
with gr.Column():
|
100 |
+
# Inputs
|
101 |
+
model_choice = gr.Radio(
|
102 |
+
choices=["BLIP-2", "LLaVA", "GIT"],
|
103 |
+
label="Escolha o Modelo",
|
104 |
+
value="BLIP-2"
|
105 |
+
)
|
106 |
+
|
107 |
+
with gr.Box():
|
108 |
+
gr.Markdown("""
|
109 |
+
### 📝 Características dos Modelos:
|
110 |
+
|
111 |
+
**BLIP-2:**
|
112 |
+
- Melhor para análise técnica
|
113 |
+
- Mais preciso em detalhes
|
114 |
+
- Respostas estruturadas
|
115 |
+
|
116 |
+
**LLaVA:**
|
117 |
+
- Mais conversacional
|
118 |
+
- Respostas naturais
|
119 |
+
- Bom para perguntas abertas
|
120 |
+
|
121 |
+
**GIT:**
|
122 |
+
- Mais rápido e leve
|
123 |
+
- Bom para descrições simples
|
124 |
+
- Menor uso de memória
|
125 |
+
""")
|
126 |
+
|
127 |
image_input = gr.Image(
|
128 |
type="pil",
|
129 |
+
label="Imagem para Análise"
|
|
|
130 |
)
|
131 |
+
|
132 |
+
question_input = gr.Textbox(
|
133 |
+
label="Sua Pergunta",
|
134 |
+
placeholder="Faça uma pergunta sobre a imagem..."
|
135 |
+
)
|
136 |
+
|
137 |
+
analyze_btn = gr.Button("🔍 Analisar", variant="primary")
|
138 |
|
139 |
with gr.Column():
|
140 |
+
# Output
|
141 |
+
with gr.Box():
|
142 |
+
gr.Markdown("### 📊 Resultado da Análise")
|
143 |
+
output_text = gr.Markdown()
|
144 |
|
145 |
+
with gr.Accordion("💡 Sugestões de Perguntas", open=False):
|
146 |
+
gr.Markdown("""
|
147 |
+
1. Quais alimentos você identifica na imagem?
|
148 |
+
2. Como os alimentos estão preparados?
|
149 |
+
3. Descreva a apresentação do prato.
|
150 |
+
4. Que tipo de culinária parece ser?
|
151 |
+
5. Quais são os ingredientes principais?
|
152 |
+
6. Como está a disposição dos elementos no prato?
|
153 |
+
7. Há algum detalhe de decoração ou finalização?
|
154 |
+
8. Qual parece ser o método de cocção utilizado?
|
155 |
+
""")
|
|
|
156 |
|
157 |
+
# Eventos
|
158 |
analyze_btn.click(
|
159 |
+
fn=model_manager.analyze_image,
|
160 |
+
inputs=[image_input, question_input, model_choice],
|
161 |
+
outputs=output_text
|
162 |
)
|
163 |
|
164 |
if __name__ == "__main__":
|
165 |
+
print(f"Dispositivo: {'CUDA' if torch.cuda.is_available() else 'CPU'}")
|
166 |
+
iface.launch()
|