Download src/streamlit_app.py from Robsonfll/ArqueoIA: direct link, hf CLI and curl.
- Browser
- Download file 9.9 kB
-
https://huggingface.co/spaces/Robsonfll/ArqueoIA/resolve/main/src/streamlit_app.py
- Command line
-
hf download hf://spaces/Robsonfll/ArqueoIA/src/streamlit_app.py
-
curl -L -o streamlit_app.py https://huggingface.co/spaces/Robsonfll/ArqueoIA/resolve/main/src/streamlit_app.py
9.9 kB
| # 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 | |
| # ============================================================ | |
| 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(), | |
| ) | |
| def load_labels(): | |
| if not LABELS_PATH.exists(): | |
| return [] | |
| return LABELS_PATH.read_text(encoding="utf-8").splitlines() | |
| 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(""" | |
| <style> | |
| body { background-color: #f4f5f7; } | |
| .main { | |
| max-width: 900px; | |
| margin: 0 auto; | |
| padding-top: 1.5rem; | |
| font-family: "Segoe UI", sans-serif; | |
| } | |
| .app-card { | |
| background: white; | |
| padding: 2rem; | |
| border-radius: 16px; | |
| box-shadow: 0 10px 30px rgba(0,0,0,0.08); | |
| } | |
| .netuno-title { | |
| font-size: 2.6rem; | |
| font-weight: 800; | |
| color: #1A73E8; | |
| text-align: center; | |
| margin-bottom: -8px; | |
| } | |
| .arqueoia-title { | |
| font-size: 2rem; | |
| font-weight: 700; | |
| color: #222; | |
| text-align: center; | |
| } | |
| .subtitle { | |
| color: #555; | |
| text-align: center; | |
| margin-top: -6px; | |
| margin-bottom: 16px; | |
| font-size: 1.05rem; | |
| } | |
| .section-header { | |
| font-size: 1.1rem; | |
| font-weight: 600; | |
| margin: 12px 0; | |
| display: flex; | |
| align-items: center; | |
| } | |
| .section-num { | |
| background: #1A73E8; | |
| color: white; | |
| border-radius: 50%; | |
| width: 26px; | |
| height: 26px; | |
| display: flex; | |
| justify-content: center; | |
| align-items: center; | |
| margin-right: 10px; | |
| } | |
| .chat-bubble { | |
| padding: 0.6rem 0.9rem; | |
| border-radius: 10px; | |
| margin-bottom: 6px; | |
| font-size: 0.95rem; | |
| } | |
| .chat-user { | |
| background: #e0ecff; | |
| border: 1px solid #b7d0ff; | |
| } | |
| .chat-assistant { | |
| background: #f0f0f0; | |
| border: 1px solid #dcdcdc; | |
| } | |
| </style> | |
| """, unsafe_allow_html=True) | |
| # Cabeçalho | |
| st.markdown('<div class="netuno-title">Equipe Netuno</div>', unsafe_allow_html=True) | |
| st.markdown('<div class="arqueoia-title">ArqueoIA</div>', unsafe_allow_html=True) | |
| st.markdown( | |
| '<p class="subtitle">Uma solução moderna de inteligência artificial criada para identificar e classificar artefatos arqueológicos de maneira confiável e educativa.</p>', | |
| unsafe_allow_html=True, | |
| ) | |
| # Caixa (card) | |
| st.markdown('<div class="app-card">', 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('<div class="section-header"><div class="section-num">1</div>Enviar imagem</div>', 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('<div class="section-header"><div class="section-num">2</div>Visualização</div>', unsafe_allow_html=True) | |
| st.image(img, use_container_width=True) | |
| # ====================================================== | |
| # Seção 3 — Resultado | |
| # ====================================================== | |
| st.markdown('<div class="section-header"><div class="section-num">3</div>Resultado</div>', 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('<div class="section-header"><div class="section-num">4</div>Consultar especialista</div>', 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'<div class="chat-bubble {css}"><b>{nome}:</b> {msg["content"]}</div>', | |
| 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("</div>", unsafe_allow_html=True) | |
| # Rodapé | |
| st.markdown("<hr>", unsafe_allow_html=True) | |
| st.markdown( | |
| "<p style='text-align:center; color:#777;'>🌍 Projeto educacional desenvolvido para o torneio FLL.</p>", | |
| unsafe_allow_html=True, | |
| ) | |