-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
438 lines (388 loc) · 11.8 KB
/
app.py
File metadata and controls
438 lines (388 loc) · 11.8 KB
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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
import time
import streamlit as st
from bot.config import Config
from bot.ingestor import ingest_pdf_to_faiss
from bot.quiz_manager import QuizManager
from bot.utils.answer_evaluator import AnswerEvaluator
from bot.utils.clean_db import clean_database
from bot.utils.document_manager import ensure_document
from bot.utils.logger import get_logger
logger = get_logger("app")
st.set_page_config(page_title="RAG Quiz", page_icon="💬", layout="centered")
# CSS CORRIGIDO com melhor alinhamento
CSS = """
<style>
header, .stApp header { display: none; }
.block-container { max-width: 760px !important; padding-top: 0; }
/* Header estilo WhatsApp */
#whats-header {
position: sticky; top: 0; z-index: 9999;
background: #075E54; color: #fff; padding: 12px 16px;
display: flex; align-items: center; gap: 12px;
border-bottom: 1px solid #054d46; border-radius: 0 0 12px 12px;
box-shadow: 0 2px 8px rgba(0,0,0,.3);
margin-bottom: 15px;
}
#whats-header .avatar {
width: 40px; height: 40px; background: #128C7E; border-radius: 50%;
display: grid; place-items: center; font-size: 20px;
border: 2px solid #fff;
}
#whats-header .title { font-weight: 700; letter-spacing: .2px; font-size: 16px; }
#whats-header .subtitle { font-size: 12px; opacity: .9; color: #e0e0e0; }
/* Container principal do chat */
.chat-container {
display: flex;
flex-direction: column;
gap: 4px;
padding: 0 8px;
}
/* Linhas de chat CORRIGIDAS */
.chat-row {
display: flex;
margin: 6px 0;
gap: 8px;
align-items: flex-start;
width: 100%;
}
.chat-row.assistant {
justify-content: flex-start;
flex-direction: row;
}
.chat-row.user {
flex-direction: row-reverse;
}
/* Avatares com emojis - CORRIGIDO */
.chat-avatar {
width: 32px;
height: 32px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
font-size: 16px;
flex-shrink: 0;
margin-top: 2px;
}
.chat-avatar.assistant {
background: linear-gradient(135deg, #25D366 0%, #128C7E 100%);
color: white;
border: 2px solid #fff;
box-shadow: 0 2px 4px rgba(0,0,0,.2);
}
.chat-avatar.user {
background: linear-gradient(135deg, #34B7F1 0%, #128C7E 100%);
color: white;
border: 2px solid #fff;
box-shadow: 0 2px 4px rgba(0,0,0,.2);
}
/* Bolhas de chat melhoradas e centralizadas */
.chat-bubble {
max-width: 70%;
padding: 10px 14px;
border-radius: 18px;
line-height: 1.4;
word-wrap: break-word;
box-shadow: 0 1px 2px rgba(0,0,0,.1);
font-size: 14px;
position: relative;
}
.chat-bubble.assistant {
background: #ffffff;
border: 1px solid #e0e0e0;
color: #303030;
border-top-left-radius: 4px;
margin-left: 0;
}
.chat-bubble.user {
background: #DCF8C6;
color: #303030;
border-top-right-radius: 4px;
margin-right: 0;
}
/* Timestamp */
.chat-time {
font-size: 11px;
color: #666;
text-align: right;
margin-top: 4px;
font-family: Arial, sans-serif;
}
/* Separador */
.separator {
margin: 20px 0;
border-top: 1px solid #e0e0e0;
display: flex;
justify-content: center;
position: relative;
}
.separator::before {
content: "●";
color: #999;
font-size: 10px;
position: absolute;
top: -7px;
background: white;
padding: 0 10px;
}
/* Botões de opção estilo WhatsApp */
.option-btn {
width: 100%;
text-align: left;
background: #f8f9fa;
color: #111;
border: 1px solid #e0e0e0;
border-radius: 18px;
padding: 14px 18px;
margin: 6px 0;
cursor: pointer;
font-size: 14px;
transition: all 0.2s ease;
box-shadow: 0 1px 2px rgba(0,0,0,.05);
}
.option-btn:hover {
background:#ffffff;
border-color: #25D366;
box-shadow: 0 2px 6px rgba(37, 211, 102, 0.2);
transform: translateY(-1px);
}
/* Card final */
.final-card {
background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
border: 1px solid #e0e0e0;
border-radius: 18px;
padding: 20px;
margin: 20px 0;
text-align: center;
box-shadow: 0 4px 12px rgba(0,0,0,.1);
color: #303030;
}
.final-card h4 { color: #075E54; margin-bottom: 15px; }
.final-card .score {
font-size: 24px; font-weight: bold; color: #25D366;
margin: 10px 0;
}
/* Feedback com emojis */
.feedback-correct {
color: #25D366;
font-weight: 600;
}
.feedback-incorrect {
color: #FF4444;
font-weight: 600;
}
/* Botão próxima pergunta */
.stButton > button {
background: linear-gradient(135deg, #25D366 0%, #128C7E 100%);
color: white;
border: none;
border-radius: 24px;
padding: 12px 30px;
font-size: 14px;
font-weight: 600;
cursor: pointer;
transition: all 0.3s ease;
box-shadow: 0 2px 8px rgba(37, 211, 102, 0.3);
width: 100%;
}
.stButton > button:hover {
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(37, 211, 102, 0.4);
}
/* Centralização do conteúdo */
.main .block-container {
padding-top: 0;
padding-bottom: 20px;
}
/* Oculta a tag <code> e o seu conteúdo */
code {
display: none !important;
}
/* Oculta o pai imediato de <code>, que costuma ser a tag <pre> no HTML */
pre {
display: none !important;
}
</style>
"""
st.markdown(CSS, unsafe_allow_html=True)
# Header com emoji
st.markdown(
"""
<div id="whats-header">
<div class="avatar">🤖</div>
<div>
<div class="title">RAG Quiz</div>
<div class="subtitle">🟢 Online • Chat Mode</div>
</div>
</div>
""",
unsafe_allow_html=True,
)
# -------------------------
# Session state (somente lógica, sem alterar front)
# -------------------------
ss = st.session_state
ss.setdefault("booted", False)
ss.setdefault("idx", 0)
ss.setdefault("score", 0)
ss.setdefault("history", [])
ss.setdefault("phase", "ask")
ss.setdefault("clicked", False)
ss.setdefault("current_question", None)
ss.setdefault("quiz_manager", None)
ss.setdefault("total_questions", 10) # manter 10, conforme solicitado
ss.setdefault("correct", None)
ss.setdefault("feedback", "")
ss.setdefault("user_answer", "")
ss.setdefault("loading_answer", False)
def bubble(role, text, show_time=True):
side = "assistant" if role == "assistant" else "user"
avatar = "🤖" if role == "assistant" else "👤"
if show_time:
current_time = time.strftime("%H:%M")
time_html = f'<div class="chat-time">{current_time}</div>'
else:
time_html = ""
st.markdown(
f"""
<div class="chat-row {side}">
<div class="chat-avatar {side}">{avatar}</div>
<div class="chat-bubble {side}">
{text}
{time_html}
</div>
</div>
""",
unsafe_allow_html=True,
)
def fetch_one_question():
with st.spinner("🤖 Generating next question..."):
qs = ss.quiz_manager.get_questions(
num_questions=1, chunks_per_q=2, cache_mode="append"
)
if not qs:
return None
return qs[0]
def boot():
if ss.booted:
return
if Config.REGENERATE_QUESTIONS_ON_START:
clean_database("questions")
vectorstore = ingest_pdf_to_faiss()
ss.quiz_manager = QuizManager(vectorstore=vectorstore)
ss.answer_evaluator = AnswerEvaluator()
ss.current_question = fetch_one_question()
ss.booted = True
boot()
st.markdown('<div class="chat-container">', unsafe_allow_html=True)
if ss.idx == 0 and not ss.clicked:
bubble(
"assistant",
"Hello! Welcome to the RAG Quiz! 💰\n\nLet's test your knowledge. Answer the questions below by interacting in the chat! 📝",
)
if ss.idx >= ss.total_questions:
st.markdown("</div>", unsafe_allow_html=True)
percentage = (ss.score / ss.total_questions) * 100
if percentage >= 80:
emoji = "🎉"
message = "Excellent! You are an expert! 🚀"
elif percentage >= 60:
emoji = "👍"
message = "Very good! You’re on the right track! 💪"
else:
emoji = "📚"
message = "Keep studying! Knowledge is the key! 🔑"
st.markdown(
f"""
<div class='final-card'>
<h4>{emoji} End of the Quiz! {emoji}</h4>
<div class='score'>🎯 Score: {ss.score}/{ss.total_questions}</div>
<p>📊 <strong>{percentage:.0f}%</strong> correct answers</p>
<p>{message}</p>
<p>💡 Thank you for participating!</p>
</div
""",
unsafe_allow_html=True,
)
st.stop()
if ss.current_question is None:
ss.current_question = fetch_one_question()
q = ss.current_question
if q is not None:
options_text = "\n".join(
[f"{label}) {opt}\n" for label, opt in zip(["A", "B", "C", "D"], q["options"])]
)
bubble("assistant", f"Question {ss.idx + 1}:\n\n{q['question']}\n\n{options_text}")
else:
bubble("assistant", "⚠️ It was not possible to generate the question right now. Please try again.")
st.stop()
if not ss.clicked:
# Input field
st.write("")
user_input = st.text_input(
"✏️ Type your answer below:",
key=f"input_{ss.idx}",
placeholder="Type your answer here...",
label_visibility="collapsed",
)
# If not loading yet, show button
if not ss.get("loading_answer", False):
if st.button("📨 Submit Answer", use_container_width=True):
if user_input.strip() == "":
st.warning("⚠️ Please type an answer before submitting.")
else:
ss.user_answer = user_input.strip()
ss.loading_answer = True
st.rerun()
# If loading, run the evaluation here
if ss.get("loading_answer", False):
with st.spinner("🤖 Evaluating your answer..."):
evaluation = ss.answer_evaluator.evaluate(
user_answer=ss.user_answer,
options=q["options"],
correct_index=q["answer_index"],
)
ss.correct = evaluation["is_correct"]
correct_answer = q["options"][q["answer_index"]]
matched_answer = evaluation.get("matched_option")
if ss.correct:
ss.feedback = (
f"✅ Correct! 🎉\n\n"
f"📌 Your answer: {matched_answer or ss.user_answer}\n\n"
f"💡 Explanation: {q.get('explanation', 'Correct answer! Keep it up!')}"
)
ss.score += 1
else:
ss.feedback = (
f"❌ Your answer: {matched_answer or ss.user_answer}\n\n"
f"✅ Correct answer: {correct_answer}\n\n"
f"💡 Explanation: {q.get('explanation', 'Study this topic further!')}"
)
ss.loading_answer = False
ss.clicked = True
st.rerun()
else:
# Show user answer
bubble("user", ss.user_answer)
# Show feedback
if ss.correct:
st.markdown('<div class="feedback-correct">', unsafe_allow_html=True)
bubble("assistant", ss.feedback, show_time=False)
st.markdown("</div>", unsafe_allow_html=True)
else:
st.markdown('<div class="feedback-incorrect">', unsafe_allow_html=True)
bubble("assistant", ss.feedback, show_time=False)
st.markdown("</div>", unsafe_allow_html=True)
# Next question bubble
if st.button("➡️ Próxima Pergunta", use_container_width=True, type="primary"):
ss.idx += 1
ss.clicked = False
if ss.idx >= ss.total_questions:
# Last question -> final screen on top of the script
st.rerun()
else:
# Generate next question
ss.current_question = fetch_one_question()
st.rerun()
st.markdown("</div>", unsafe_allow_html=True)
st.markdown("---")