# src/streamlit_app.py
import json
from pathlib import Path
import os
import numpy as np
from PIL import Image
import streamlit as st
import tensorflow as tf
from openai import OpenAI
# ============================================================
# 0. OpenAI — especialista
# ============================================================
OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")
client = OpenAI(api_key=OPENAI_API_KEY) if OPENAI_API_KEY else None
# ============================================================
# 1. Arquivos
# ============================================================
SRC_DIR = Path(__file__).parent
MODEL_PATH = SRC_DIR / "model.tflite"
LABELS_PATH = SRC_DIR / "labels.txt"
META_PATH = SRC_DIR / "meta.json"
# ============================================================
# 2. Carregamento
# ============================================================
@st.cache_resource
def load_interpreter():
interpreter = tf.lite.Interpreter(model_path=str(MODEL_PATH))
interpreter.allocate_tensors()
return (
interpreter,
interpreter.get_input_details(),
interpreter.get_output_details(),
)
@st.cache_data
def load_labels():
if not LABELS_PATH.exists():
return []
return LABELS_PATH.read_text(encoding="utf-8").splitlines()
@st.cache_data
def load_meta():
meta = {"input_height": 224, "input_width": 224}
if META_PATH.exists():
try:
data = json.loads(META_PATH.read_text())
shape = data.get("input_shape") or data.get("expected_input_shape") or {}
h = shape.get("height") or shape.get("1") or 224
w = shape.get("width") or shape.get("2") or 224
meta["input_height"] = int(h)
meta["input_width"] = int(w)
except:
pass
return meta
# ============================================================
# 3. Inferência
# ============================================================
def preprocess(img, size):
h, w = size
img = img.convert("RGB").resize((w, h))
arr = np.array(img).astype("float32") / 255.0
return np.expand_dims(arr, axis=0)
def run_inference(img):
meta = load_meta()
size = (meta["input_height"], meta["input_width"])
interpreter, input_details, output_details = load_interpreter()
arr = preprocess(img, size)
arr = arr.astype(input_details[0]["dtype"])
interpreter.set_tensor(input_details[0]["index"], arr)
interpreter.invoke()
out = interpreter.get_tensor(output_details[0]["index"])[0]
ex = np.exp(out - np.max(out))
return ex / np.sum(ex)
# ============================================================
# 4. Layout visual
# ============================================================
st.set_page_config(page_title="ArqueoIA - Equipe Netuno", layout="centered")
st.markdown("""
""", unsafe_allow_html=True)
# Cabeçalho
st.markdown('
Equipe Netuno
', unsafe_allow_html=True)
st.markdown('ArqueoIA
', unsafe_allow_html=True)
st.markdown(
'Uma solução moderna de inteligência artificial criada para identificar e classificar artefatos arqueológicos de maneira confiável e educativa.
',
unsafe_allow_html=True,
)
# Caixa (card)
st.markdown('', unsafe_allow_html=True)
# ============================================================
# 5. Estados
# ============================================================
if "chat_history" not in st.session_state:
st.session_state["chat_history"] = []
if "last_pred_label" not in st.session_state:
st.session_state["last_pred_label"] = None
if "last_conf" not in st.session_state:
st.session_state["last_conf"] = None
labels = load_labels()
# ============================================================
# 6. Seção 1 - Imagem
# ============================================================
st.markdown('', unsafe_allow_html=True)
uploaded_file = st.camera_input("Tire uma foto") or st.file_uploader("Ou envie uma imagem", type=["jpg","jpeg","png"])
if uploaded_file:
img = Image.open(uploaded_file)
# ======================================================
# Seção 2 - Visualização
# ======================================================
st.markdown('', unsafe_allow_html=True)
st.image(img, use_container_width=True)
# ======================================================
# Seção 3 — Resultado
# ======================================================
st.markdown('', unsafe_allow_html=True)
with st.spinner("Analisando artefato..."):
probs = run_inference(img)
idx = int(np.argmax(probs))
conf = float(probs[idx])
label = labels[idx] if labels else f"classe {idx}"
st.markdown(f"**Artefato identificado:** `{label}`")
st.markdown(f"**Precisão estimada:** `{conf*100:.1f}%`")
st.markdown("### Distribuição por classe")
for i, p in enumerate(probs):
name = labels[i] if labels else f"classe {i}"
col1, col2 = st.columns([1,4])
col1.write(f"**{name}**")
col2.progress(float(p))
st.session_state["last_pred_label"] = label
st.session_state["last_conf"] = conf
# ======================================================
# Seção 4 — Especialista (CHAT COM 1 CLIQUE)
# ======================================================
st.markdown("---")
st.markdown('', unsafe_allow_html=True)
if client is None:
st.error("OPENAI_API_KEY não configurada.")
else:
# Exibir chat
for msg in st.session_state["chat_history"]:
css = "chat-user" if msg["role"] == "user" else "chat-assistant"
nome = "Você" if msg["role"] == "user" else "Especialista"
st.markdown(
f'
{nome}: {msg["content"]}
',
unsafe_allow_html=True,
)
# FORM — 1 clique funcionando
with st.form("form_chat", clear_on_submit=True):
pergunta = st.text_input("Digite sua pergunta:")
enviar = st.form_submit_button("Enviar")
if enviar:
pergunta = pergunta.strip()
if pergunta:
st.session_state["chat_history"].append({"role": "user", "content": pergunta})
contexto = ""
if st.session_state["last_pred_label"]:
contexto = (
f"O artefato analisado foi identificado como '{st.session_state['last_pred_label']}'. "
"Use essa informação apenas como referência contextual."
)
mensagens = [
{
"role": "system",
"content": (
"Você é um arqueólogo especialista. "
"Explique de forma clara, natural e didática. "
"Não mencione confiança do modelo. "
"Foque apenas em conteúdo arqueológico e educativo."
),
}
]
if contexto:
mensagens.append({"role": "user", "content": contexto})
for m in st.session_state["chat_history"]:
mensagens.append(m)
with st.spinner("Especialista respondendo..."):
try:
resposta = client.chat.completions.create(
model="gpt-4o-mini",
messages=mensagens
)
texto = resposta.choices[0].message.content.strip()
st.session_state["chat_history"].append({"role": "assistant", "content": texto})
except Exception as e:
st.error(f"Erro ao consultar especialista: {e}")
else:
st.info("Envie uma imagem para começar.")
# Fecha card
st.markdown("
", unsafe_allow_html=True)
# Rodapé
st.markdown("
", unsafe_allow_html=True)
st.markdown(
"🌍 Projeto educacional desenvolvido para o torneio FLL.
",
unsafe_allow_html=True,
)