-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstudy_only.py
More file actions
374 lines (329 loc) · 17.2 KB
/
Copy pathstudy_only.py
File metadata and controls
374 lines (329 loc) · 17.2 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
"""
FlashCard Studio — Streamlit App
Image input methods for answers:
1. Regular file uploader (browse)
2. Drag-and-drop onto the paste zone
3. Clipboard paste (Ctrl+V / Cmd+V) anywhere on the page
The paste/drop bridge:
- An HTML component captures paste/drop events and converts the image to a
base64 data-URL.
- JS then finds the hidden Streamlit textarea (aria-label="__paste_relay__")
in the parent document and sets its value, firing React synthetic events so
Streamlit registers the change.
- Python reads session_state for that key and saves the image to disk.
"""
import streamlit as st
import streamlit.components.v1 as components
import json, base64, os, random, uuid
from pathlib import Path
from PIL import Image
import io
import markdown as md_lib
st.set_page_config(page_title="FlashCard Studio", page_icon="🧠", layout="wide")
DATA_FILE = "flashcard_data.json"
IMAGES_DIR = "flashcard_images"
os.makedirs(IMAGES_DIR, exist_ok=True)
# ─── persistence ──────────────────────────────────────────────────────────────
def load_data():
if os.path.exists(DATA_FILE):
with open(DATA_FILE) as f:
return json.load(f)
return {}
def save_data(d):
with open(DATA_FILE, "w") as f:
json.dump(d, f, indent=2)
def img_to_b64(path):
if path and os.path.exists(path):
with open(path, "rb") as f:
ext = Path(path).suffix.lower().lstrip(".")
mime = {"jpg":"jpeg","jpeg":"jpeg","png":"png","gif":"gif","webp":"webp"}.get(ext,"png")
return f"data:image/{mime};base64,{base64.b64encode(f.read()).decode()}"
return None
# ─── session state ───────────────────────────────────────────────────────────
for k, v in [("data", load_data()), ("study_state", {}), ("show_setup", True)]:
if k not in st.session_state:
st.session_state[k] = v
data = st.session_state.data
# ─── CSS ──────────────────────────────────────────────────────────────────────
st.markdown("""
<style>
.main-title{font-size:2.4rem;font-weight:800;color:#4F46E5;margin-bottom:.2rem}
.card-front {
background: linear-gradient(135deg, #667eea, #764ba2);
border-radius: 16px;
padding: 2rem;
color: #fff;
font-size: 1.3rem;
font-weight: 600;
text-align: center; /* was: center */
min-height: 180px;
display: flex;
flex-direction: column; /* ADD: stacks children vertically */
align-items: center; /* was: center — lets content left-align */
justify-content: center;
box-shadow: 0 8px 32px rgba(79, 70, 229, .3);
margin-bottom: 1rem;
}
.card-back img{max-width:100%;max-height:700px;border-radius:10px;margin-top:1rem}
.progress-bar{background:#E5E7EB;border-radius:8px;height:12px}
.progress-fill{background:#4F46E5;border-radius:8px;height:12px}
.badge{display:inline-block;background:#EEF2FF;color:#4F46E5;border-radius:20px;
padding:2px 12px;font-size:.8rem;font-weight:600;margin:2px}
.section-header{font-size:1.1rem;font-weight:700;color:#374151;
border-left:4px solid #4F46E5;padding-left:10px;margin:1.2rem 0 .6rem 0}
/* ── Topic grid: force every column cell to the same fixed height so rows
stay perfectly aligned no matter how long the label text is. ── */
div[data-testid="stHorizontalBlock"] > div[data-testid="stColumn"] {
height: 56px !important;
overflow: visible !important;
display: flex !important;
flex-direction: column !important; /* ← keep only this one */
justify-content: flex-start !important;
white-space: nowrap !important;
}
/* Keep the actual checkbox widget from inheriting the flex stretch */
div[data-testid="stHorizontalBlock"] > div[data-testid="stColumn"]
> div[data-testid="stCheckbox"] {
margin-top: 0 !important;
padding-top: 0 !important;
}
/* Prevent the checkbox label from pushing the row taller */
div[data-testid="stHorizontalBlock"] > div[data-testid="stColumn"]
> div[data-testid="stCheckbox"] label {
white-space: nowrap !important;
overflow: hidden !important;
text-overflow: ellipsis !important;
display: block !important;
}
</style>
""", unsafe_allow_html=True)
# ─── header ──────────────────────────────────────────────────────────────────
st.markdown('<div class="main-title">🦠 Micro and 🧬 Immuno Flashcard Study</div>', unsafe_allow_html=True)
st.divider()
if not data:
st.info("No flashcard data found. Make sure flashcard_data.json is in the same folder as this app.")
else:
ss = st.session_state.study_state
# ── Pre-initialise all checkbox state before any widgets render ──────────
all_classes = list(data.keys())
if "select_all_classes" not in st.session_state:
st.session_state["select_all_classes"] = True
for cls in all_classes:
if f"class_cb_{cls}" not in st.session_state:
st.session_state[f"class_cb_{cls}"] = True
if f"select_all_topics_{cls}" not in st.session_state:
st.session_state[f"select_all_topics_{cls}"] = True
for t in data[cls]:
if f"topic_cb_{cls}_{t}" not in st.session_state:
st.session_state[f"topic_cb_{cls}_{t}"] = True
# ── Callbacks ─────────────────────────────────────────────────────────────
def on_select_all_classes():
val = st.session_state["select_all_classes"]
for cls in all_classes:
st.session_state[f"class_cb_{cls}"] = val
st.session_state[f"select_all_topics_{cls}"] = val
for t in data[cls]:
st.session_state[f"topic_cb_{cls}_{t}"] = val
def make_class_cb(cls):
def on_class_cb():
val = st.session_state[f"class_cb_{cls}"]
# Cascade down to this class's topics only
st.session_state[f"select_all_topics_{cls}"] = val
for t in data[cls]:
st.session_state[f"topic_cb_{cls}_{t}"] = val
# Sync global select-all (True only if ALL classes are checked)
st.session_state["select_all_classes"] = all(
st.session_state.get(f"class_cb_{c}", True) for c in all_classes
)
return on_class_cb
def make_select_all_topics_cb(cls):
def on_select_all_topics():
val = st.session_state[f"select_all_topics_{cls}"]
# Cascade down to this class's topics only
for t in data[cls]:
st.session_state[f"topic_cb_{cls}_{t}"] = val
# Sync class checkbox to match
st.session_state[f"class_cb_{cls}"] = val
# Sync global select-all
st.session_state["select_all_classes"] = all(
st.session_state.get(f"class_cb_{c}", True) for c in all_classes
)
return on_select_all_topics
def make_topic_cb(cls):
def on_topic_cb():
topics = list(data[cls].keys())
all_on = all(st.session_state.get(f"topic_cb_{cls}_{t}", True) for t in topics)
any_on = any(st.session_state.get(f"topic_cb_{cls}_{t}", False) for t in topics)
# "Select all topics" is only checked when every topic is on
st.session_state[f"select_all_topics_{cls}"] = all_on
# Class checkbox stays True as long as at least one topic is checked
st.session_state[f"class_cb_{cls}"] = any_on
# Sync global select-all
st.session_state["select_all_classes"] = all(
st.session_state.get(f"class_cb_{c}", True) for c in all_classes
)
return on_topic_cb
# ── Setup toggle (shown only when a session is active) ───────────────────
if ss.get("deck"):
toggle_label = "🔼 Hide Setup" if st.session_state.show_setup else "🔽 Change Setup"
if st.button(toggle_label):
st.session_state.show_setup = not st.session_state.show_setup
st.rerun()
if st.session_state.show_setup:
# st.markdown('<div class="section-header">Study Session Setup</div>',
# unsafe_allow_html=True)
# ── Top controls ──────────────────────────────────────────────────────
top1, top2 = st.columns([0.325, 1], gap='small')
with top1:
st.checkbox("📚 Select All Classes", key="select_all_classes",
on_change=on_select_all_classes)
with top2:
shuffle = st.checkbox("🔀 Shuffle cards", value=True)
else:
shuffle = st.session_state.get("_last_shuffle", True)
# if st.session_state.show_setup:
st.divider()
# ── Per-class sections ─────────────────────────────────────────────────────
# FIX: Topics are ALWAYS rendered regardless of class checkbox state.
# Previously they were hidden when the class was unchecked, which caused
# Streamlit to destroy and recreate those widgets on every toggle,
# resetting all their state values and producing the "deselects everything" bug.
if st.session_state.show_setup:
for cls in all_classes:
topics = list(data[cls].keys())
total_cls_cards = sum(len(data[cls][t]) for t in topics)
# Class-level checkbox
st.checkbox(
f"**{cls}** — {len(topics)} topic(s), {total_cls_cards} card(s)",
key=f"class_cb_{cls}",
on_change=make_class_cb(cls),
)
# "Select all topics" toggle — always visible
if topics:
st.checkbox(
"Select all topics",
key=f"select_all_topics_{cls}",
on_change=make_select_all_topics_cb(cls),
)
# Individual topic checkboxes — always visible
topic_cols = st.columns(min(4, len(topics)))
for i, topic in enumerate(topics):
with topic_cols[i % len(topic_cols)]:
n = len(data[cls][topic])
label = topic if len(topic) <= 40 else topic[:38] + "…"
st.checkbox(
f"{label} ({n})",
key=f"topic_cb_{cls}_{topic}",
on_change=make_topic_cb(cls),
)
st.divider()
# ── Build card deck from current checkbox state ───────────────────────────
all_cards = [
{**card, "_class": cls, "_topic": topic}
for cls in all_classes
if st.session_state.get(f"class_cb_{cls}", True)
for topic in data[cls]
if st.session_state.get(f"topic_cb_{cls}_{topic}", True)
for card in data[cls][topic]
]
if st.session_state.show_setup:
total_selected_topics = sum(
1 for cls in all_classes
if st.session_state.get(f"class_cb_{cls}", True)
for t in data[cls]
if st.session_state.get(f"topic_cb_{cls}_{t}", True)
)
selected_classes = [c for c in all_classes if st.session_state.get(f"class_cb_{c}", True)]
st.caption(f"📌 {len(selected_classes)} class(es) · {total_selected_topics} topic(s) · {len(all_cards)} card(s) selected")
if not all_cards:
st.warning("No cards found for this selection.")
else:
if st.button("▶️ Start / Restart Session", type="primary"):
st.session_state["_last_shuffle"] = shuffle
deck = all_cards.copy()
if shuffle: random.shuffle(deck)
ss.update({"deck": deck, "index": 0, "show_answer": False,
"correct": 0, "incorrect": 0})
st.session_state.show_setup = False
st.rerun()
if ss.get("deck"):
deck = ss["deck"]
idx = ss["index"]
total = len(deck)
if idx >= total:
st.balloons()
st.markdown("## 🎉 Session Complete!")
c = ss.get("correct", 0)
w = ss.get("incorrect", 0)
pct = round(c / (c+w) * 100) if (c+w) else 0
st.markdown(f"**Score: {c}/{c+w} correct ({pct}%)**")
if pct >= 80: st.success("Great job! You're mastering this material! 🌟")
elif pct >= 60: st.info("Good effort! Keep practicing the ones you missed.")
else: st.warning("Keep going! Repetition is key to learning.")
if st.button("🔄 Study Again"):
ss.clear()
st.session_state.show_setup = True
st.rerun()
missed_cards = ss.get("missed", [])
if missed_cards:
st.markdown("---")
st.markdown(f"### 🔁 You missed **{len(missed_cards)}** card(s)")
st.caption("Want to drill just those cards before moving on?")
if st.button(f"🔁 Retry {len(missed_cards)} Missed Card(s)", type="primary"):
retry_deck = missed_cards.copy()
if st.session_state.get("_last_shuffle", True):
random.shuffle(retry_deck)
ss.clear()
ss.update({"deck": retry_deck, "index": 0, "show_answer": False,
"correct": 0, "incorrect": 0, "is_retry": True})
st.session_state.show_setup = False
st.rerun()
else:
card = deck[idx]
if ss.get("is_retry"):
st.info("🔁 **Retry Mode** — drilling your missed cards only")
st.markdown(f"**Card {idx+1} of {total}** — {card.get('_class','')} › *{card.get('_topic','')}*")
st.markdown(f"""
<div class="progress-bar">
<div class="progress-fill" style="width:{idx/total*100:.1f}%"></div>
</div>""", unsafe_allow_html=True)
rc1, rc2, _ = st.columns([1, 1, 4])
with rc1: st.markdown(f'✅ **{ss.get("correct",0)}** correct')
with rc2: st.markdown(f'❌ **{ss.get("incorrect",0)}** incorrect')
st.markdown("<br>", unsafe_allow_html=True)
question_html = md_lib.markdown(card["question"])
st.markdown(f'<div class="card-front">{question_html}</div>',
unsafe_allow_html=True, width='stretch')
if not ss.get("show_answer"):
if st.button("Show Answer", type="primary", use_container_width=True):
ss["show_answer"] = True; st.rerun()
else:
img_html = ""
if card.get("answer_image"):
b64 = img_to_b64(card["answer_image"])
if b64: img_html = f'<img src="{b64}" style="max-width:100%;max-height:600px;border-radius:10px;" />'
with st.container(border=True):
st.markdown(
'<div style="background:linear-gradient(135deg,#f093fb,#f5576c);'
'border-radius:16px;padding:1rem;color:#fff;margin-bottom:1rem">',
unsafe_allow_html=True
)
if card.get("answer_text"):
st.markdown(card["answer_text"], unsafe_allow_html=True)
if img_html:
st.markdown(img_html, unsafe_allow_html=True)
st.markdown('</div>', unsafe_allow_html=True)
st.markdown("**How did you do?**")
cy, cn = st.columns(2)
with cy:
if st.button("✅ Got it!", type="primary", use_container_width=True):
ss["correct"] = ss.get("correct", 0) + 1
ss["index"] = idx + 1; ss["show_answer"] = False; st.rerun()
with cn:
if st.button("❌ Missed it", use_container_width=True):
ss["incorrect"] = ss.get("incorrect", 0) + 1
ss.setdefault("missed", []).append(card)
ss["index"] = idx + 1; ss["show_answer"] = False; st.rerun()
st.markdown("---")
if st.button("⏭️ Skip (don't count)"):
ss["index"] = idx + 1; ss["show_answer"] = False; st.rerun()