Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,10 +1,10 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
from transformers import Blip2Processor, Blip2ForConditionalGeneration, pipeline
|
| 3 |
from PIL import Image
|
| 4 |
-
import requests
|
| 5 |
import os
|
| 6 |
import io
|
| 7 |
from functools import lru_cache
|
|
|
|
| 8 |
|
| 9 |
# Função para verificar se o modelo existe localmente
|
| 10 |
def check_model_locally(model_name):
|
|
@@ -23,7 +23,7 @@ else:
|
|
| 23 |
processor = Blip2Processor.from_pretrained(model_blip2_name)
|
| 24 |
model_blip2 = Blip2ForConditionalGeneration.from_pretrained(model_blip2_name)
|
| 25 |
|
| 26 |
-
# Carregar
|
| 27 |
nutrition_model_name = "google/flan-t5-large"
|
| 28 |
if check_model_locally(nutrition_model_name):
|
| 29 |
print(f"Modelo {nutrition_model_name} encontrado localmente.")
|
|
@@ -35,27 +35,18 @@ else:
|
|
| 35 |
# Função para interpretar a imagem com cache
|
| 36 |
@lru_cache(maxsize=128)
|
| 37 |
def interpret_image_cached(image_bytes):
|
| 38 |
-
|
| 39 |
-
image = Image.open(io.BytesIO(image_bytes))
|
| 40 |
-
|
| 41 |
-
# Processar a imagem e gerar a descrição usando BLIP-2
|
| 42 |
inputs = processor(image, return_tensors="pt")
|
| 43 |
out = model_blip2.generate(**inputs)
|
| 44 |
-
|
| 45 |
-
# Decodificar a saída para texto
|
| 46 |
description = processor.decode(out[0], skip_special_tokens=True)
|
| 47 |
-
|
| 48 |
-
# Pós-processamento para melhorar a descrição
|
| 49 |
description = description.strip().capitalize()
|
| 50 |
if not description.endswith("."):
|
| 51 |
description += "."
|
| 52 |
-
|
| 53 |
return description
|
| 54 |
|
| 55 |
# Função para análise nutricional com cache
|
| 56 |
@lru_cache(maxsize=128)
|
| 57 |
def nutritional_analysis_cached(description):
|
| 58 |
-
# Criar um prompt refinado para análise nutricional
|
| 59 |
prompt = (
|
| 60 |
f"Com base na descrição do prato de comida abaixo, forneça uma análise nutricional detalhada.\n\n"
|
| 61 |
f"Descrição do prato: {description}\n\n"
|
|
@@ -68,91 +59,117 @@ def nutritional_analysis_cached(description):
|
|
| 68 |
f"- Recomendações para melhorar o prato: [sugestões]\n\n"
|
| 69 |
f"Análise nutricional:"
|
| 70 |
)
|
| 71 |
-
|
| 72 |
-
# Usar o modelo de linguagem para gerar a análise nutricional
|
| 73 |
analysis = nutrition_model(prompt, max_length=300)[0]['generated_text']
|
| 74 |
-
|
| 75 |
-
# Pós-processamento para formatar a análise nutricional
|
| 76 |
analysis = analysis.replace("Análise nutricional:", "").strip()
|
| 77 |
-
|
| 78 |
return analysis
|
| 79 |
|
| 80 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue", secondary_hue="cyan")) as demo:
|
| 82 |
-
# Cabeçalho com Marketing
|
| 83 |
with gr.Row():
|
| 84 |
gr.Markdown("""
|
| 85 |
-
# 🍽️ Agente Nutricionista Inteligente
|
| 86 |
-
###
|
| 87 |
-
- **Descrição automática** de pratos
|
| 88 |
-
- **Análise nutricional detalhada** com estimativas de calorias e macronutrientes.
|
| 89 |
-
- **
|
|
|
|
| 90 |
""")
|
| 91 |
-
|
| 92 |
-
# Seção de Upload de Imagem
|
| 93 |
with gr.Row():
|
| 94 |
with gr.Column(scale=1):
|
| 95 |
gr.Markdown("### 📸 Carregue uma Imagem")
|
| 96 |
image_input = gr.Image(type="pil", label="Upload de Imagem", height=300)
|
| 97 |
-
|
| 98 |
with gr.Column(scale=2):
|
| 99 |
gr.Markdown("### 🔍 Resultados")
|
| 100 |
with gr.Tabs():
|
| 101 |
with gr.TabItem("Descrição do Prato"):
|
| 102 |
description_output = gr.Textbox(label="Descrição Gerada", lines=3, interactive=False)
|
| 103 |
-
|
| 104 |
with gr.TabItem("Análise Nutricional"):
|
| 105 |
analysis_output = gr.Textbox(label="Análise Nutricional", lines=8, interactive=False)
|
| 106 |
-
|
| 107 |
-
|
|
|
|
|
|
|
|
|
|
| 108 |
with gr.Row():
|
| 109 |
submit_button = gr.Button("✨ Analisar Prato", variant="primary")
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
feedback.update("✅ Análise concluída com sucesso!")
|
| 130 |
-
return description, analysis
|
| 131 |
-
except Exception as e:
|
| 132 |
-
feedback.update(f"❌ Erro ao processar a imagem: {str(e)}")
|
| 133 |
-
return "", ""
|
| 134 |
-
|
| 135 |
-
# Conectar botão aos outputs
|
| 136 |
-
submit_button.click(process_image, inputs=image_input, outputs=[description_output, analysis_output])
|
| 137 |
-
|
| 138 |
-
# Rodapé com Chamada à Ação
|
| 139 |
with gr.Row():
|
| 140 |
gr.Markdown("""
|
| 141 |
---
|
| 142 |
### 💡 Dicas para Melhores Resultados:
|
| 143 |
-
-
|
| 144 |
-
-
|
| 145 |
-
- Experimente diferentes ângulos para capturar
|
| 146 |
|
| 147 |
-
### 🌟
|
| 148 |
-
-
|
| 149 |
""")
|
| 150 |
-
|
| 151 |
-
# Adicionar exemplos pré-definidos
|
| 152 |
examples = [
|
| 153 |
"https://huggingface.co/spaces/DHEIVER/blip-image-captioning-base/blob/main/img.jpg"
|
| 154 |
]
|
| 155 |
gr.Examples(examples, inputs=image_input)
|
| 156 |
|
| 157 |
-
|
| 158 |
-
demo.launch()
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
from transformers import Blip2Processor, Blip2ForConditionalGeneration, pipeline
|
| 3 |
from PIL import Image
|
|
|
|
| 4 |
import os
|
| 5 |
import io
|
| 6 |
from functools import lru_cache
|
| 7 |
+
import tempfile
|
| 8 |
|
| 9 |
# Função para verificar se o modelo existe localmente
|
| 10 |
def check_model_locally(model_name):
|
|
|
|
| 23 |
processor = Blip2Processor.from_pretrained(model_blip2_name)
|
| 24 |
model_blip2 = Blip2ForConditionalGeneration.from_pretrained(model_blip2_name)
|
| 25 |
|
| 26 |
+
# Carregar o modelo de linguagem para análise nutricional (exemplo: Flan-T5)
|
| 27 |
nutrition_model_name = "google/flan-t5-large"
|
| 28 |
if check_model_locally(nutrition_model_name):
|
| 29 |
print(f"Modelo {nutrition_model_name} encontrado localmente.")
|
|
|
|
| 35 |
# Função para interpretar a imagem com cache
|
| 36 |
@lru_cache(maxsize=128)
|
| 37 |
def interpret_image_cached(image_bytes):
|
| 38 |
+
image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
|
|
|
|
|
|
|
|
|
|
| 39 |
inputs = processor(image, return_tensors="pt")
|
| 40 |
out = model_blip2.generate(**inputs)
|
|
|
|
|
|
|
| 41 |
description = processor.decode(out[0], skip_special_tokens=True)
|
|
|
|
|
|
|
| 42 |
description = description.strip().capitalize()
|
| 43 |
if not description.endswith("."):
|
| 44 |
description += "."
|
|
|
|
| 45 |
return description
|
| 46 |
|
| 47 |
# Função para análise nutricional com cache
|
| 48 |
@lru_cache(maxsize=128)
|
| 49 |
def nutritional_analysis_cached(description):
|
|
|
|
| 50 |
prompt = (
|
| 51 |
f"Com base na descrição do prato de comida abaixo, forneça uma análise nutricional detalhada.\n\n"
|
| 52 |
f"Descrição do prato: {description}\n\n"
|
|
|
|
| 59 |
f"- Recomendações para melhorar o prato: [sugestões]\n\n"
|
| 60 |
f"Análise nutricional:"
|
| 61 |
)
|
|
|
|
|
|
|
| 62 |
analysis = nutrition_model(prompt, max_length=300)[0]['generated_text']
|
|
|
|
|
|
|
| 63 |
analysis = analysis.replace("Análise nutricional:", "").strip()
|
|
|
|
| 64 |
return analysis
|
| 65 |
|
| 66 |
+
# Função para gerar dicas de saúde com cache
|
| 67 |
+
@lru_cache(maxsize=128)
|
| 68 |
+
def health_tips_cached(description):
|
| 69 |
+
prompt = (
|
| 70 |
+
f"Com base na descrição do prato de comida abaixo, forneça dicas de saúde e sugestões "
|
| 71 |
+
f"para melhorar o prato, tornando-o mais equilibrado e nutritivo. Liste as dicas em tópicos.\n\n"
|
| 72 |
+
f"Descrição do prato: {description}\n\n"
|
| 73 |
+
f"Dicas de saúde:"
|
| 74 |
+
)
|
| 75 |
+
tips = nutrition_model(prompt, max_length=150)[0]['generated_text']
|
| 76 |
+
tips = tips.replace("Dicas de saúde:", "").strip()
|
| 77 |
+
return tips
|
| 78 |
+
|
| 79 |
+
# Função para processar a imagem e gerar todos os resultados
|
| 80 |
+
def process_image(image):
|
| 81 |
+
try:
|
| 82 |
+
# Converter a imagem para bytes e gerar a descrição com cache
|
| 83 |
+
buffered = io.BytesIO()
|
| 84 |
+
image.save(buffered, format="JPEG")
|
| 85 |
+
image_bytes = buffered.getvalue()
|
| 86 |
+
|
| 87 |
+
description = interpret_image_cached(image_bytes)
|
| 88 |
+
analysis = nutritional_analysis_cached(description)
|
| 89 |
+
tips = health_tips_cached(description)
|
| 90 |
+
complete_result = (
|
| 91 |
+
f"Descrição do Prato:\n{description}\n\n"
|
| 92 |
+
f"Análise Nutricional:\n{analysis}\n\n"
|
| 93 |
+
f"Dicas de Saúde:\n{tips}"
|
| 94 |
+
)
|
| 95 |
+
feedback_message = "✅ Análise concluída com sucesso!"
|
| 96 |
+
# Retorne os 5 outputs: cada aba e um estado oculto com o resultado completo
|
| 97 |
+
return description, analysis, tips, complete_result, complete_result, feedback_message
|
| 98 |
+
except Exception as e:
|
| 99 |
+
feedback_message = f"❌ Erro ao processar a imagem: {str(e)}"
|
| 100 |
+
return "", "", "", "", "", feedback_message
|
| 101 |
+
|
| 102 |
+
# Função para gerar um arquivo de download com o resultado completo
|
| 103 |
+
def generate_download(complete_result):
|
| 104 |
+
try:
|
| 105 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".txt", mode="w", encoding="utf-8") as tmp:
|
| 106 |
+
tmp.write(complete_result)
|
| 107 |
+
return tmp.name
|
| 108 |
+
except Exception as e:
|
| 109 |
+
return None
|
| 110 |
+
|
| 111 |
with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue", secondary_hue="cyan")) as demo:
|
|
|
|
| 112 |
with gr.Row():
|
| 113 |
gr.Markdown("""
|
| 114 |
+
# 🍽️ Agente Nutricionista Inteligente Avançado
|
| 115 |
+
### Revolucione a análise de suas refeições com IA de última geração!
|
| 116 |
+
- **Descrição automática** de pratos a partir de imagens.
|
| 117 |
+
- **Análise nutricional detalhada** com estimativas precisas de calorias e macronutrientes.
|
| 118 |
+
- **Dicas de saúde personalizadas** para aprimorar sua alimentação.
|
| 119 |
+
- **Resultado completo para download** em formato TXT.
|
| 120 |
""")
|
| 121 |
+
|
|
|
|
| 122 |
with gr.Row():
|
| 123 |
with gr.Column(scale=1):
|
| 124 |
gr.Markdown("### 📸 Carregue uma Imagem")
|
| 125 |
image_input = gr.Image(type="pil", label="Upload de Imagem", height=300)
|
|
|
|
| 126 |
with gr.Column(scale=2):
|
| 127 |
gr.Markdown("### 🔍 Resultados")
|
| 128 |
with gr.Tabs():
|
| 129 |
with gr.TabItem("Descrição do Prato"):
|
| 130 |
description_output = gr.Textbox(label="Descrição Gerada", lines=3, interactive=False)
|
|
|
|
| 131 |
with gr.TabItem("Análise Nutricional"):
|
| 132 |
analysis_output = gr.Textbox(label="Análise Nutricional", lines=8, interactive=False)
|
| 133 |
+
with gr.TabItem("Dicas de Saúde"):
|
| 134 |
+
tips_output = gr.Textbox(label="Dicas de Saúde", lines=6, interactive=False)
|
| 135 |
+
with gr.TabItem("Resultado Completo"):
|
| 136 |
+
complete_result_output = gr.Textbox(label="Resultado Completo", lines=15, interactive=False)
|
| 137 |
+
|
| 138 |
with gr.Row():
|
| 139 |
submit_button = gr.Button("✨ Analisar Prato", variant="primary")
|
| 140 |
+
download_button = gr.Button("💾 Baixar Resultado", variant="secondary")
|
| 141 |
+
|
| 142 |
+
# Estado oculto para armazenar o resultado completo para o download
|
| 143 |
+
result_state = gr.State("")
|
| 144 |
+
feedback = gr.Markdown("")
|
| 145 |
+
|
| 146 |
+
submit_button.click(
|
| 147 |
+
process_image,
|
| 148 |
+
inputs=image_input,
|
| 149 |
+
outputs=[description_output, analysis_output, tips_output, complete_result_output, result_state, feedback]
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
download_button.click(
|
| 153 |
+
generate_download,
|
| 154 |
+
inputs=result_state,
|
| 155 |
+
outputs=gr.File(label="Seu Resultado")
|
| 156 |
+
)
|
| 157 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
with gr.Row():
|
| 159 |
gr.Markdown("""
|
| 160 |
---
|
| 161 |
### 💡 Dicas para Melhores Resultados:
|
| 162 |
+
- Utilize imagens de alta resolução e boa iluminação.
|
| 163 |
+
- Certifique-se de que todos os ingredientes estejam visíveis.
|
| 164 |
+
- Experimente diferentes ângulos para capturar os detalhes do prato.
|
| 165 |
|
| 166 |
+
### 🌟 Conecte-se Conosco
|
| 167 |
+
- Para mais informações, visite nosso site oficial ou siga nossas redes sociais!
|
| 168 |
""")
|
| 169 |
+
|
|
|
|
| 170 |
examples = [
|
| 171 |
"https://huggingface.co/spaces/DHEIVER/blip-image-captioning-base/blob/main/img.jpg"
|
| 172 |
]
|
| 173 |
gr.Examples(examples, inputs=image_input)
|
| 174 |
|
| 175 |
+
demo.launch()
|
|
|