Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
@@ -3,6 +3,8 @@ import numpy as np
|
|
3 |
import os
|
4 |
from dotenv import load_dotenv
|
5 |
import pandas as pd
|
|
|
|
|
6 |
|
7 |
# Carrega variáveis de ambiente
|
8 |
load_dotenv()
|
@@ -10,6 +12,30 @@ load_dotenv()
|
|
10 |
# Obtém a API key da variável de ambiente
|
11 |
API_KEY = os.getenv('NUTRITION_API_KEY', '')
|
12 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
13 |
def analyze_nutrition(image):
|
14 |
"""
|
15 |
Função principal que processa a imagem e retorna os resultados formatados
|
@@ -17,6 +43,9 @@ def analyze_nutrition(image):
|
|
17 |
try:
|
18 |
if not API_KEY:
|
19 |
raise ValueError("API Key não encontrada nas variáveis de ambiente. Configure NUTRITION_API_KEY no arquivo .env")
|
|
|
|
|
|
|
20 |
|
21 |
# Simula resultado da análise (aqui você usaria a API_KEY para fazer a requisição real)
|
22 |
nutrients = {
|
@@ -53,14 +82,18 @@ def analyze_nutrition(image):
|
|
53 |
|
54 |
recommendations_text = "\n".join(recommendations) if recommendations else "✅ Valores nutricionais dentro das recomendações!"
|
55 |
|
|
|
|
|
|
|
56 |
return {
|
57 |
"message": "Análise concluída com sucesso!",
|
58 |
-
"nutrients": nutrients
|
59 |
-
|
|
|
60 |
|
61 |
except Exception as e:
|
62 |
error_json = {"error": str(e)}
|
63 |
-
return error_json, None, None, f"Erro na análise: {str(e)}"
|
64 |
|
65 |
# Interface Gradio
|
66 |
with gr.Blocks(theme=gr.themes.Soft()) as iface:
|
@@ -83,6 +116,12 @@ with gr.Blocks(theme=gr.themes.Soft()) as iface:
|
|
83 |
with gr.Column(scale=2):
|
84 |
# Outputs
|
85 |
with gr.Tab("Resumo"):
|
|
|
|
|
|
|
|
|
|
|
|
|
86 |
with gr.Row():
|
87 |
recommendations = gr.Textbox(
|
88 |
label="Recomendações",
|
@@ -112,7 +151,7 @@ with gr.Blocks(theme=gr.themes.Soft()) as iface:
|
|
112 |
analyze_btn.click(
|
113 |
fn=analyze_nutrition,
|
114 |
inputs=[image_input],
|
115 |
-
outputs=[json_output, macro_plot, nutri_table, recommendations]
|
116 |
)
|
117 |
|
118 |
gr.Markdown("""
|
|
|
3 |
import os
|
4 |
from dotenv import load_dotenv
|
5 |
import pandas as pd
|
6 |
+
from transformers import Blip2Processor, Blip2ForConditionalGeneration
|
7 |
+
import torch
|
8 |
|
9 |
# Carrega variáveis de ambiente
|
10 |
load_dotenv()
|
|
|
12 |
# Obtém a API key da variável de ambiente
|
13 |
API_KEY = os.getenv('NUTRITION_API_KEY', '')
|
14 |
|
15 |
+
# Carrega o modelo BLIP2 para identificação de alimentos
|
16 |
+
model_name = "Salesforce/blip2-opt-2.7b"
|
17 |
+
processor = Blip2Processor.from_pretrained(model_name)
|
18 |
+
model = Blip2ForConditionalGeneration.from_pretrained(model_name, torch_dtype=torch.float16, device_map="auto")
|
19 |
+
|
20 |
+
def identify_foods(image):
|
21 |
+
"""
|
22 |
+
Usa o modelo BLIP2 para identificar alimentos na imagem
|
23 |
+
"""
|
24 |
+
prompt = "Liste todos os alimentos visíveis nesta imagem de refeição."
|
25 |
+
inputs = processor(image, text=prompt, return_tensors="pt").to(model.device)
|
26 |
+
|
27 |
+
outputs = model.generate(
|
28 |
+
**inputs,
|
29 |
+
max_new_tokens=100,
|
30 |
+
do_sample=False,
|
31 |
+
num_beams=5,
|
32 |
+
temperature=1.0,
|
33 |
+
top_p=0.9,
|
34 |
+
)
|
35 |
+
|
36 |
+
description = processor.decode(outputs[0], skip_special_tokens=True)
|
37 |
+
return description
|
38 |
+
|
39 |
def analyze_nutrition(image):
|
40 |
"""
|
41 |
Função principal que processa a imagem e retorna os resultados formatados
|
|
|
43 |
try:
|
44 |
if not API_KEY:
|
45 |
raise ValueError("API Key não encontrada nas variáveis de ambiente. Configure NUTRITION_API_KEY no arquivo .env")
|
46 |
+
|
47 |
+
# Identifica os alimentos na imagem
|
48 |
+
identified_foods = identify_foods(image)
|
49 |
|
50 |
# Simula resultado da análise (aqui você usaria a API_KEY para fazer a requisição real)
|
51 |
nutrients = {
|
|
|
82 |
|
83 |
recommendations_text = "\n".join(recommendations) if recommendations else "✅ Valores nutricionais dentro das recomendações!"
|
84 |
|
85 |
+
# Formata a descrição dos alimentos identificados
|
86 |
+
foods_identified = f"🔍 Alimentos Identificados:\n{identified_foods}"
|
87 |
+
|
88 |
return {
|
89 |
"message": "Análise concluída com sucesso!",
|
90 |
+
"nutrients": nutrients,
|
91 |
+
"foods_identified": foods_identified
|
92 |
+
}, plot_data, table_data, foods_identified, recommendations_text
|
93 |
|
94 |
except Exception as e:
|
95 |
error_json = {"error": str(e)}
|
96 |
+
return error_json, None, None, f"Erro na análise: {str(e)}", ""
|
97 |
|
98 |
# Interface Gradio
|
99 |
with gr.Blocks(theme=gr.themes.Soft()) as iface:
|
|
|
116 |
with gr.Column(scale=2):
|
117 |
# Outputs
|
118 |
with gr.Tab("Resumo"):
|
119 |
+
with gr.Row():
|
120 |
+
foods_detected = gr.Textbox(
|
121 |
+
label="Alimentos Identificados",
|
122 |
+
lines=3
|
123 |
+
)
|
124 |
+
|
125 |
with gr.Row():
|
126 |
recommendations = gr.Textbox(
|
127 |
label="Recomendações",
|
|
|
151 |
analyze_btn.click(
|
152 |
fn=analyze_nutrition,
|
153 |
inputs=[image_input],
|
154 |
+
outputs=[json_output, macro_plot, nutri_table, foods_detected, recommendations]
|
155 |
)
|
156 |
|
157 |
gr.Markdown("""
|