Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,15 +1,23 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
-
import
|
| 3 |
-
|
| 4 |
-
import
|
| 5 |
-
from io import BytesIO
|
| 6 |
|
| 7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
"""
|
| 9 |
Função principal que processa a imagem e retorna os resultados formatados
|
| 10 |
"""
|
| 11 |
try:
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
| 13 |
nutrients = {
|
| 14 |
"calorias": 450,
|
| 15 |
"proteinas": 25,
|
|
@@ -19,8 +27,10 @@ def analyze_nutrition(image, api_key=""):
|
|
| 19 |
}
|
| 20 |
|
| 21 |
# Prepara dados para o gráfico
|
| 22 |
-
|
| 23 |
-
|
|
|
|
|
|
|
| 24 |
|
| 25 |
# Prepara tabela nutricional
|
| 26 |
table_data = [
|
|
@@ -39,24 +49,13 @@ def analyze_nutrition(image, api_key=""):
|
|
| 39 |
recommendations.append("⚠️ Baixo teor de proteínas - considere adicionar fontes proteicas")
|
| 40 |
if nutrients['fibras'] < 6:
|
| 41 |
recommendations.append("⚠️ Baixo teor de fibras - adicione mais vegetais")
|
| 42 |
-
|
| 43 |
recommendations_text = "\n".join(recommendations) if recommendations else "✅ Valores nutricionais dentro das recomendações!"
|
| 44 |
|
| 45 |
-
# Cria o gráfico
|
| 46 |
-
plot = gr.BarPlot(
|
| 47 |
-
value=(labels, values),
|
| 48 |
-
title="Distribuição de Macronutrientes",
|
| 49 |
-
x="Nutrientes",
|
| 50 |
-
y="Gramas",
|
| 51 |
-
tooltip=["Nutriente", "Quantidade (g)"],
|
| 52 |
-
height=300
|
| 53 |
-
)
|
| 54 |
-
|
| 55 |
-
# Retorna os componentes
|
| 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)}
|
|
@@ -78,29 +77,32 @@ with gr.Blocks(theme=gr.themes.Soft()) as iface:
|
|
| 78 |
sources=['upload', 'webcam'],
|
| 79 |
height=300
|
| 80 |
)
|
| 81 |
-
api_key = gr.Textbox(
|
| 82 |
-
label="API Key (opcional)",
|
| 83 |
-
placeholder="Digite sua API key aqui...",
|
| 84 |
-
type="password",
|
| 85 |
-
visible=False # Oculto por enquanto
|
| 86 |
-
)
|
| 87 |
analyze_btn = gr.Button("📊 Analisar", variant="primary")
|
| 88 |
|
| 89 |
with gr.Column(scale=2):
|
| 90 |
# Outputs
|
| 91 |
with gr.Tab("Resumo"):
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
|
| 105 |
with gr.Tab("Detalhes"):
|
| 106 |
json_output = gr.JSON()
|
|
@@ -108,7 +110,7 @@ with gr.Blocks(theme=gr.themes.Soft()) as iface:
|
|
| 108 |
# Eventos
|
| 109 |
analyze_btn.click(
|
| 110 |
fn=analyze_nutrition,
|
| 111 |
-
inputs=[image_input
|
| 112 |
outputs=[json_output, macro_plot, nutri_table, recommendations]
|
| 113 |
)
|
| 114 |
|
|
@@ -125,6 +127,10 @@ with gr.Blocks(theme=gr.themes.Soft()) as iface:
|
|
| 125 |
- Evite sombras ou reflexos fortes
|
| 126 |
""")
|
| 127 |
|
| 128 |
-
# Inicia a interface
|
| 129 |
if __name__ == "__main__":
|
| 130 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
import numpy as np
|
| 3 |
+
import os
|
| 4 |
+
from dotenv import load_dotenv
|
|
|
|
| 5 |
|
| 6 |
+
# Carrega variáveis de ambiente
|
| 7 |
+
load_dotenv()
|
| 8 |
+
|
| 9 |
+
# Obtém a API key da variável de ambiente
|
| 10 |
+
API_KEY = os.getenv('NUTRITION_API_KEY', '')
|
| 11 |
+
|
| 12 |
+
def analyze_nutrition(image):
|
| 13 |
"""
|
| 14 |
Função principal que processa a imagem e retorna os resultados formatados
|
| 15 |
"""
|
| 16 |
try:
|
| 17 |
+
if not API_KEY:
|
| 18 |
+
raise ValueError("API Key não encontrada nas variáveis de ambiente. Configure NUTRITION_API_KEY no arquivo .env")
|
| 19 |
+
|
| 20 |
+
# Simula resultado da análise (aqui você usaria a API_KEY para fazer a requisição real)
|
| 21 |
nutrients = {
|
| 22 |
"calorias": 450,
|
| 23 |
"proteinas": 25,
|
|
|
|
| 27 |
}
|
| 28 |
|
| 29 |
# Prepara dados para o gráfico
|
| 30 |
+
plot_data = (
|
| 31 |
+
["Proteínas", "Carboidratos", "Gorduras"],
|
| 32 |
+
[nutrients['proteinas'], nutrients['carboidratos'], nutrients['gorduras']]
|
| 33 |
+
)
|
| 34 |
|
| 35 |
# Prepara tabela nutricional
|
| 36 |
table_data = [
|
|
|
|
| 49 |
recommendations.append("⚠️ Baixo teor de proteínas - considere adicionar fontes proteicas")
|
| 50 |
if nutrients['fibras'] < 6:
|
| 51 |
recommendations.append("⚠️ Baixo teor de fibras - adicione mais vegetais")
|
| 52 |
+
|
| 53 |
recommendations_text = "\n".join(recommendations) if recommendations else "✅ Valores nutricionais dentro das recomendações!"
|
| 54 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
return {
|
| 56 |
"message": "Análise concluída com sucesso!",
|
| 57 |
"nutrients": nutrients
|
| 58 |
+
}, plot_data, table_data, recommendations_text
|
| 59 |
|
| 60 |
except Exception as e:
|
| 61 |
error_json = {"error": str(e)}
|
|
|
|
| 77 |
sources=['upload', 'webcam'],
|
| 78 |
height=300
|
| 79 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
analyze_btn = gr.Button("📊 Analisar", variant="primary")
|
| 81 |
|
| 82 |
with gr.Column(scale=2):
|
| 83 |
# Outputs
|
| 84 |
with gr.Tab("Resumo"):
|
| 85 |
+
with gr.Row():
|
| 86 |
+
recommendations = gr.Textbox(
|
| 87 |
+
label="Recomendações",
|
| 88 |
+
lines=3
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
with gr.Row():
|
| 92 |
+
nutri_table = gr.Dataframe(
|
| 93 |
+
headers=["Nutriente", "Quantidade"],
|
| 94 |
+
label="Informação Nutricional"
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
with gr.Row():
|
| 98 |
+
macro_plot = gr.BarPlot(
|
| 99 |
+
x="Nutriente",
|
| 100 |
+
y="Gramas",
|
| 101 |
+
title="Macronutrientes",
|
| 102 |
+
tooltip=["Nutriente", "Quantidade (g)"],
|
| 103 |
+
height=300,
|
| 104 |
+
label="Distribuição de Macronutrientes"
|
| 105 |
+
)
|
| 106 |
|
| 107 |
with gr.Tab("Detalhes"):
|
| 108 |
json_output = gr.JSON()
|
|
|
|
| 110 |
# Eventos
|
| 111 |
analyze_btn.click(
|
| 112 |
fn=analyze_nutrition,
|
| 113 |
+
inputs=[image_input],
|
| 114 |
outputs=[json_output, macro_plot, nutri_table, recommendations]
|
| 115 |
)
|
| 116 |
|
|
|
|
| 127 |
- Evite sombras ou reflexos fortes
|
| 128 |
""")
|
| 129 |
|
|
|
|
| 130 |
if __name__ == "__main__":
|
| 131 |
+
# Verifica se a API key está configurada
|
| 132 |
+
if not API_KEY:
|
| 133 |
+
print("⚠️ Atenção: API Key não encontrada!")
|
| 134 |
+
print("Configure a variável de ambiente NUTRITION_API_KEY no arquivo .env")
|
| 135 |
+
|
| 136 |
+
iface.launch(share=False)
|