Update app.py
Browse files
app.py
CHANGED
@@ -5,6 +5,7 @@ import io
|
|
5 |
import base64
|
6 |
from functools import lru_cache
|
7 |
import tempfile
|
|
|
8 |
|
9 |
# Variável global para armazenar o token da API (padrão vazio)
|
10 |
API_TOKEN = ""
|
@@ -21,27 +22,13 @@ def get_inference_client(model):
|
|
21 |
|
22 |
# Função para interpretar a imagem com cache utilizando InferenceClient (captioning)
|
23 |
@lru_cache(maxsize=128)
|
24 |
-
def interpret_image_cached(
|
25 |
-
# Converter imagem para base64 e criar data URI
|
26 |
-
base64_image = base64.b64encode(image_bytes).decode("utf-8")
|
27 |
-
data_uri = f"data:image/jpeg;base64,{base64_image}"
|
28 |
-
|
29 |
# Instanciar o client para o modelo de captioning
|
30 |
client = get_inference_client("Salesforce/blip2-opt-2.7b")
|
31 |
|
32 |
-
#
|
33 |
-
|
34 |
-
|
35 |
-
"content": [
|
36 |
-
{"type": "image_url", "image_url": {"url": data_uri}},
|
37 |
-
{"type": "text", "text": "Descreva esta imagem em uma frase."}
|
38 |
-
]
|
39 |
-
}]
|
40 |
-
|
41 |
-
# Chamada da API usando método de chat (a estrutura de retorno segue o padrão da API)
|
42 |
-
output = client.chat.completions.create(messages=messages)
|
43 |
-
# Supondo que o resultado esteja em output["choices"][0]["message"]["content"]
|
44 |
-
description = output["choices"][0]["message"]["content"].strip().capitalize()
|
45 |
if not description.endswith("."):
|
46 |
description += "."
|
47 |
return description
|
@@ -83,12 +70,13 @@ def health_tips_cached(description):
|
|
83 |
# Função principal para processar a imagem e gerar resultados
|
84 |
def process_image(image):
|
85 |
try:
|
86 |
-
# Converter imagem para bytes
|
87 |
buffered = io.BytesIO()
|
88 |
image.save(buffered, format="JPEG")
|
89 |
image_bytes = buffered.getvalue()
|
|
|
90 |
|
91 |
-
description = interpret_image_cached(
|
92 |
analysis = nutritional_analysis_cached(description)
|
93 |
tips = health_tips_cached(description)
|
94 |
complete_result = (
|
@@ -107,7 +95,8 @@ def generate_download(complete_result):
|
|
107 |
try:
|
108 |
with tempfile.NamedTemporaryFile(delete=False, suffix=".txt", mode="w", encoding="utf-8") as tmp:
|
109 |
tmp.write(complete_result)
|
110 |
-
|
|
|
111 |
except Exception:
|
112 |
return None
|
113 |
|
@@ -115,7 +104,7 @@ def generate_download(complete_result):
|
|
115 |
with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue", secondary_hue="cyan")) as demo:
|
116 |
with gr.Row():
|
117 |
gr.Markdown("""
|
118 |
-
#
|
119 |
### Revolucione a análise de suas refeições com IA de última geração!
|
120 |
- **[Descrição automática](pplx://action/followup)** de pratos a partir de imagens.
|
121 |
- **[Análise nutricional detalhada](pplx://action/followup)** com estimativas precisas de calorias e macronutrientes.
|
@@ -169,4 +158,4 @@ with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue", secondary_hue="cyan")) a
|
|
169 |
outputs=update_feedback
|
170 |
)
|
171 |
|
172 |
-
demo.launch()
|
|
|
5 |
import base64
|
6 |
from functools import lru_cache
|
7 |
import tempfile
|
8 |
+
import hashlib
|
9 |
|
10 |
# Variável global para armazenar o token da API (padrão vazio)
|
11 |
API_TOKEN = ""
|
|
|
22 |
|
23 |
# Função para interpretar a imagem com cache utilizando InferenceClient (captioning)
|
24 |
@lru_cache(maxsize=128)
|
25 |
+
def interpret_image_cached(image_hash):
|
|
|
|
|
|
|
|
|
26 |
# Instanciar o client para o modelo de captioning
|
27 |
client = get_inference_client("Salesforce/blip2-opt-2.7b")
|
28 |
|
29 |
+
# Chamada da API usando método post para gerar a descrição da imagem
|
30 |
+
response = client.post(data=image_hash, task="image-to-text")
|
31 |
+
description = response.get("generated_text", "").strip().capitalize()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
32 |
if not description.endswith("."):
|
33 |
description += "."
|
34 |
return description
|
|
|
70 |
# Função principal para processar a imagem e gerar resultados
|
71 |
def process_image(image):
|
72 |
try:
|
73 |
+
# Converter imagem para bytes e gerar um hash
|
74 |
buffered = io.BytesIO()
|
75 |
image.save(buffered, format="JPEG")
|
76 |
image_bytes = buffered.getvalue()
|
77 |
+
image_hash = hashlib.md5(image_bytes).hexdigest()
|
78 |
|
79 |
+
description = interpret_image_cached(image_hash)
|
80 |
analysis = nutritional_analysis_cached(description)
|
81 |
tips = health_tips_cached(description)
|
82 |
complete_result = (
|
|
|
95 |
try:
|
96 |
with tempfile.NamedTemporaryFile(delete=False, suffix=".txt", mode="w", encoding="utf-8") as tmp:
|
97 |
tmp.write(complete_result)
|
98 |
+
tmp_path = tmp.name
|
99 |
+
return tmp_path
|
100 |
except Exception:
|
101 |
return None
|
102 |
|
|
|
104 |
with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue", secondary_hue="cyan")) as demo:
|
105 |
with gr.Row():
|
106 |
gr.Markdown("""
|
107 |
+
# �️ Agente Nutricionista Inteligente Avançado
|
108 |
### Revolucione a análise de suas refeições com IA de última geração!
|
109 |
- **[Descrição automática](pplx://action/followup)** de pratos a partir de imagens.
|
110 |
- **[Análise nutricional detalhada](pplx://action/followup)** com estimativas precisas de calorias e macronutrientes.
|
|
|
158 |
outputs=update_feedback
|
159 |
)
|
160 |
|
161 |
+
demo.launch()
|