Update src/streamlit_app.py
Browse files- src/streamlit_app.py +127 -172
src/streamlit_app.py
CHANGED
|
@@ -1,37 +1,37 @@
|
|
| 1 |
# src/streamlit_app.py
|
| 2 |
|
| 3 |
-
import json
|
| 4 |
import os
|
|
|
|
| 5 |
from pathlib import Path
|
| 6 |
|
| 7 |
-
from openai import OpenAI
|
| 8 |
-
|
| 9 |
import numpy as np
|
| 10 |
from PIL import Image
|
| 11 |
import streamlit as st
|
| 12 |
import tensorflow as tf
|
| 13 |
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
#
|
| 18 |
-
|
|
|
|
|
|
|
| 19 |
client = OpenAI(api_key=OPENAI_API_KEY) if OPENAI_API_KEY else None
|
| 20 |
|
| 21 |
|
| 22 |
-
# ============================================================
|
| 23 |
-
# 1. Caminhos dos arquivos (
|
| 24 |
-
# ============================================================
|
| 25 |
SRC_DIR = Path(__file__).parent # .../src
|
| 26 |
MODEL_PATH = SRC_DIR / "model.tflite" # .../src/model.tflite
|
| 27 |
LABELS_PATH = SRC_DIR / "labels.txt" # .../src/labels.txt
|
| 28 |
META_PATH = SRC_DIR / "meta.json" # .../src/meta.json
|
| 29 |
-
LOGO_PATH = SRC_DIR / "logo.png" #
|
| 30 |
|
| 31 |
|
| 32 |
-
# ============================================================
|
| 33 |
# 2. Funções de carregamento (com cache do Streamlit)
|
| 34 |
-
# ============================================================
|
| 35 |
@st.cache_resource
|
| 36 |
def load_interpreter():
|
| 37 |
"""Carrega o modelo TFLite e retorna o interpretador + detalhes."""
|
|
@@ -59,7 +59,10 @@ def load_labels():
|
|
| 59 |
|
| 60 |
@st.cache_data
|
| 61 |
def load_meta():
|
| 62 |
-
"""
|
|
|
|
|
|
|
|
|
|
| 63 |
meta = {
|
| 64 |
"input_height": 224,
|
| 65 |
"input_width": 224,
|
|
@@ -76,14 +79,14 @@ def load_meta():
|
|
| 76 |
meta["input_height"] = int(h)
|
| 77 |
meta["input_width"] = int(w)
|
| 78 |
except Exception:
|
| 79 |
-
#
|
| 80 |
pass
|
| 81 |
return meta
|
| 82 |
|
| 83 |
|
| 84 |
-
# ============================================================
|
| 85 |
# 3. Pré-processamento e inferência
|
| 86 |
-
# ============================================================
|
| 87 |
def preprocess_image(pil_img: Image.Image, target_size):
|
| 88 |
"""Redimensiona e normaliza a imagem para o modelo."""
|
| 89 |
h, w = target_size
|
|
@@ -115,7 +118,7 @@ def run_inference(pil_img: Image.Image):
|
|
| 115 |
output_index = output_details[0]["index"]
|
| 116 |
output_data = interpreter.get_tensor(output_index)[0] # (num_classes,)
|
| 117 |
|
| 118 |
-
#
|
| 119 |
if output_data.ndim == 1:
|
| 120 |
exp = np.exp(output_data - np.max(output_data))
|
| 121 |
probs = exp / np.sum(exp)
|
|
@@ -125,123 +128,53 @@ def run_inference(pil_img: Image.Image):
|
|
| 125 |
return probs
|
| 126 |
|
| 127 |
|
| 128 |
-
# ============================================================
|
| 129 |
-
# 4.
|
| 130 |
-
# ============================================================
|
| 131 |
-
def consultar_especialista(pred_label, probs_dict, user_question):
|
| 132 |
-
"""
|
| 133 |
-
Usa o modelo de linguagem para explicar o resultado
|
| 134 |
-
e responder a pergunta do usuário.
|
| 135 |
-
"""
|
| 136 |
-
if client is None or not OPENAI_API_KEY:
|
| 137 |
-
return (
|
| 138 |
-
"A consulta online está desativada neste Space. "
|
| 139 |
-
"Verifique se o secret OPENAI_API_KEY foi configurado corretamente."
|
| 140 |
-
)
|
| 141 |
-
|
| 142 |
-
# Monte um contexto simples com o resultado do modelo
|
| 143 |
-
resumo_prob = "\n".join(
|
| 144 |
-
f"- {nome}: {p * 100:.1f}%"
|
| 145 |
-
for nome, p in probs_dict.items()
|
| 146 |
-
)
|
| 147 |
-
|
| 148 |
-
system_prompt = (
|
| 149 |
-
"Você é um arqueólogo experiente ajudando professores e estudantes. "
|
| 150 |
-
"Explique de forma simples, com foco educativo, sem inventar informações."
|
| 151 |
-
)
|
| 152 |
-
|
| 153 |
-
user_prompt = f"""
|
| 154 |
-
Resultado de um classificador de imagens arqueológicas:
|
| 155 |
-
|
| 156 |
-
Classe prevista principal: {pred_label}
|
| 157 |
-
Confiâncias aproximadas:
|
| 158 |
-
{resumo_prob}
|
| 159 |
-
|
| 160 |
-
Pergunta do usuário:
|
| 161 |
-
{user_question}
|
| 162 |
-
"""
|
| 163 |
-
|
| 164 |
-
try:
|
| 165 |
-
response = client.responses.create(
|
| 166 |
-
model="gpt-4.1-mini",
|
| 167 |
-
input=[
|
| 168 |
-
{"role": "system", "content": system_prompt},
|
| 169 |
-
{"role": "user", "content": user_prompt},
|
| 170 |
-
],
|
| 171 |
-
)
|
| 172 |
-
# Resposta de texto
|
| 173 |
-
answer = response.output[0].content[0].text
|
| 174 |
-
return answer
|
| 175 |
-
except Exception as e:
|
| 176 |
-
return f"Ocorreu um erro ao consultar o especialista online: {e}"
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
# =====================================================================
|
| 180 |
-
# 5. Interface Streamlit (layout e visual)
|
| 181 |
-
# =====================================================================
|
| 182 |
st.set_page_config(
|
| 183 |
page_title="ArqueoIA",
|
| 184 |
page_icon="🗿",
|
| 185 |
layout="centered",
|
| 186 |
)
|
| 187 |
|
| 188 |
-
# CSS para
|
| 189 |
st.markdown(
|
| 190 |
"""
|
| 191 |
<style>
|
| 192 |
-
|
| 193 |
-
.stApp {
|
| 194 |
-
background: radial-gradient(circle at top left, #f5f5ff 0, #ffffff 55%);
|
| 195 |
-
}
|
| 196 |
-
/* Título centralizado */
|
| 197 |
-
.arqueo-title {
|
| 198 |
text-align: center;
|
| 199 |
-
font-size:
|
| 200 |
font-weight: 800;
|
| 201 |
margin-bottom: 0.2rem;
|
| 202 |
}
|
| 203 |
-
.
|
| 204 |
text-align: center;
|
| 205 |
-
font-size: 1.
|
| 206 |
color: #555;
|
| 207 |
-
max-width: 780px;
|
| 208 |
-
margin: 0 auto 1.5rem auto;
|
| 209 |
-
}
|
| 210 |
-
/* Card branco */
|
| 211 |
-
.card {
|
| 212 |
-
background-color: #ffffff;
|
| 213 |
-
border-radius: 18px;
|
| 214 |
-
padding: 1.5rem 1.8rem;
|
| 215 |
-
box-shadow: 0 8px 24px rgba(15, 23, 42, 0.08);
|
| 216 |
margin-bottom: 1.5rem;
|
| 217 |
}
|
| 218 |
-
.
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
}
|
| 223 |
</style>
|
| 224 |
""",
|
| 225 |
unsafe_allow_html=True,
|
| 226 |
)
|
| 227 |
|
| 228 |
-
# ----
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
with
|
| 232 |
-
|
| 233 |
-
st.image(str(LOGO_PATH), use_container_width=True)
|
| 234 |
-
|
| 235 |
-
with title_col:
|
| 236 |
-
st.markdown('<div class="arqueo-title">ArqueoIA 🗿</div>', unsafe_allow_html=True)
|
| 237 |
|
|
|
|
|
|
|
| 238 |
st.markdown(
|
| 239 |
-
""
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
(osso, cerâmica, moeda, flecha).
|
| 243 |
-
</div>
|
| 244 |
-
""",
|
| 245 |
unsafe_allow_html=True,
|
| 246 |
)
|
| 247 |
|
|
@@ -256,18 +189,15 @@ else:
|
|
| 256 |
"Os nomes das classes serão mostrados como índices (0, 1, 2, ...)."
|
| 257 |
)
|
| 258 |
|
| 259 |
-
# ------------------------ Upload de imagem ------------------------
|
| 260 |
-
st.markdown('<div class="card">', unsafe_allow_html=True)
|
| 261 |
-
|
| 262 |
-
st.markdown('<div class="section-title">1) Envie uma imagem (JPG ou PNG)</div>',
|
| 263 |
-
unsafe_allow_html=True)
|
| 264 |
-
|
| 265 |
uploaded_file = st.file_uploader(
|
| 266 |
-
"
|
| 267 |
type=["jpg", "jpeg", "png"],
|
| 268 |
-
label_visibility="collapsed",
|
| 269 |
)
|
| 270 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 271 |
if uploaded_file is not None:
|
| 272 |
try:
|
| 273 |
pil_img = Image.open(uploaded_file)
|
|
@@ -275,9 +205,10 @@ if uploaded_file is not None:
|
|
| 275 |
st.image(pil_img, caption="Imagem enviada", use_container_width=True)
|
| 276 |
st.write("")
|
| 277 |
|
| 278 |
-
with st.spinner("
|
| 279 |
probs = run_inference(pil_img)
|
| 280 |
|
|
|
|
| 281 |
probs = np.array(probs).flatten()
|
| 282 |
num_classes = len(probs)
|
| 283 |
idx_max = int(np.argmax(probs))
|
|
@@ -288,74 +219,98 @@ if uploaded_file is not None:
|
|
| 288 |
else:
|
| 289 |
pred_label = f"classe {idx_max}"
|
| 290 |
|
| 291 |
-
|
| 292 |
-
class_probs = {}
|
| 293 |
-
for i in range(num_classes):
|
| 294 |
-
if labels and i < len(labels):
|
| 295 |
-
name = labels[i]
|
| 296 |
-
else:
|
| 297 |
-
name = f"classe {i}"
|
| 298 |
-
class_probs[name] = float(probs[i])
|
| 299 |
-
|
| 300 |
-
# ---------------- Resultado principal ----------------
|
| 301 |
-
st.markdown('</div>', unsafe_allow_html=True) # fecha card de upload
|
| 302 |
-
st.markdown('<div class="card">', unsafe_allow_html=True)
|
| 303 |
-
|
| 304 |
-
st.markdown('<div class="section-title">3) Resultado principal</div>',
|
| 305 |
-
unsafe_allow_html=True)
|
| 306 |
-
|
| 307 |
st.markdown(
|
| 308 |
f"**Classe prevista:** `{pred_label}` \n"
|
| 309 |
-
f"**Confiança aproximada:** `{conf_max * 100:.1f}%`"
|
| 310 |
)
|
| 311 |
|
| 312 |
st.markdown("### Detalhamento das classes")
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
|
|
|
| 318 |
|
| 319 |
st.success("Análise concluída com sucesso! ✅")
|
| 320 |
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
#
|
| 324 |
-
st.markdown(
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
"⚠️ A consulta online está desativada: "
|
| 333 |
-
"secret `OPENAI_API_KEY` não encontrado neste Space."
|
| 334 |
-
)
|
| 335 |
-
else:
|
| 336 |
-
default_question = (
|
| 337 |
-
f"Explique, em linguagem simples, como identificar um artefato do tipo "
|
| 338 |
-
f"'{pred_label}' e quais cuidados tomar ao manuseá-lo em campo."
|
| 339 |
)
|
| 340 |
|
| 341 |
user_question = st.text_area(
|
| 342 |
-
"
|
| 343 |
-
|
| 344 |
-
height=120,
|
| 345 |
)
|
| 346 |
|
| 347 |
-
if st.button("
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 353 |
|
| 354 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 355 |
|
| 356 |
except Exception as e:
|
| 357 |
-
st.markdown('</div>', unsafe_allow_html=True) # garante fechamento do card
|
| 358 |
st.error(f"Ocorreu um erro ao processar a imagem: {e}")
|
|
|
|
| 359 |
else:
|
| 360 |
-
st.markdown('</div>', unsafe_allow_html=True) # fecha card de upload
|
| 361 |
st.info("Envie uma imagem para iniciar a análise.")
|
|
|
|
| 1 |
# src/streamlit_app.py
|
| 2 |
|
|
|
|
| 3 |
import os
|
| 4 |
+
import json
|
| 5 |
from pathlib import Path
|
| 6 |
|
|
|
|
|
|
|
| 7 |
import numpy as np
|
| 8 |
from PIL import Image
|
| 9 |
import streamlit as st
|
| 10 |
import tensorflow as tf
|
| 11 |
|
| 12 |
+
from openai import OpenAI
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
# ============================================================
|
| 16 |
+
# 0. OpenAI – lê chave dos Secrets do Hugging Face
|
| 17 |
+
# ============================================================
|
| 18 |
+
OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")
|
| 19 |
client = OpenAI(api_key=OPENAI_API_KEY) if OPENAI_API_KEY else None
|
| 20 |
|
| 21 |
|
| 22 |
+
# ============================================================
|
| 23 |
+
# 1. Caminhos dos arquivos (relativos ao próprio arquivo)
|
| 24 |
+
# ============================================================
|
| 25 |
SRC_DIR = Path(__file__).parent # .../src
|
| 26 |
MODEL_PATH = SRC_DIR / "model.tflite" # .../src/model.tflite
|
| 27 |
LABELS_PATH = SRC_DIR / "labels.txt" # .../src/labels.txt
|
| 28 |
META_PATH = SRC_DIR / "meta.json" # .../src/meta.json
|
| 29 |
+
LOGO_PATH = SRC_DIR / "logo.png" # opcional: logo da equipe
|
| 30 |
|
| 31 |
|
| 32 |
+
# ============================================================
|
| 33 |
# 2. Funções de carregamento (com cache do Streamlit)
|
| 34 |
+
# ============================================================
|
| 35 |
@st.cache_resource
|
| 36 |
def load_interpreter():
|
| 37 |
"""Carrega o modelo TFLite e retorna o interpretador + detalhes."""
|
|
|
|
| 59 |
|
| 60 |
@st.cache_data
|
| 61 |
def load_meta():
|
| 62 |
+
"""
|
| 63 |
+
Lê meta.json, se existir. Caso contrário, usa padrão 224x224.
|
| 64 |
+
No Colab salvamos algo como {"input_shape": {"height": 224, "width": 224}}
|
| 65 |
+
"""
|
| 66 |
meta = {
|
| 67 |
"input_height": 224,
|
| 68 |
"input_width": 224,
|
|
|
|
| 79 |
meta["input_height"] = int(h)
|
| 80 |
meta["input_width"] = int(w)
|
| 81 |
except Exception:
|
| 82 |
+
# Se der qualquer erro, segue com o padrão 224x224
|
| 83 |
pass
|
| 84 |
return meta
|
| 85 |
|
| 86 |
|
| 87 |
+
# ============================================================
|
| 88 |
# 3. Pré-processamento e inferência
|
| 89 |
+
# ============================================================
|
| 90 |
def preprocess_image(pil_img: Image.Image, target_size):
|
| 91 |
"""Redimensiona e normaliza a imagem para o modelo."""
|
| 92 |
h, w = target_size
|
|
|
|
| 118 |
output_index = output_details[0]["index"]
|
| 119 |
output_data = interpreter.get_tensor(output_index)[0] # (num_classes,)
|
| 120 |
|
| 121 |
+
# Normaliza se não for softmax
|
| 122 |
if output_data.ndim == 1:
|
| 123 |
exp = np.exp(output_data - np.max(output_data))
|
| 124 |
probs = exp / np.sum(exp)
|
|
|
|
| 128 |
return probs
|
| 129 |
|
| 130 |
|
| 131 |
+
# ============================================================
|
| 132 |
+
# 4. Layout / Interface Streamlit
|
| 133 |
+
# ============================================================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
st.set_page_config(
|
| 135 |
page_title="ArqueoIA",
|
| 136 |
page_icon="🗿",
|
| 137 |
layout="centered",
|
| 138 |
)
|
| 139 |
|
| 140 |
+
# ---- CSS simples para centralizar título e deixar mais bonito
|
| 141 |
st.markdown(
|
| 142 |
"""
|
| 143 |
<style>
|
| 144 |
+
.main-title {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
text-align: center;
|
| 146 |
+
font-size: 3rem;
|
| 147 |
font-weight: 800;
|
| 148 |
margin-bottom: 0.2rem;
|
| 149 |
}
|
| 150 |
+
.subtitle {
|
| 151 |
text-align: center;
|
| 152 |
+
font-size: 1.05rem;
|
| 153 |
color: #555;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 154 |
margin-bottom: 1.5rem;
|
| 155 |
}
|
| 156 |
+
.stButton>button {
|
| 157 |
+
border-radius: 999px;
|
| 158 |
+
padding: 0.4rem 1.4rem;
|
| 159 |
+
font-weight: 600;
|
| 160 |
}
|
| 161 |
</style>
|
| 162 |
""",
|
| 163 |
unsafe_allow_html=True,
|
| 164 |
)
|
| 165 |
|
| 166 |
+
# ---- Logo da equipe (opcional)
|
| 167 |
+
if LOGO_PATH.exists():
|
| 168 |
+
col_logo_1, col_logo_2, col_logo_3 = st.columns([1, 2, 1])
|
| 169 |
+
with col_logo_2:
|
| 170 |
+
st.image(str(LOGO_PATH), width=140)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 171 |
|
| 172 |
+
# ---- Título + subtítulo centralizados
|
| 173 |
+
st.markdown('<h1 class="main-title">ArqueoIA 🗿</h1>', unsafe_allow_html=True)
|
| 174 |
st.markdown(
|
| 175 |
+
'<p class="subtitle">Sistema de IA para '
|
| 176 |
+
'identificar e classificar artefatos arqueológicos '
|
| 177 |
+
'(osso, cerâmica, moeda, flecha).</p>',
|
|
|
|
|
|
|
|
|
|
| 178 |
unsafe_allow_html=True,
|
| 179 |
)
|
| 180 |
|
|
|
|
| 189 |
"Os nomes das classes serão mostrados como índices (0, 1, 2, ...)."
|
| 190 |
)
|
| 191 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 192 |
uploaded_file = st.file_uploader(
|
| 193 |
+
"Envie uma imagem (JPG ou PNG)",
|
| 194 |
type=["jpg", "jpeg", "png"],
|
|
|
|
| 195 |
)
|
| 196 |
|
| 197 |
+
# Variáveis para contexto do chat
|
| 198 |
+
pred_label = None
|
| 199 |
+
probs = None
|
| 200 |
+
|
| 201 |
if uploaded_file is not None:
|
| 202 |
try:
|
| 203 |
pil_img = Image.open(uploaded_file)
|
|
|
|
| 205 |
st.image(pil_img, caption="Imagem enviada", use_container_width=True)
|
| 206 |
st.write("")
|
| 207 |
|
| 208 |
+
with st.spinner("Analisando a imagem com o modelo ArqueoIA..."):
|
| 209 |
probs = run_inference(pil_img)
|
| 210 |
|
| 211 |
+
# garante array 1D
|
| 212 |
probs = np.array(probs).flatten()
|
| 213 |
num_classes = len(probs)
|
| 214 |
idx_max = int(np.argmax(probs))
|
|
|
|
| 219 |
else:
|
| 220 |
pred_label = f"classe {idx_max}"
|
| 221 |
|
| 222 |
+
st.subheader("Resultado principal")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 223 |
st.markdown(
|
| 224 |
f"**Classe prevista:** `{pred_label}` \n"
|
| 225 |
+
f"**Confiança aproximada:** `{conf_max * 100:.1f}%`"
|
| 226 |
)
|
| 227 |
|
| 228 |
st.markdown("### Detalhamento das classes")
|
| 229 |
+
for i in range(num_classes):
|
| 230 |
+
if labels and i < len(labels):
|
| 231 |
+
name = labels[i]
|
| 232 |
+
else:
|
| 233 |
+
name = f"classe {i}"
|
| 234 |
+
st.write(f"- **{name}**: {probs[i] * 100:.1f}%")
|
| 235 |
|
| 236 |
st.success("Análise concluída com sucesso! ✅")
|
| 237 |
|
| 238 |
+
# ========================================================
|
| 239 |
+
# 5. Consultar especialista online (OpenAI)
|
| 240 |
+
# ========================================================
|
| 241 |
+
st.markdown("---")
|
| 242 |
+
st.markdown("### 4) Consultar especialista online")
|
| 243 |
+
|
| 244 |
+
if OPENAI_API_KEY and client is not None:
|
| 245 |
+
st.write(
|
| 246 |
+
"Envie uma pergunta sobre o resultado, sobre arqueologia "
|
| 247 |
+
"ou sobre o funcionamento do ArqueoIA. "
|
| 248 |
+
"Um especialista virtual responderá com base no contexto."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 249 |
)
|
| 250 |
|
| 251 |
user_question = st.text_area(
|
| 252 |
+
"Pergunta para o especialista",
|
| 253 |
+
placeholder="Ex.: Essa classificação faz sentido? Como esse tipo de artefato era utilizado?",
|
|
|
|
| 254 |
)
|
| 255 |
|
| 256 |
+
if st.button("Enviar pergunta ao especialista"):
|
| 257 |
+
if not user_question.strip():
|
| 258 |
+
st.warning("Por favor, escreva uma pergunta antes de enviar.")
|
| 259 |
+
else:
|
| 260 |
+
with st.spinner("Consultando especialista online..."):
|
| 261 |
+
# Contexto que será enviado ao modelo da OpenAI
|
| 262 |
+
context_parts = []
|
| 263 |
+
|
| 264 |
+
if pred_label is not None:
|
| 265 |
+
context_parts.append(
|
| 266 |
+
f"Classe prevista pelo modelo ArqueoIA: {pred_label}"
|
| 267 |
+
)
|
| 268 |
+
|
| 269 |
+
if probs is not None and labels and len(labels) == len(probs):
|
| 270 |
+
ranking = [
|
| 271 |
+
f"{labels[i]}: {probs[i]*100:.1f}%"
|
| 272 |
+
for i in range(len(probs))
|
| 273 |
+
]
|
| 274 |
+
context_parts.append(
|
| 275 |
+
"Distribuição das classes: " + ", ".join(ranking)
|
| 276 |
+
)
|
| 277 |
+
|
| 278 |
+
context_text = "\n".join(context_parts) if context_parts else "Sem contexto adicional."
|
| 279 |
+
|
| 280 |
+
prompt = (
|
| 281 |
+
"Você é um especialista em arqueologia que está ajudando uma equipe de estudantes "
|
| 282 |
+
"da FIRST LEGO League. Use uma linguagem simples e educativa.\n\n"
|
| 283 |
+
f"Contexto do modelo ArqueoIA:\n{context_text}\n\n"
|
| 284 |
+
f"Pergunta do usuário:\n{user_question}"
|
| 285 |
+
)
|
| 286 |
+
|
| 287 |
+
try:
|
| 288 |
+
response = client.responses.create(
|
| 289 |
+
model="gpt-4.1-mini",
|
| 290 |
+
input=prompt,
|
| 291 |
+
)
|
| 292 |
+
# Tentativa de extrair o texto da nova API de Responses
|
| 293 |
+
try:
|
| 294 |
+
answer = response.output[0].content[0].text
|
| 295 |
+
except Exception:
|
| 296 |
+
answer = str(response)
|
| 297 |
+
except Exception as e:
|
| 298 |
+
answer = (
|
| 299 |
+
"Não foi possível consultar o especialista online neste momento. "
|
| 300 |
+
f"Detalhes técnicos: {e}"
|
| 301 |
+
)
|
| 302 |
+
|
| 303 |
+
st.markdown("**Resposta do especialista:**")
|
| 304 |
+
st.write(answer)
|
| 305 |
|
| 306 |
+
else:
|
| 307 |
+
st.info(
|
| 308 |
+
"A função de consulta ao especialista online está desativada, "
|
| 309 |
+
"porque a chave de API da OpenAI não está configurada no servidor."
|
| 310 |
+
)
|
| 311 |
|
| 312 |
except Exception as e:
|
|
|
|
| 313 |
st.error(f"Ocorreu um erro ao processar a imagem: {e}")
|
| 314 |
+
|
| 315 |
else:
|
|
|
|
| 316 |
st.info("Envie uma imagem para iniciar a análise.")
|