Spaces:
Sleeping

Robsonfll commited on
Commit
1e0702e
·
verified ·
1 Parent(s): d638b9d

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +83 -238
src/streamlit_app.py CHANGED
@@ -1,265 +1,110 @@
1
- # ============================
2
- # src/streamlit_app.py
3
- # Layout Azul - Equipe Netuno
4
- # ============================
5
-
6
- import json
7
- from pathlib import Path
8
- import os
9
-
10
- import numpy as np
11
- from PIL import Image
12
  import streamlit as st
13
- import tensorflow as tf
14
-
15
- from openai import OpenAI
16
-
17
-
18
- # ============================================
19
- # 0. Configuração da API da OpenAI
20
- # ============================================
21
- OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")
22
- client = None
23
- if OPENAI_API_KEY:
24
- client = OpenAI(api_key=OPENAI_API_KEY)
25
-
26
- # ============================================
27
- # 1. Caminhos dos arquivos
28
- # ============================================
29
- SRC_DIR = Path(__file__).parent
30
- MODEL_PATH = SRC_DIR / "model.tflite"
31
- LABELS_PATH = SRC_DIR / "labels.txt"
32
- META_PATH = SRC_DIR / "meta.json"
33
- LOGO_PATH = SRC_DIR / "logo.png" # Coloque seu logo Netuno (opcional)
34
-
35
 
36
- # ============================================
37
- # 2. Estilo visual (CSS) - Tema Azul Netuno
38
- # ============================================
39
  st.set_page_config(
40
- page_title="ArqueoIA - Equipe Netuno",
41
- page_icon="🌊",
42
  layout="centered"
43
  )
44
 
 
 
 
45
  st.markdown(
46
- """
47
  <style>
48
- body {
49
- background-color: #e9f2ff;
50
- }
51
-
52
- .main {
53
- max-width: 900px;
54
- margin: 0 auto;
55
- padding-top: 30px;
56
- }
57
-
58
- h1, h2, h3 {
59
- font-family: 'Segoe UI', sans-serif;
60
- text-align: center;
61
- color: #003f7d;
62
- }
63
-
64
- .titulo-netuno {
65
- font-size: 42px;
66
- font-weight: 900;
67
- color: #0059c9;
68
- text-align: center;
69
- margin-bottom: -5px;
70
- letter-spacing: 1px;
71
- font-family: 'Segoe UI', sans-serif;
72
- }
73
-
74
- .descricao {
75
- text-align: center;
76
- color: #004b9b;
77
- font-size: 18px;
78
- margin-bottom: 18px;
79
- font-style: italic;
80
- padding-left: 20px;
81
- padding-right: 20px;
82
- }
83
-
84
- .card {
85
- background: #d9eaff;
86
- padding: 18px 25px;
87
- border-radius: 14px;
88
- margin: 25px 0;
89
- border-left: 6px solid #2d7dff;
90
- box-shadow: 0 3px 6px rgba(0,0,0,0.08);
91
- }
92
-
93
- .stButton>button {
94
- background-color: #2d7dff;
95
  color: white;
96
- border-radius: 10px;
97
- padding: 10px 22px;
98
- font-size: 16px;
99
  border: none;
100
- font-weight: bold;
101
- transition: 0.3s;
102
- }
103
-
104
- .stButton>button:hover {
105
- background-color: #1b5fcc;
106
- transform: scale(1.03);
107
- }
108
-
109
  </style>
110
  """,
111
- unsafe_allow_html=True,
112
  )
113
 
