Update src/streamlit_app.py
Browse files- src/streamlit_app.py +30 -47
src/streamlit_app.py
CHANGED
|
@@ -20,9 +20,6 @@ client = None
|
|
| 20 |
if OPENAI_API_KEY:
|
| 21 |
client = OpenAI(api_key=OPENAI_API_KEY)
|
| 22 |
|
| 23 |
-
# Limite de confiança mínima para considerar a predição "segura"
|
| 24 |
-
CONFIDENCE_THRESHOLD = 0.70 # 70%
|
| 25 |
-
|
| 26 |
# ============================================================
|
| 27 |
# 1. Caminhos dos arquivos (sempre relativos ao próprio arquivo)
|
| 28 |
# ============================================================
|
|
@@ -32,6 +29,9 @@ LABELS_PATH = SRC_DIR / "labels.txt" # .../src/labels.txt
|
|
| 32 |
META_PATH = SRC_DIR / "meta.json" # .../src/meta.json
|
| 33 |
LOGO_PATH = SRC_DIR / "logo.png" # opcional: coloque um logo.png na pasta src
|
| 34 |
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
# ============================================================
|
| 37 |
# 2. Funções de carregamento (com cache do Streamlit)
|
|
@@ -72,13 +72,11 @@ def load_meta():
|
|
| 72 |
try:
|
| 73 |
with META_PATH.open("r", encoding="utf-8") as f:
|
| 74 |
data = json.load(f)
|
| 75 |
-
# tenta ler do meta.json no formato que usamos no Colab
|
| 76 |
shape = (
|
| 77 |
data.get("input_shape")
|
| 78 |
or data.get("expected_input_shape")
|
| 79 |
or {}
|
| 80 |
)
|
| 81 |
-
# exemplos: {"height": 224, "width": 224} ou {"1": 1, "2": 224, ...}
|
| 82 |
if isinstance(shape, dict):
|
| 83 |
h = shape.get("height") or shape.get("1") or 224
|
| 84 |
w = shape.get("width") or shape.get("2") or 224
|
|
@@ -98,8 +96,7 @@ def preprocess_image(pil_img: Image.Image, target_size):
|
|
| 98 |
h, w = target_size
|
| 99 |
img = pil_img.convert("RGB").resize((w, h))
|
| 100 |
img_arr = np.array(img).astype("float32") / 255.0
|
| 101 |
-
|
| 102 |
-
img_arr = np.expand_dims(img_arr, axis=0)
|
| 103 |
return img_arr
|
| 104 |
|
| 105 |
|
|
@@ -195,10 +192,8 @@ st.markdown("## 1) Envie uma imagem ou tire uma foto")
|
|
| 195 |
# ============================================================
|
| 196 |
# 4.1 Entrada da imagem: CÂMERA + UPLOAD
|
| 197 |
# ============================================================
|
| 198 |
-
# Primeiro tenta câmera
|
| 199 |
uploaded_file = st.camera_input("Tire uma foto do artefato (opcional)")
|
| 200 |
|
| 201 |
-
# Se não tiver foto da câmera, permite upload tradicional
|
| 202 |
if uploaded_file is None:
|
| 203 |
uploaded_file = st.file_uploader(
|
| 204 |
"Ou envie uma imagem (JPG ou PNG)",
|
|
@@ -214,41 +209,38 @@ if uploaded_file is not None:
|
|
| 214 |
|
| 215 |
st.markdown("## 2) Resultado da análise")
|
| 216 |
|
|
|
|
| 217 |
with st.spinner("Analisando a imagem com o modelo ArqueoIA..."):
|
| 218 |
probs = run_inference(pil_img)
|
| 219 |
|
| 220 |
-
# garante array 1D
|
| 221 |
probs = np.array(probs).flatten()
|
| 222 |
num_classes = len(probs)
|
| 223 |
idx_max = int(np.argmax(probs))
|
| 224 |
conf_max = float(probs[idx_max])
|
| 225 |
|
| 226 |
-
# Nome da classe mais provável (antes de checar o limiar)
|
| 227 |
if labels and len(labels) == num_classes:
|
| 228 |
-
|
| 229 |
else:
|
| 230 |
-
|
| 231 |
|
| 232 |
st.subheader("Resultado principal")
|
| 233 |
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
|
|
|
| 238 |
st.markdown(
|
| 239 |
-
"
|
| 240 |
-
"
|
| 241 |
-
|
| 242 |
-
|
| 243 |
)
|
| 244 |
-
pred_label = "desconhecido"
|
| 245 |
else:
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
f"**
|
| 249 |
-
f"**Confiança aproximada:** `{conf_max * 100:.1f}%`"
|
| 250 |
)
|
| 251 |
-
st.success("Análise concluída com sucesso! ✅")
|
| 252 |
|
| 253 |
st.markdown("### Detalhamento das classes")
|
| 254 |
for i in range(num_classes):
|
|
@@ -258,11 +250,12 @@ if uploaded_file is not None:
|
|
| 258 |
name = f"classe {i}"
|
| 259 |
st.write(f"- **{name}**: {probs[i] * 100:.1f}%")
|
| 260 |
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
|
|
|
| 266 |
|
| 267 |
# ====================================================
|
| 268 |
# 5. Consultar especialista online (Chat com OpenAI)
|
|
@@ -281,20 +274,11 @@ if uploaded_file is not None:
|
|
| 281 |
"contextos históricos ou curiosidades. A resposta é gerada por IA."
|
| 282 |
)
|
| 283 |
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
"aparecer em ossos, cerâmica, moedas e flechas em contextos "
|
| 290 |
-
"arqueológicos, em uma linguagem adequada para estudantes."
|
| 291 |
-
)
|
| 292 |
-
else:
|
| 293 |
-
pergunta_default = (
|
| 294 |
-
f"A imagem foi classificada como '{pred_label}' com confiança de "
|
| 295 |
-
f"{conf_max*100:.1f}%. Explique o que esse tipo de artefato costuma "
|
| 296 |
-
"representar em contextos arqueológicos."
|
| 297 |
-
)
|
| 298 |
|
| 299 |
pergunta = st.text_area(
|
| 300 |
"Digite sua pergunta para o especialista:",
|
|
@@ -347,4 +331,3 @@ st.markdown(
|
|
| 347 |
"</p>",
|
| 348 |
unsafe_allow_html=True,
|
| 349 |
)
|
| 350 |
-
|
|
|
|
| 20 |
if OPENAI_API_KEY:
|
| 21 |
client = OpenAI(api_key=OPENAI_API_KEY)
|
| 22 |
|
|
|
|
|
|
|
|
|
|
| 23 |
# ============================================================
|
| 24 |
# 1. Caminhos dos arquivos (sempre relativos ao próprio arquivo)
|
| 25 |
# ============================================================
|
|
|
|
| 29 |
META_PATH = SRC_DIR / "meta.json" # .../src/meta.json
|
| 30 |
LOGO_PATH = SRC_DIR / "logo.png" # opcional: coloque um logo.png na pasta src
|
| 31 |
|
| 32 |
+
# limiar de confiança para considerar a previsão "segura"
|
| 33 |
+
CONF_THRESHOLD = 0.40 # 40%
|
| 34 |
+
|
| 35 |
|
| 36 |
# ============================================================
|
| 37 |
# 2. Funções de carregamento (com cache do Streamlit)
|
|
|
|
| 72 |
try:
|
| 73 |
with META_PATH.open("r", encoding="utf-8") as f:
|
| 74 |
data = json.load(f)
|
|
|
|
| 75 |
shape = (
|
| 76 |
data.get("input_shape")
|
| 77 |
or data.get("expected_input_shape")
|
| 78 |
or {}
|
| 79 |
)
|
|
|
|
| 80 |
if isinstance(shape, dict):
|
| 81 |
h = shape.get("height") or shape.get("1") or 224
|
| 82 |
w = shape.get("width") or shape.get("2") or 224
|
|
|
|
| 96 |
h, w = target_size
|
| 97 |
img = pil_img.convert("RGB").resize((w, h))
|
| 98 |
img_arr = np.array(img).astype("float32") / 255.0
|
| 99 |
+
img_arr = np.expand_dims(img_arr, axis=0) # (1, H, W, 3)
|
|
|
|
| 100 |
return img_arr
|
| 101 |
|
| 102 |
|
|
|
|
| 192 |
# ============================================================
|
| 193 |
# 4.1 Entrada da imagem: CÂMERA + UPLOAD
|
| 194 |
# ============================================================
|
|
|
|
| 195 |
uploaded_file = st.camera_input("Tire uma foto do artefato (opcional)")
|
| 196 |
|
|
|
|
| 197 |
if uploaded_file is None:
|
| 198 |
uploaded_file = st.file_uploader(
|
| 199 |
"Ou envie uma imagem (JPG ou PNG)",
|
|
|
|
| 209 |
|
| 210 |
st.markdown("## 2) Resultado da análise")
|
| 211 |
|
| 212 |
+
# ------------------ INFERÊNCIA ------------------------
|
| 213 |
with st.spinner("Analisando a imagem com o modelo ArqueoIA..."):
|
| 214 |
probs = run_inference(pil_img)
|
| 215 |
|
|
|
|
| 216 |
probs = np.array(probs).flatten()
|
| 217 |
num_classes = len(probs)
|
| 218 |
idx_max = int(np.argmax(probs))
|
| 219 |
conf_max = float(probs[idx_max])
|
| 220 |
|
|
|
|
| 221 |
if labels and len(labels) == num_classes:
|
| 222 |
+
pred_label = labels[idx_max]
|
| 223 |
else:
|
| 224 |
+
pred_label = f"classe {idx_max}"
|
| 225 |
|
| 226 |
st.subheader("Resultado principal")
|
| 227 |
|
| 228 |
+
# Lógica de confiança
|
| 229 |
+
if conf_max < CONF_THRESHOLD:
|
| 230 |
+
st.warning(
|
| 231 |
+
"⚠️ O modelo ainda está **pouco confiante** na identificação desta imagem."
|
| 232 |
+
)
|
| 233 |
st.markdown(
|
| 234 |
+
f"A classe mais provável no momento é **{pred_label}**, "
|
| 235 |
+
f"com aproximadamente **{conf_max*100:.1f}%** de confiança. "
|
| 236 |
+
"Use esse resultado apenas como uma sugestão inicial e, se possível, "
|
| 237 |
+
"consulte um especialista humano."
|
| 238 |
)
|
|
|
|
| 239 |
else:
|
| 240 |
+
st.success(
|
| 241 |
+
f"A imagem foi classificada como **{pred_label}** "
|
| 242 |
+
f"com aproximadamente **{conf_max*100:.1f}%** de confiança."
|
|
|
|
| 243 |
)
|
|
|
|
| 244 |
|
| 245 |
st.markdown("### Detalhamento das classes")
|
| 246 |
for i in range(num_classes):
|
|
|
|
| 250 |
name = f"classe {i}"
|
| 251 |
st.write(f"- **{name}**: {probs[i] * 100:.1f}%")
|
| 252 |
|
| 253 |
+
st.info(
|
| 254 |
+
"Tente tirar outra foto com boa iluminação e foco, ou reposicionar o artefato "
|
| 255 |
+
"para facilitar a identificação."
|
| 256 |
+
)
|
| 257 |
+
|
| 258 |
+
st.success("Análise concluída com sucesso! ✅")
|
| 259 |
|
| 260 |
# ====================================================
|
| 261 |
# 5. Consultar especialista online (Chat com OpenAI)
|
|
|
|
| 274 |
"contextos históricos ou curiosidades. A resposta é gerada por IA."
|
| 275 |
)
|
| 276 |
|
| 277 |
+
pergunta_default = (
|
| 278 |
+
f"A imagem foi classificada como '{pred_label}' com confiança de "
|
| 279 |
+
f"{conf_max*100:.1f}%. Explique o que esse tipo de artefato costuma "
|
| 280 |
+
"representar em contextos arqueológicos."
|
| 281 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 282 |
|
| 283 |
pergunta = st.text_area(
|
| 284 |
"Digite sua pergunta para o especialista:",
|
|
|
|
| 331 |
"</p>",
|
| 332 |
unsafe_allow_html=True,
|
| 333 |
)
|
|
|