Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,52 +1,36 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
-
from
|
| 3 |
from PIL import Image
|
| 4 |
-
import os
|
| 5 |
import io
|
| 6 |
from functools import lru_cache
|
| 7 |
import tempfile
|
| 8 |
|
| 9 |
-
#
|
| 10 |
-
|
| 11 |
-
cache_dir = os.path.expanduser("~/.cache/huggingface/transformers")
|
| 12 |
-
model_path = os.path.join(cache_dir, model_name.replace("/", "--"))
|
| 13 |
-
return os.path.exists(model_path)
|
| 14 |
|
| 15 |
-
#
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
model_blip2 = Blip2ForConditionalGeneration.from_pretrained(model_blip2_name, local_files_only=True)
|
| 21 |
-
else:
|
| 22 |
-
print(f"Modelo {model_blip2_name} não encontrado localmente. Baixando...")
|
| 23 |
-
processor = Blip2Processor.from_pretrained(model_blip2_name)
|
| 24 |
-
model_blip2 = Blip2ForConditionalGeneration.from_pretrained(model_blip2_name)
|
| 25 |
|
| 26 |
-
#
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
print(f"Modelo {nutrition_model_name} encontrado localmente.")
|
| 30 |
-
nutrition_model = pipeline("text2text-generation", model=nutrition_model_name, local_files_only=True)
|
| 31 |
-
else:
|
| 32 |
-
print(f"Modelo {nutrition_model_name} não encontrado localmente. Baixando...")
|
| 33 |
-
nutrition_model = pipeline("text2text-generation", model=nutrition_model_name)
|
| 34 |
|
| 35 |
-
#
|
| 36 |
@lru_cache(maxsize=128)
|
| 37 |
def interpret_image_cached(image_bytes):
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 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,27 +43,27 @@ def nutritional_analysis_cached(description):
|
|
| 59 |
f"- Recomendações para melhorar o prato: [sugestões]\n\n"
|
| 60 |
f"Análise nutricional:"
|
| 61 |
)
|
| 62 |
-
|
| 63 |
-
analysis =
|
| 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 |
-
|
| 76 |
-
tips =
|
| 77 |
return tips
|
| 78 |
|
| 79 |
-
# Função para processar a imagem e gerar
|
| 80 |
def process_image(image):
|
| 81 |
try:
|
| 82 |
-
# Converter a imagem para bytes
|
| 83 |
buffered = io.BytesIO()
|
| 84 |
image.save(buffered, format="JPEG")
|
| 85 |
image_bytes = buffered.getvalue()
|
|
@@ -93,7 +77,6 @@ def process_image(image):
|
|
| 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)}"
|
|
@@ -105,24 +88,26 @@ def generate_download(complete_result):
|
|
| 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
|
| 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():
|
|
@@ -134,42 +119,35 @@ with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue", secondary_hue="cyan")) a
|
|
| 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 |
-
|
| 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
|
| 150 |
)
|
| 151 |
-
|
| 152 |
download_button.click(
|
| 153 |
generate_download,
|
| 154 |
inputs=result_state,
|
| 155 |
outputs=gr.File(label="Seu Resultado")
|
| 156 |
)
|
| 157 |
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 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()
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
from huggingface_hub import InferenceApi
|
| 3 |
from PIL import Image
|
|
|
|
| 4 |
import io
|
| 5 |
from functools import lru_cache
|
| 6 |
import tempfile
|
| 7 |
|
| 8 |
+
# Variável global para armazenar o token da API (padrão vazio)
|
| 9 |
+
API_TOKEN = ""
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
+
# Função para atualizar o token da API
|
| 12 |
+
def update_api_token(new_token):
|
| 13 |
+
global API_TOKEN
|
| 14 |
+
API_TOKEN = new_token.strip()
|
| 15 |
+
return f"✅ Token atualizado com sucesso: {API_TOKEN[:8]}... (ocultado)"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
+
# Função para criar uma instância da API com o token atualizado
|
| 18 |
+
def get_inference_api(repo_id):
|
| 19 |
+
return InferenceApi(repo_id=repo_id, token=API_TOKEN)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
+
# Funções para os modelos utilizando a API Hugging Face
|
| 22 |
@lru_cache(maxsize=128)
|
| 23 |
def interpret_image_cached(image_bytes):
|
| 24 |
+
captioning_api = get_inference_api("Salesforce/blip2-opt-2.7b")
|
| 25 |
+
response = captioning_api(image_bytes)
|
| 26 |
+
description = response.get("generated_text", "").strip().capitalize()
|
|
|
|
|
|
|
| 27 |
if not description.endswith("."):
|
| 28 |
description += "."
|
| 29 |
return description
|
| 30 |
|
|
|
|
| 31 |
@lru_cache(maxsize=128)
|
| 32 |
def nutritional_analysis_cached(description):
|
| 33 |
+
nutrition_api = get_inference_api("google/flan-t5-large")
|
| 34 |
prompt = (
|
| 35 |
f"Com base na descrição do prato de comida abaixo, forneça uma análise nutricional detalhada.\n\n"
|
| 36 |
f"Descrição do prato: {description}\n\n"
|
|
|
|
| 43 |
f"- Recomendações para melhorar o prato: [sugestões]\n\n"
|
| 44 |
f"Análise nutricional:"
|
| 45 |
)
|
| 46 |
+
response = nutrition_api(prompt, max_length=300)
|
| 47 |
+
analysis = response.get("generated_text", "").replace("Análise nutricional:", "").strip()
|
| 48 |
return analysis
|
| 49 |
|
|
|
|
| 50 |
@lru_cache(maxsize=128)
|
| 51 |
def health_tips_cached(description):
|
| 52 |
+
nutrition_api = get_inference_api("google/flan-t5-large")
|
| 53 |
prompt = (
|
| 54 |
f"Com base na descrição do prato de comida abaixo, forneça dicas de saúde e sugestões "
|
| 55 |
f"para melhorar o prato, tornando-o mais equilibrado e nutritivo. Liste as dicas em tópicos.\n\n"
|
| 56 |
f"Descrição do prato: {description}\n\n"
|
| 57 |
f"Dicas de saúde:"
|
| 58 |
)
|
| 59 |
+
response = nutrition_api(prompt, max_length=150)
|
| 60 |
+
tips = response.get("generated_text", "").replace("Dicas de saúde:", "").strip()
|
| 61 |
return tips
|
| 62 |
|
| 63 |
+
# Função principal para processar a imagem e gerar resultados
|
| 64 |
def process_image(image):
|
| 65 |
try:
|
| 66 |
+
# Converter a imagem para bytes para uso com as APIs
|
| 67 |
buffered = io.BytesIO()
|
| 68 |
image.save(buffered, format="JPEG")
|
| 69 |
image_bytes = buffered.getvalue()
|
|
|
|
| 77 |
f"Dicas de Saúde:\n{tips}"
|
| 78 |
)
|
| 79 |
feedback_message = "✅ Análise concluída com sucesso!"
|
|
|
|
| 80 |
return description, analysis, tips, complete_result, complete_result, feedback_message
|
| 81 |
except Exception as e:
|
| 82 |
feedback_message = f"❌ Erro ao processar a imagem: {str(e)}"
|
|
|
|
| 88 |
with tempfile.NamedTemporaryFile(delete=False, suffix=".txt", mode="w", encoding="utf-8") as tmp:
|
| 89 |
tmp.write(complete_result)
|
| 90 |
return tmp.name
|
| 91 |
+
except Exception:
|
| 92 |
return None
|
| 93 |
|
| 94 |
+
# Interface Gradio com aba Settings para configurar o token da API
|
| 95 |
with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue", secondary_hue="cyan")) as demo:
|
| 96 |
with gr.Row():
|
| 97 |
gr.Markdown("""
|
| 98 |
# 🍽️ Agente Nutricionista Inteligente Avançado
|
| 99 |
### Revolucione a análise de suas refeições com IA de última geração!
|
| 100 |
+
- **[Descrição automática](pplx://action/followup)** de pratos a partir de imagens.
|
| 101 |
+
- **[Análise nutricional detalhada](pplx://action/followup)** com estimativas precisas de calorias e macronutrientes.
|
| 102 |
+
- **[Dicas de saúde personalizadas](pplx://action/followup)** para aprimorar sua alimentação.
|
| 103 |
+
- **[Resultado completo para download](pplx://action/followup)** em formato TXT.
|
| 104 |
""")
|
| 105 |
|
| 106 |
with gr.Row():
|
| 107 |
with gr.Column(scale=1):
|
| 108 |
gr.Markdown("### 📸 Carregue uma Imagem")
|
| 109 |
image_input = gr.Image(type="pil", label="Upload de Imagem", height=300)
|
| 110 |
+
|
| 111 |
with gr.Column(scale=2):
|
| 112 |
gr.Markdown("### 🔍 Resultados")
|
| 113 |
with gr.Tabs():
|
|
|
|
| 119 |
tips_output = gr.Textbox(label="Dicas de Saúde", lines=6, interactive=False)
|
| 120 |
with gr.TabItem("Resultado Completo"):
|
| 121 |
complete_result_output = gr.Textbox(label="Resultado Completo", lines=15, interactive=False)
|
| 122 |
+
with gr.TabItem("Settings"):
|
| 123 |
+
api_token_input = gr.Textbox(label="Token da API Hugging Face", placeholder="Insira seu token aqui...")
|
| 124 |
+
update_button = gr.Button("Atualizar Token")
|
| 125 |
+
update_feedback = gr.Markdown("")
|
| 126 |
+
|
| 127 |
with gr.Row():
|
| 128 |
submit_button = gr.Button("✨ Analisar Prato", variant="primary")
|
| 129 |
download_button = gr.Button("💾 Baixar Resultado", variant="secondary")
|
| 130 |
|
| 131 |
# Estado oculto para armazenar o resultado completo para o download
|
| 132 |
result_state = gr.State("")
|
| 133 |
+
|
|
|
|
| 134 |
submit_button.click(
|
| 135 |
process_image,
|
| 136 |
inputs=image_input,
|
| 137 |
+
outputs=[description_output, analysis_output, tips_output, complete_result_output, result_state]
|
| 138 |
)
|
| 139 |
+
|
| 140 |
download_button.click(
|
| 141 |
generate_download,
|
| 142 |
inputs=result_state,
|
| 143 |
outputs=gr.File(label="Seu Resultado")
|
| 144 |
)
|
| 145 |
|
| 146 |
+
# Conectar botão de atualização do token à função correspondente
|
| 147 |
+
update_button.click(
|
| 148 |
+
update_api_token,
|
| 149 |
+
inputs=api_token_input,
|
| 150 |
+
outputs=update_feedback
|
| 151 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
|
| 153 |
demo.launch()
|