114
- # ============================================
115
- # 3. Carregadores
116
- # ============================================
117
- @st.cache_resource
118
- def load_interpreter():
119
- interpreter = tf.lite.Interpreter(model_path=str(MODEL_PATH))
120
- interpreter.allocate_tensors()
121
- return (
122
- interpreter,
123
- interpreter.get_input_details(),
124
- interpreter.get_output_details(),
125
- )
126
-
127
-
128
- @st.cache_data
129
- def load_labels():
130
- if LABELS_PATH.exists():
131
- return LABELS_PATH.read_text(encoding="utf-8").strip().split("\n")
132
- return []
133
-
134
-
135
- @st.cache_data
136
- def load_meta():
137
- meta = {"input_height": 224, "input_width": 224}
138
- if META_PATH.exists():
139
- try:
140
- data = json.loads(META_PATH.read_text(encoding="utf-8"))
141
- shape = data.get("input_shape", {})
142
- meta["input_height"] = int(shape.get("height", 224))
143
- meta["input_width"] = int(shape.get("width", 224))
144
- except:
145
- pass
146
- return meta
147
-
148
-
149
- # ============================================
150
- # 4. Funções de inferência
151
- # ============================================
152
- def preprocess_image(pil_img, target_size):
153
- h, w = target_size
154
- img = pil_img.convert("RGB").resize((w, h))
155
- arr = np.expand_dims(np.array(img).astype("float32") / 255.0, axis=0)
156
- return arr
157
-
158
-
159
- def run_inference(pil_img):
160
- interpreter, input_details, output_details = load_interpreter()
161
- meta = load_meta()
162
-
163
- input_data = preprocess_image(
164
- pil_img, (meta["input_height"], meta["input_width"])
165
- )
166
-
167
- interpreter.set_tensor(
168
- input_details[0]["index"], input_data.astype(input_details[0]["dtype"])
169
- )
170
- interpreter.invoke()
171
-
172
- output = interpreter.get_tensor(output_details[0]["index"])[0]
173
- exp = np.exp(output - np.max(output))
174
- return exp / exp.sum()
175
-
176
-
177
- # ============================================
178
- # 5. Interface Gráfica
179
- # ============================================
180
-
181
- # LOGO NETUNO (opcional)
182
- if LOGO_PATH.exists():
183
- st.image(str(LOGO_PATH), width=180)
184
-
185
- # TÍTULO PRINCIPAL — apenas "Equipe Netuno"
186
- st.markdown("<div class='titulo-netuno'>Equipe NETUNO</div>", unsafe_allow_html=True)
187
-
188
- # TEXTO QUE VOCÊ GOSTA — restaurado exatamente
189
- st.markdown(
190
- "<div class='descricao'>"
191
- "Sistema educacional de IA para identificar e classificar artefatos arqueológicos "
192
- "<br>(osso, cerâmica, moeda, flecha)."
193
- "</div>",
194
- unsafe_allow_html=True,
195
  )
196
 
197
- labels = load_labels()
198
-
199
-
200
- # 🔵 CARD: Envio de imagem
201
- st.markdown("<div class='card'><h3>1) Envie uma foto do artefato</h3>", unsafe_allow_html=True)
202
-
203
- uploaded_file = (
204
- st.camera_input("Tirar foto agora")
205
- or st.file_uploader("Ou selecione uma imagem", type=["jpg", "jpeg", "png"])
 
 
 
 
 
 
 
 
 
 
 
206
  )
207
 
208
- st.markdown("</div>", unsafe_allow_html=True)
209
-
210
-
211
- # Se imagem for enviada
212
  if uploaded_file:
213
- pil_img = Image.open(uploaded_file)
214
- st.image(pil_img, caption="Imagem enviada", use_container_width=True)
215
-
216
- # 🔵 CARD: Resultado
217
- st.markdown("<div class='card'><h3>2) Resultado da análise</h3>", unsafe_allow_html=True)
218
-
219
- with st.spinner("Analisando imagem com ArqueoIA..."):
220
- probs = run_inference(pil_img)
221
-
222
- idx = int(np.argmax(probs))
223
- pred = labels[idx] if idx < len(labels) else f"classe {idx}"
224
- conf = probs[idx] * 100
225
-
226
- st.success(f"🔍 Sugestão da IA: **{pred}** ({conf:.1f}% de confiança)")
227
 
228
- st.markdown("### 📊 Detalhamento das classes")
229
- for i, p in enumerate(probs):
230
- nome = labels[i] if i < len(labels) else f"classe {i}"
231
- st.write(f"- **{nome}**: {p*100:.1f}%")
232
-
233
- st.markdown("</div>", unsafe_allow_html=True)
234
 
 
 
235
 
236
- # 🔵 CARD: Consultar especialista
237
- st.markdown("<div class='card'><h3>3) Consultar Especialista</h3>", unsafe_allow_html=True)
238
-
239
- if client is None:
240
- st.warning("API da OpenAI não configurada.")
241
- else:
242
- pergunta = st.text_area(
243
- "Pergunte algo sobre o artefato identificado:",
244
- value=f"O modelo sugeriu '{pred}'. Explique sobre esse tipo de artefato."
245
  )
246
 
