File size: 9,904 Bytes
107eb4b
0d50058
107eb4b
 
 
acdfc93
107eb4b
 
 
 
 
25c25e7
107eb4b
5257ecf
107eb4b
1350a72
107eb4b
73b5a41
1350a72
107eb4b
5257ecf
107eb4b
 
 
 
 
 
 
 
5257ecf
107eb4b
 
 
 
 
 
5257ecf
 
 
 
 
107eb4b
 
 
 
 
5257ecf
107eb4b
 
 
 
 
 
73b5a41
107eb4b
5257ecf
 
 
 
 
107eb4b
 
 
 
5257ecf
107eb4b
 
5257ecf
 
 
107eb4b
5257ecf
107eb4b
5257ecf
107eb4b
5257ecf
107eb4b
 
5257ecf
 
 
107eb4b
dd0baa6
5257ecf
 
 
107eb4b
 
5257ecf
107eb4b
 
5257ecf
1350a72
5257ecf
107eb4b
e01397d
5257ecf
 
107eb4b
5257ecf
107eb4b
e01397d
107eb4b
 
 
e01397d
5257ecf
 
e01397d
5257ecf
107eb4b
 
 
5257ecf
107eb4b
5257ecf
 
 
107eb4b
 
 
5257ecf
107eb4b
 
5257ecf
107eb4b
 
 
 
5257ecf
 
 
1b59d63
e01397d
 
 
5257ecf
e01397d
5257ecf
 
e01397d
 
 
5257ecf
e01397d
5257ecf
 
 
 
 
 
 
 
e01397d
 
 
5257ecf
e01397d
 
 
 
 
 
5257ecf
 
e01397d
 
 
5257ecf
 
e01397d
 
107eb4b
5257ecf
acdfc93
5257ecf
107eb4b
 
1b59d63
 
 
 
4ff4ed4
73b5a41
e01397d
633d63c
107eb4b
73b5a41
107eb4b
acdfc93
107eb4b
 
 
 
 
 
 
 
 
 
5257ecf
107eb4b
 
5257ecf
107eb4b
5257ecf
acdfc93
73b5a41
5257ecf
 
 
73b5a41
5257ecf
 
 
 
 
73b5a41
5257ecf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73b5a41
5257ecf
 
 
 
 
73b5a41
5257ecf
73b5a41
 
5257ecf
73b5a41
 
5257ecf
73b5a41
5257ecf
0d50058
 
73b5a41
 
 
5257ecf
 
73b5a41
 
 
5257ecf
73b5a41
5257ecf
73b5a41
 
 
 
 
5257ecf
 
73b5a41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9be0825
107eb4b
5257ecf
107eb4b
5257ecf
e01397d
 
5257ecf
107eb4b
 
5257ecf
107eb4b
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
# 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("""
<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,
)