Spaces:
Build error
Build error
| import gradio as gr | |
| import numpy as np | |
| import os | |
| from dotenv import load_dotenv | |
| # Carrega variáveis de ambiente | |
| load_dotenv() | |
| # Obtém a API key da variável de ambiente | |
| API_KEY = os.getenv('NUTRITION_API_KEY', '') | |
| def analyze_nutrition(image): | |
| """ | |
| Função principal que processa a imagem e retorna os resultados formatados | |
| """ | |
| try: | |
| if not API_KEY: | |
| raise ValueError("API Key não encontrada nas variáveis de ambiente. Configure NUTRITION_API_KEY no arquivo .env") | |
| # Simula resultado da análise (aqui você usaria a API_KEY para fazer a requisição real) | |
| nutrients = { | |
| "calorias": 450, | |
| "proteinas": 25, | |
| "carboidratos": 55, | |
| "gorduras": 15, | |
| "fibras": 8 | |
| } | |
| # Prepara dados para o gráfico | |
| plot_data = ( | |
| ["Proteínas", "Carboidratos", "Gorduras"], | |
| [nutrients['proteinas'], nutrients['carboidratos'], nutrients['gorduras']] | |
| ) | |
| # Prepara tabela nutricional | |
| table_data = [ | |
| ["Calorias", f"{nutrients['calorias']:.1f} kcal"], | |
| ["Proteínas", f"{nutrients['proteinas']:.1f}g"], | |
| ["Carboidratos", f"{nutrients['carboidratos']:.1f}g"], | |
| ["Gorduras", f"{nutrients['gorduras']:.1f}g"], | |
| ["Fibras", f"{nutrients['fibras']:.1f}g"] | |
| ] | |
| # Prepara recomendações | |
| recommendations = [] | |
| if nutrients['calorias'] > 800: | |
| recommendations.append("⚠️ Alto valor calórico - considere reduzir as porções") | |
| if nutrients['proteinas'] < 15: | |
| recommendations.append("⚠️ Baixo teor de proteínas - considere adicionar fontes proteicas") | |
| if nutrients['fibras'] < 6: | |
| recommendations.append("⚠️ Baixo teor de fibras - adicione mais vegetais") | |
| recommendations_text = "\n".join(recommendations) if recommendations else "✅ Valores nutricionais dentro das recomendações!" | |
| return { | |
| "message": "Análise concluída com sucesso!", | |
| "nutrients": nutrients | |
| }, plot_data, table_data, recommendations_text | |
| except Exception as e: | |
| error_json = {"error": str(e)} | |
| return error_json, None, None, f"Erro na análise: {str(e)}" | |
| # Interface Gradio | |
| with gr.Blocks(theme=gr.themes.Soft()) as iface: | |
| gr.Markdown(""" | |
| # 🍽️ Análise Nutricional com IA | |
| Faça upload de uma foto do seu prato para receber uma análise nutricional detalhada. | |
| """) | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| # Inputs | |
| image_input = gr.Image( | |
| type="pil", | |
| label="Foto do Prato", | |
| sources=['upload', 'webcam'], | |
| height=300 | |
| ) | |
| analyze_btn = gr.Button("📊 Analisar", variant="primary") | |
| with gr.Column(scale=2): | |
| # Outputs | |
| with gr.Tab("Resumo"): | |
| with gr.Row(): | |
| recommendations = gr.Textbox( | |
| label="Recomendações", | |
| lines=3 | |
| ) | |
| with gr.Row(): | |
| nutri_table = gr.Dataframe( | |
| headers=["Nutriente", "Quantidade"], | |
| label="Informação Nutricional" | |
| ) | |
| with gr.Row(): | |
| macro_plot = gr.BarPlot( | |
| x="Nutriente", | |
| y="Gramas", | |
| title="Macronutrientes", | |
| tooltip=["Nutriente", "Quantidade (g)"], | |
| height=300, | |
| label="Distribuição de Macronutrientes" | |
| ) | |
| with gr.Tab("Detalhes"): | |
| json_output = gr.JSON() | |
| # Eventos | |
| analyze_btn.click( | |
| fn=analyze_nutrition, | |
| inputs=[image_input], | |
| outputs=[json_output, macro_plot, nutri_table, recommendations] | |
| ) | |
| gr.Markdown(""" | |
| ### 📝 Instruções | |
| 1. Faça upload de uma foto do seu prato ou tire uma foto com a webcam | |
| 2. Clique em "Analisar" | |
| 3. Veja os resultados nas abas "Resumo" e "Detalhes" | |
| ### 🎯 Dicas para melhores resultados | |
| - Use fotos bem iluminadas | |
| - Fotografe de cima para baixo | |
| - Certifique-se que todos os alimentos estão visíveis | |
| - Evite sombras ou reflexos fortes | |
| """) | |
| if __name__ == "__main__": | |
| # Verifica se a API key está configurada | |
| if not API_KEY: | |
| print("⚠️ Atenção: API Key não encontrada!") | |
| print("Configure a variável de ambiente NUTRITION_API_KEY no arquivo .env") | |
| iface.launch(share=False) |