Update src/streamlit_app.py
Browse files- src/streamlit_app.py +109 -107
src/streamlit_app.py
CHANGED
|
@@ -1,8 +1,8 @@
|
|
| 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
|
|
@@ -11,22 +11,23 @@ import tensorflow as tf
|
|
| 11 |
|
| 12 |
from openai import OpenAI
|
| 13 |
|
| 14 |
-
|
| 15 |
# ============================================================
|
| 16 |
-
# 0.
|
| 17 |
# ============================================================
|
|
|
|
| 18 |
OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")
|
| 19 |
-
client =
|
| 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
|
| 30 |
|
| 31 |
|
| 32 |
# ============================================================
|
|
@@ -59,10 +60,7 @@ def load_labels():
|
|
| 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,
|
|
@@ -71,15 +69,20 @@ def load_meta():
|
|
| 71 |
try:
|
| 72 |
with META_PATH.open("r", encoding="utf-8") as f:
|
| 73 |
data = json.load(f)
|
| 74 |
-
|
| 75 |
-
shape =
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
if isinstance(shape, dict):
|
| 77 |
h = shape.get("height") or shape.get("1") or 224
|
| 78 |
w = shape.get("width") or shape.get("2") or 224
|
| 79 |
meta["input_height"] = int(h)
|
| 80 |
meta["input_width"] = int(w)
|
| 81 |
except Exception:
|
| 82 |
-
#
|
| 83 |
pass
|
| 84 |
return meta
|
| 85 |
|
|
@@ -118,7 +121,7 @@ def run_inference(pil_img: Image.Image):
|
|
| 118 |
output_index = output_details[0]["index"]
|
| 119 |
output_data = interpreter.get_tensor(output_index)[0] # (num_classes,)
|
| 120 |
|
| 121 |
-
#
|
| 122 |
if output_data.ndim == 1:
|
| 123 |
exp = np.exp(output_data - np.max(output_data))
|
| 124 |
probs = exp / np.sum(exp)
|
|
@@ -137,44 +140,39 @@ st.set_page_config(
|
|
| 137 |
layout="centered",
|
| 138 |
)
|
| 139 |
|
| 140 |
-
#
|
| 141 |
st.markdown(
|
| 142 |
"""
|
| 143 |
<style>
|
| 144 |
-
.main
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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.
|
| 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 |
-
#
|
| 167 |
if LOGO_PATH.exists():
|
| 168 |
-
|
| 169 |
-
with col_logo_2:
|
| 170 |
-
st.image(str(LOGO_PATH), width=140)
|
| 171 |
|
| 172 |
-
|
| 173 |
-
st.markdown('<h1 class="main-title">ArqueoIA 🗿</h1>', unsafe_allow_html=True)
|
| 174 |
st.markdown(
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
|
|
|
|
|
|
|
|
|
| 178 |
unsafe_allow_html=True,
|
| 179 |
)
|
| 180 |
|
|
@@ -189,14 +187,20 @@ else:
|
|
| 189 |
"Os nomes das classes serão mostrados como índices (0, 1, 2, ...)."
|
| 190 |
)
|
| 191 |
|
| 192 |
-
|
| 193 |
-
"Envie uma imagem (JPG ou PNG)",
|
| 194 |
-
type=["jpg", "jpeg", "png"],
|
| 195 |
-
)
|
| 196 |
|
| 197 |
-
#
|
| 198 |
-
|
| 199 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 200 |
|
| 201 |
if uploaded_file is not None:
|
| 202 |
try:
|
|
@@ -205,6 +209,8 @@ if uploaded_file is not None:
|
|
| 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 |
|
|
@@ -235,82 +241,78 @@ if uploaded_file is not None:
|
|
| 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("##
|
| 243 |
|
| 244 |
-
if
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 245 |
st.write(
|
| 246 |
-
"
|
| 247 |
-
"ou
|
| 248 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 249 |
)
|
| 250 |
|
| 251 |
-
|
| 252 |
-
"
|
| 253 |
-
|
|
|
|
| 254 |
)
|
| 255 |
|
| 256 |
if st.button("Enviar pergunta ao especialista"):
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 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 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 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 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 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("
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
# src/streamlit_app.py
|
| 2 |
|
|
|
|
| 3 |
import json
|
| 4 |
from pathlib import Path
|
| 5 |
+
import os
|
| 6 |
|
| 7 |
import numpy as np
|
| 8 |
from PIL import Image
|
|
|
|
| 11 |
|
| 12 |
from openai import OpenAI
|
| 13 |
|
|
|
|
| 14 |
# ============================================================
|
| 15 |
+
# 0. Configuração da API da OpenAI (Chat especialista)
|
| 16 |
# ============================================================
|
| 17 |
+
# A chave deve estar configurada nos "Repository secrets" como OPENAI_API_KEY
|
| 18 |
OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")
|
| 19 |
+
client = None
|
| 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 |
# ============================================================
|
| 26 |
SRC_DIR = Path(__file__).parent # .../src
|
| 27 |
MODEL_PATH = SRC_DIR / "model.tflite" # .../src/model.tflite
|
| 28 |
LABELS_PATH = SRC_DIR / "labels.txt" # .../src/labels.txt
|
| 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 |
|
| 33 |
# ============================================================
|
|
|
|
| 60 |
|
| 61 |
@st.cache_data
|
| 62 |
def load_meta():
|
| 63 |
+
"""Lê meta.json, se existir. Caso contrário, usa padrão 224x224."""
|
|
|
|
|
|
|
|
|
|
| 64 |
meta = {
|
| 65 |
"input_height": 224,
|
| 66 |
"input_width": 224,
|
|
|
|
| 69 |
try:
|
| 70 |
with META_PATH.open("r", encoding="utf-8") as f:
|
| 71 |
data = json.load(f)
|
| 72 |
+
# tenta ler do meta.json no formato que usamos no Colab
|
| 73 |
+
shape = (
|
| 74 |
+
data.get("input_shape")
|
| 75 |
+
or data.get("expected_input_shape")
|
| 76 |
+
or {}
|
| 77 |
+
)
|
| 78 |
+
# exemplos: {"height": 224, "width": 224} ou {"1": 1, "2": 224, ...}
|
| 79 |
if isinstance(shape, dict):
|
| 80 |
h = shape.get("height") or shape.get("1") or 224
|
| 81 |
w = shape.get("width") or shape.get("2") or 224
|
| 82 |
meta["input_height"] = int(h)
|
| 83 |
meta["input_width"] = int(w)
|
| 84 |
except Exception:
|
| 85 |
+
# se der qualquer erro, segue com o padrão 224x224
|
| 86 |
pass
|
| 87 |
return meta
|
| 88 |
|
|
|
|
| 121 |
output_index = output_details[0]["index"]
|
| 122 |
output_data = interpreter.get_tensor(output_index)[0] # (num_classes,)
|
| 123 |
|
| 124 |
+
# normaliza se não for softmax
|
| 125 |
if output_data.ndim == 1:
|
| 126 |
exp = np.exp(output_data - np.max(output_data))
|
| 127 |
probs = exp / np.sum(exp)
|
|
|
|
| 140 |
layout="centered",
|
| 141 |
)
|
| 142 |
|
| 143 |
+
# Estilo básico para centralizar e limitar largura
|
| 144 |
st.markdown(
|
| 145 |
"""
|
| 146 |
<style>
|
| 147 |
+
.main {
|
| 148 |
+
max-width: 900px;
|
| 149 |
+
margin: 0 auto;
|
| 150 |
+
}
|
| 151 |
+
h1, h2, h3, h4 {
|
| 152 |
text-align: center;
|
|
|
|
|
|
|
|
|
|
| 153 |
}
|
| 154 |
.subtitle {
|
| 155 |
text-align: center;
|
| 156 |
+
font-size: 1.0rem;
|
| 157 |
color: #555;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
}
|
| 159 |
</style>
|
| 160 |
""",
|
| 161 |
unsafe_allow_html=True,
|
| 162 |
)
|
| 163 |
|
| 164 |
+
# Logo opcional (coloque um arquivo logo.png dentro de src)
|
| 165 |
if LOGO_PATH.exists():
|
| 166 |
+
st.image(str(LOGO_PATH), width=140, caption="Equipe ArqueoIA", use_container_width=False)
|
|
|
|
|
|
|
| 167 |
|
| 168 |
+
st.markdown("<h1>ArqueoIA 🗿</h1>", unsafe_allow_html=True)
|
|
|
|
| 169 |
st.markdown(
|
| 170 |
+
"""
|
| 171 |
+
<p class="subtitle">
|
| 172 |
+
Sistema educacional de IA para identificar e classificar artefatos arqueológicos
|
| 173 |
+
(osso, cerâmica, moeda, flecha).
|
| 174 |
+
</p>
|
| 175 |
+
""",
|
| 176 |
unsafe_allow_html=True,
|
| 177 |
)
|
| 178 |
|
|
|
|
| 187 |
"Os nomes das classes serão mostrados como índices (0, 1, 2, ...)."
|
| 188 |
)
|
| 189 |
|
| 190 |
+
st.markdown("## 1) Envie uma imagem ou tire uma foto")
|
|
|
|
|
|
|
|
|
|
| 191 |
|
| 192 |
+
# ============================================================
|
| 193 |
+
# 4.1 Entrada da imagem: CÂMERA + UPLOAD
|
| 194 |
+
# ============================================================
|
| 195 |
+
# Primeiro tenta câmera
|
| 196 |
+
uploaded_file = st.camera_input("Tire uma foto do artefato (opcional)")
|
| 197 |
+
|
| 198 |
+
# Se não tiver foto da câmera, permite upload tradicional
|
| 199 |
+
if uploaded_file is None:
|
| 200 |
+
uploaded_file = st.file_uploader(
|
| 201 |
+
"Ou envie uma imagem (JPG ou PNG)",
|
| 202 |
+
type=["jpg", "jpeg", "png"],
|
| 203 |
+
)
|
| 204 |
|
| 205 |
if uploaded_file is not None:
|
| 206 |
try:
|
|
|
|
| 209 |
st.image(pil_img, caption="Imagem enviada", use_container_width=True)
|
| 210 |
st.write("")
|
| 211 |
|
| 212 |
+
st.markdown("## 2) Resultado da análise")
|
| 213 |
+
|
| 214 |
with st.spinner("Analisando a imagem com o modelo ArqueoIA..."):
|
| 215 |
probs = run_inference(pil_img)
|
| 216 |
|
|
|
|
| 241 |
|
| 242 |
st.success("Análise concluída com sucesso! ✅")
|
| 243 |
|
| 244 |
+
# ====================================================
|
| 245 |
+
# 5. Consultar especialista online (Chat com OpenAI)
|
| 246 |
+
# ====================================================
|
| 247 |
st.markdown("---")
|
| 248 |
+
st.markdown("## 3) Consultar especialista online")
|
| 249 |
|
| 250 |
+
if client is None:
|
| 251 |
+
st.info(
|
| 252 |
+
"A consulta ao especialista online está desativada no momento "
|
| 253 |
+
"(chave da OpenAI não configurada)."
|
| 254 |
+
)
|
| 255 |
+
else:
|
| 256 |
st.write(
|
| 257 |
+
"Use o campo abaixo para tirar dúvidas sobre o artefato analisado, "
|
| 258 |
+
"contextos históricos ou curiosidades. A resposta é gerada por IA."
|
| 259 |
+
)
|
| 260 |
+
|
| 261 |
+
pergunta_default = (
|
| 262 |
+
f"A imagem foi classificada como '{pred_label}' com confiança de "
|
| 263 |
+
f"{conf_max*100:.1f}%. Explique o que esse tipo de artefato costuma "
|
| 264 |
+
"representar em contextos arqueológicos."
|
| 265 |
)
|
| 266 |
|
| 267 |
+
pergunta = st.text_area(
|
| 268 |
+
"Digite sua pergunta para o especialista:",
|
| 269 |
+
value=pergunta_default,
|
| 270 |
+
height=120,
|
| 271 |
)
|
| 272 |
|
| 273 |
if st.button("Enviar pergunta ao especialista"):
|
| 274 |
+
with st.spinner("Consultando especialista online..."):
|
| 275 |
+
try:
|
| 276 |
+
resposta = client.chat.completions.create(
|
| 277 |
+
model="gpt-4o-mini",
|
| 278 |
+
messages=[
|
| 279 |
+
{
|
| 280 |
+
"role": "system",
|
| 281 |
+
"content": (
|
| 282 |
+
"Você é um arqueólogo e educador. "
|
| 283 |
+
"Responda em português de forma clara, "
|
| 284 |
+
"didática e adequada para estudantes do ensino básico e médio."
|
| 285 |
+
),
|
| 286 |
+
},
|
| 287 |
+
{
|
| 288 |
+
"role": "user",
|
| 289 |
+
"content": pergunta,
|
| 290 |
+
},
|
| 291 |
+
],
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 292 |
)
|
| 293 |
|
| 294 |
+
texto_resposta = (
|
| 295 |
+
resposta.choices[0].message.content
|
| 296 |
+
if resposta.choices and resposta.choices[0].message.content
|
| 297 |
+
else "Não foi possível obter uma resposta no momento."
|
| 298 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 299 |
|
| 300 |
+
st.markdown("#### Resposta do especialista")
|
| 301 |
+
st.write(texto_resposta)
|
| 302 |
+
|
| 303 |
+
except Exception as e:
|
| 304 |
+
st.error(f"Ocorreu um erro ao consultar o especialista: {e}")
|
| 305 |
|
| 306 |
except Exception as e:
|
| 307 |
st.error(f"Ocorreu um erro ao processar a imagem: {e}")
|
|
|
|
| 308 |
else:
|
| 309 |
+
st.info("Tire uma foto ou envie uma imagem para iniciar a análise.")
|
| 310 |
+
|
| 311 |
+
st.markdown("---")
|
| 312 |
+
st.markdown(
|
| 313 |
+
"<p style='text-align:center; font-size:0.9rem; color:#777;'>"
|
| 314 |
+
"Projeto educacional desenvolvido para o torneio FLL."
|
| 315 |
+
"</p>",
|
| 316 |
+
unsafe_allow_html=True,
|
| 317 |
+
)
|
| 318 |
+
|