|
import gradio as gr |
|
from transformers import Blip2Processor, Blip2ForConditionalGeneration, pipeline |
|
from PIL import Image |
|
import requests |
|
|
|
|
|
processor = Blip2Processor.from_pretrained("Salesforce/blip2-opt-2.7b") |
|
model_blip2 = Blip2ForConditionalGeneration.from_pretrained("Salesforce/blip2-opt-2.7b") |
|
|
|
|
|
nutrition_model = pipeline("text2text-generation", model="google/flan-t5-large") |
|
|
|
def interpret_image(image): |
|
|
|
if isinstance(image, str): |
|
image = Image.open(requests.get(image, stream=True).raw) |
|
|
|
|
|
inputs = processor(image, return_tensors="pt") |
|
out = model_blip2.generate(**inputs) |
|
|
|
|
|
description = processor.decode(out[0], skip_special_tokens=True) |
|
|
|
|
|
description = description.strip().capitalize() |
|
if not description.endswith("."): |
|
description += "." |
|
|
|
return description |
|
|
|
def nutritional_analysis(image): |
|
|
|
description = interpret_image(image) |
|
|
|
|
|
prompt = ( |
|
f"Com base na descrição do prato de comida abaixo, forneça uma análise nutricional detalhada.\n\n" |
|
f"Descrição do prato: {description}\n\n" |
|
f"Siga este formato:\n" |
|
f"- Calorias totais estimadas: [valor]\n" |
|
f"- Macronutrientes (em gramas):\n" |
|
f" - Carboidratos: [valor]\n" |
|
f" - Proteínas: [valor]\n" |
|
f" - Gorduras: [valor]\n" |
|
f"- Recomendações para melhorar o prato: [sugestões]\n\n" |
|
f"Análise nutricional:" |
|
) |
|
|
|
|
|
analysis = nutrition_model(prompt, max_length=300)[0]['generated_text'] |
|
|
|
|
|
analysis = analysis.replace("Análise nutricional:", "").strip() |
|
|
|
|
|
return description, analysis |
|
|
|
|
|
with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue", secondary_hue="cyan")) as demo: |
|
|
|
with gr.Row(): |
|
gr.Markdown(""" |
|
# 🍽️ Agente Nutricionista Inteligente |
|
### Transforme suas refeições em escolhas saudáveis! |
|
- **Descrição automática** de pratos de comida com IA avançada. |
|
- **Análise nutricional detalhada** com estimativas de calorias e macronutrientes. |
|
- **Recomendações personalizadas** para melhorar sua dieta. |
|
""") |
|
|
|
|
|
with gr.Row(): |
|
with gr.Column(scale=1): |
|
gr.Markdown("### 📸 Carregue uma Imagem") |
|
image_input = gr.Image(type="pil", label="Upload de Imagem", height=300) |
|
|
|
with gr.Column(scale=2): |
|
gr.Markdown("### 🔍 Resultados") |
|
with gr.Tabs(): |
|
with gr.TabItem("Descrição do Prato"): |
|
description_output = gr.Textbox(label="Descrição Gerada", lines=3, interactive=False) |
|
|
|
with gr.TabItem("Análise Nutricional"): |
|
analysis_output = gr.Textbox(label="Análise Nutricional", lines=8, interactive=False) |
|
|
|
|
|
with gr.Row(): |
|
submit_button = gr.Button("✨ Analisar Prato", variant="primary") |
|
|
|
|
|
with gr.Row(): |
|
feedback = gr.Markdown("") |
|
|
|
|
|
def process_image(image): |
|
try: |
|
description, analysis = nutritional_analysis(image) |
|
feedback.update("✅ Análise concluída com sucesso!") |
|
return description, analysis |
|
except Exception as e: |
|
feedback.update(f"❌ Erro ao processar a imagem: {str(e)}") |
|
return "", "" |
|
|
|
|
|
submit_button.click(process_image, inputs=image_input, outputs=[description_output, analysis_output]) |
|
|
|
|
|
with gr.Row(): |
|
gr.Markdown(""" |
|
--- |
|
### 💡 Dicas para Melhores Resultados: |
|
- Use imagens claras e bem iluminadas. |
|
- Inclua todos os ingredientes visíveis no prato. |
|
- Experimente diferentes ângulos para capturar mais detalhes. |
|
|
|
### 🌟 Entre em Contato |
|
- Quer saber mais? Visite nosso [site](https://example.com) ou nos siga nas redes sociais! |
|
""") |
|
|
|
|
|
examples = [ |
|
"https://huggingface.co/spaces/DHEIVER/blip-image-captioning-base/blob/main/img.jpg" |
|
] |
|
gr.Examples(examples, inputs=image_input) |
|
|
|
|
|
demo.launch() |