247
- if st.button("Consultar Especialista (IA)"):
248
- with st.spinner("Pensando..."):
249
- try:
250
- resposta = client.chat.completions.create(
251
- model="gpt-4o-mini",
252
- messages=[
253
- {"role": "system", "content": "Você é arqueólogo e explica com clareza."},
254
- {"role": "user", "content": pergunta}
255
- ],
256
- )
257
- st.info(resposta.choices[0].message.content)
258
 
259
- except Exception as e:
260
- st.error(f"Erro ao consultar IA: {e}")
 
 
261
 
262
- st.markdown("</div>", unsafe_allow_html=True)
 
 
 
263
 
264
- else:
265
- st.info("📌 Envie uma foto para começar a análise.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ from PIL import Image
3
+ import torch
4
+ from transformers import CLIPProcessor, CLIPModel
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
+ # =============================
7
+ # CONFIGURAÇÃO DO APP
8
+ # =============================
9
  st.set_page_config(
10
+ page_title="ArqueoIA – Identificação de Artefatos",
11
+ page_icon="🗿",
12
  layout="centered"
13
  )
14
 
15
+ # Tema azul Netuno
16
+ PRIMARY_COLOR = "#1f6feb"
17
+
18
  st.markdown(
19
+ f"""
20
  <style>
21
+ .reportview-container {{
22
+ background-color: #f1f8ff;
23
+ }}
24
+ .stButton>button {{
25
+ background-color: {PRIMARY_COLOR};
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
  color: white;
27
+ border-radius: 8px;
28
+ padding: 8px 16px;
 
29
  border: none;
30
+ }}
31
+ .stProgress > div > div > div {{
32
+ background-color: {PRIMARY_COLOR};
33
+ }}
 
 
 
 
 
34
  </style>
35
  """,
36
+ unsafe_allow_html=True
37
  )
38
 
39
+ # =============================
40
+ # TÍTULO
41
+ # =============================
42
+ st.title("🗿 ArqueoIA – Identificação de Artefatos Arqueológicos")
43
+ st.write(
44
+ "Sistema educacional de IA para identificar e classificar artefatos "
45
+ "**(osso, cerâmica, moeda, flecha)** utilizando tecnologia zero-shot."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
  )
47
 
48
+ # =============================
49
+ # CARREGAR MODELO CLIP
50
+ # =============================
51
+ @st.cache_resource
52
+ def load_model():
53
+ model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
54
+ processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")
55
+ return model, processor
56
+
57
+ model, processor = load_model()
58
+
59
+ # Classes alvo
60
+ CLASSES = ["osso", "cerâmica", "moeda", "flecha"]
61
+
62
+ # =============================
63
+ # UPLOAD DA IMAGEM
64
+ # =============================
65
+ uploaded_file = st.file_uploader(
66
+ "Envie uma imagem para análise",
67
+ type=["jpg", "jpeg", "png"]
68
  )
69
 
 
 
 
 
70
  if uploaded_file:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
 
72
+ img = Image.open(uploaded_file).convert("RGB")
73
+ st.image(img, caption="Imagem enviada", use_column_width=True)
 
 
 
 
74
 
75
+ st.markdown("## 🔍 2) Resultado da análise")
76
+ with st.spinner("Analisando imagem com IA Zero-Shot..."):
77
 
78
+ # Preparação
79
+ inputs = processor(
80
+ text=CLASSES,
81
+ images=img,
82
+ return_tensors="pt",
83
+ padding=True
 
 
 
84
  )
85
 
86
+ # Inferência
87
+ with torch.no_grad():
88
+ outputs = model(**inputs)
89
+ logits = outputs.logits_per_image[0]
90
+ probs = logits.softmax(dim=0)
 
 
 
 
 
 
91
 
92
+ # Resultado
93
+ best_idx = probs.argmax().item()
94
+ best_class = CLASSES[best_idx]
95
+ best_score = float(probs[best_idx] * 100)
96
 
97
+ # Caixa final
98
+ st.success(
99
+ f"📌 **A imagem foi classificada como `{best_class}` com {best_score:.1f}% de confiança.**"
100
+ )
101
 
102
+ # Detalhamento
103
+ st.markdown("### 📊 Detalhamento das classes")
104
+ for cls, p in zip(CLASSES, probs):
105
+ st.write(f"• **{cls.capitalize()}**: {float(p*100):.1f}%")
106
+
107
+ st.info(
108
+ "💡 *Dica:* Para obter melhores resultados, envie imagens claras, "
109
+ "centralizadas e com boa iluminação."
110
+ )