-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproject.py
553 lines (465 loc) · 16 KB
/
project.py
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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
import os
import csv
import time
import pandas as pd
import streamlit as st
from datetime import date
from user import User
from flashcard import Flashcard
from constants import (
USER_DATA_FILE,
DECKS_DATA_FILE,
INCORRECT_ANS_DELAY,
CORRECT_ANS_DELAY,
)
# INTIAL SETUP
def setup_page():
st.set_page_config(
page_title="CS50P PROJECT",
page_icon="🎩",
)
st.title("CS50P Flashcards Project")
def main():
# SETUP
setup_page()
if not check_decks_data_exist():
setup_decks_data()
if not check_user_data_exist():
setup_user_data()
# MAIN
else:
settings_popover()
st.markdown("---")
st.header("CONFIG SECTION")
col1, col2 = st.columns(2)
decks = list_deck()
decks_name = list_deck_name(decks)
with col1:
tab1, tab2, tab3, tab4 = st.tabs(["ADD", "REMOVE", "DOWNLOAD", "UPLOAD"])
with tab1:
add_section()
with tab2:
with st.container(border=True):
filepath_to_remove = choose_deck_name(decks_name, "deck_to_remove")
remove_section(filepath_to_remove)
with tab3:
with st.container(border=True):
filepath_to_download = choose_deck_name(decks_name, "deck_to_download")
download_deck(filepath_to_download)
with tab4:
with st.container(border=True):
upload_deck()
with col2:
lastest_decks_df = pd.DataFrame(decks[-10:])
lastest_decks_df = lastest_decks_df.rename(
columns={"deck_name": "Deck name", "created_date": "Created date"}
)
lastest_decks_df = lastest_decks_df.reset_index(drop=True)
st.table(lastest_decks_df)
st.markdown("---")
st.header("LEARNING SECTION")
with st.container(border=True):
filepath_to_learn = choose_deck_name(decks_name, "deck_to_learn")
if filepath_to_learn:
learn_deck(filepath_to_learn)
def settings_popover() -> None:
with st.popover("SETTINGS"):
tab1, tab2 = st.tabs(["ABOUT", "USER"])
with tab1:
st.markdown(
"This is a CS50P project that allows you to create and manage flashcards. "
"You can create new decks, add cards, remove and review them interactively. "
"[GitHub](https://github.com/haolamnm/CS50P-project). "
"[LinkedIn](https://www.linkedin.com/in/haolamnm/). "
)
with tab2:
st.write("Edit user information")
update_user_data()
USER_DATA_DF = pd.read_csv(USER_DATA_FILE)
st.table(USER_DATA_DF)
def update_user_data() -> None:
"""
Allows user to update user's information
Return:
None
"""
with open(USER_DATA_FILE, "r", newline="") as file:
reader = csv.DictReader(file)
for user in reader:
current_user = {
"username": user["username"],
"name": user["name"],
"email": user["email"],
}
new_username = st.text_input(
label="New username",
value=current_user["username"],
key="new_username",
placeholder=f"{current_user["username"]}",
)
new_name = st.text_input(
label="New name",
value=current_user["name"],
key="new_name",
placeholder=f"{current_user["name"]}",
)
new_email = st.text_input(
label="New email",
value=current_user["email"],
key="new_email",
placeholder=f"{current_user["email"]}",
)
if st.button("Update"):
try:
new_user = User(new_username, new_name, new_email)
new_user.save()
st.success("Update user information successfully!")
time.sleep(0.5)
st.rerun()
except ValueError as E:
st.error(E)
def check_user_data_exist() -> bool:
"""
Checks if the user_data.csv file exist.
Return:
True if the file exist, False otherwise.
"""
try:
with open(USER_DATA_FILE, "r", newline=""):
return True
except FileNotFoundError:
return False
def check_decks_data_exist() -> bool:
"""
Checks if the decks_data.csv file exist.
Return:
True if the file exist, False otherwise.
"""
try:
with open(DECKS_DATA_FILE, "r", newline=""):
return True
except FileNotFoundError:
return False
def check_deck_name_exist(filename: str) -> bool:
"""
Checks if a deck with the given filename exist in the decks_data.csv file.
Args:
filename: The filename to check.
Return:
True if a deck with the given filename exists, False otherwise.
"""
with open(DECKS_DATA_FILE, "r", newline="") as file:
reader = csv.DictReader(file)
for row in reader:
if row["deck_name"].strip() == filename:
return True
return False
def setup_user_data() -> None:
"""
Creates a user registration form using Streamlit and save it to user_data.csv upon submission.
Return:
None
"""
with st.form("REGISTRATION"):
name = st.text_input(
label="Name:",
value="",
key="name",
placeholder="Lam Chi Hao",
)
username = st.text_input(
label="Username:",
value="",
key="username",
placeholder="haolamm",
)
email = st.text_input(
label="Email:",
value="",
key="email",
placeholder="[email protected]",
)
submit_button = st.form_submit_button("Submit")
if submit_button:
try:
user = User(username, name, email)
user.save()
st.success("User data saved successfully!")
time.sleep(0.5)
st.rerun()
except ValueError as E:
st.error(E)
def setup_decks_data() -> None:
"""
Creates decks_data.csv file with needed entries
Return:
None
"""
with open(DECKS_DATA_FILE, "w", newline="") as file:
writer = csv.DictWriter(file, fieldnames=["deck_name", "created_date"])
writer.writeheader()
writer.writerow(
{
"deck_name": "decks_data",
"created_date": date.today(),
}
)
writer.writerow(
{
"deck_name": "user_data",
"created_date": date.today(),
}
)
def add_section() -> None:
"""
Creates a card addition form using Streamlit and saves a new card upon submission.
This function allows users to enter deck name, card front and back content.
If the deck doesn't exist, a new deck entry is created in decks_data.csv.
Return:
None
"""
with st.form("ADD CARD"):
filename = st.text_input(
label="Deck name:",
value="",
key="filename",
placeholder="capitals",
max_chars=30,
)
front = st.text_input(
label="Front:",
value="",
key="front",
placeholder="vietnam",
)
back = st.text_input(
label="Back:",
value="",
key="back",
placeholder="hanoi"
)
submit_button = st.form_submit_button("Add")
if submit_button:
try:
card = Flashcard(front, back)
card.save(filename)
if not check_deck_name_exist(filename):
with open(DECKS_DATA_FILE, "a", newline="") as file:
writer = csv.DictWriter(file, fieldnames=["deck_name", "created_date"])
writer.writerow(
{"deck_name": filename, "created_date": date.today()}
)
st.success("Card saved successfully!")
time.sleep(0.5)
st.rerun()
except ValueError as E:
st.error(E)
def remove_section(filepath: str) -> None:
"""
Removes a selected card or deck.
Args:
filepath: The .csv filepath leads to selected deck.
Return:
None
"""
cards_name = list_card_name(filepath)
if st.button("Remove deck"):
filename = filepath.removesuffix(".csv")
temp_decks = []
with open(DECKS_DATA_FILE, "r", newline="") as file:
reader = csv.DictReader(file)
for deck in reader:
if deck["deck_name"].strip() != filename:
temp_decks.append(deck)
with open(DECKS_DATA_FILE, "w", newline="") as file:
writer = csv.DictWriter(file, fieldnames=["deck_name", "created_date"])
writer.writeheader()
writer.writerows(temp_decks)
os.remove(filepath)
st.success(f"Deck {filename} removed successfully")
time.sleep(0.5)
st.rerun()
if cards_name:
rm_card = st.selectbox(
label="Choose card:",
options=cards_name,
key="cardname_toremove",
)
if st.button("Remove card"):
temp_cards = []
with open(filepath, "r", newline="") as file:
reader = csv.DictReader(file)
for card in reader:
card_info = f"{card['front']} - {card['back']}"
if card_info != rm_card:
temp_cards.append(card)
with open(filepath, "w", newline="") as file:
writer = csv.DictWriter(file, fieldnames=["front", "back"])
writer.writeheader()
writer.writerows(temp_cards)
st.success(f"Card {rm_card} removed successfully")
time.sleep(0.5)
st.rerun()
else:
st.warning("Empty deck")
def list_deck() -> list[dict]:
"""
Lists all decks information excluding user_data.csv and decks_data.csv.
Return:
A list of decks
"""
decks = []
with open(DECKS_DATA_FILE, "r", newline="") as file:
reader = csv.DictReader(file)
for deck in reader:
if deck["deck_name"].strip() == USER_DATA_FILE.removesuffix(".csv") or deck[
"deck_name"
].strip() == DECKS_DATA_FILE.removesuffix(".csv"):
continue
else:
decks.append(deck)
return decks
def list_deck_name(decks: list[dict]) -> list[str]:
"""
Extracts deck name from a list of decks.
Args:
decks: A list of decks.
Return:
A list of deck names.
"""
decks_name = []
for deck in decks:
decks_name.append(deck["deck_name"])
return decks_name
def list_card_name(filepath: str) -> list[str]:
"""
Lists card names from a given deck
Args:
filepath: The .csv filepath leads to selected deck.
Return:
A list of card names of selected deck.
"""
cards_name = []
try:
with open(filepath, "r", newline="") as file:
reader = csv.DictReader(file)
for card in reader:
cards_name.append(f"{card["front"]} - {card["back"]}")
except FileNotFoundError:
st.warning("No deck to remove")
return cards_name
def choose_deck_name(decks_name: list[str], key: str) -> str:
"""
Allows user to choose a deck from a list of available decks
Args:
decks_name: A list of deck names.
key: A unique key for Steamlit select box.
Return:
The filepath of the selected deck.
"""
filename = st.selectbox(
label="Choose deck:",
options=decks_name,
key=key,
)
filepath = f"{filename}.csv"
return filepath
def learn_deck(filepath: str) -> None:
"""
Learning session for a selected deck.
Present flashcard one by one.
Keeps track of the score.
Args:
filepath: The .csv filepath that leads to selected deck.
Return:
None
"""
if "current_card" not in st.session_state:
st.session_state.current_card = 0
if (
"current_filepath" not in st.session_state
or st.session_state.current_filepath != filepath
):
st.session_state.current_card = 0
st.session_state.current_filepath = filepath
try:
with open(filepath, "r", newline="") as file:
deck = list(csv.DictReader(file))
total_cards = len(deck)
if total_cards == 0:
raise ValueError("Empty deck")
current_card = deck[st.session_state.current_card]
with st.form(f"{st.session_state.current_card}"):
answer = st.text_input(
label=f"{current_card["front"]}",
value="",
placeholder="answer here ...",
)
submit_button = st.form_submit_button("Submit")
if submit_button:
answer = answer.strip().lower()
if answer == current_card["back"]:
st.success("Correct")
time.sleep(CORRECT_ANS_DELAY)
else:
st.error(f"Incorrect, answer is {current_card["back"]}")
time.sleep(INCORRECT_ANS_DELAY)
if st.session_state.current_card < total_cards - 1:
st.session_state.current_card += 1
st.rerun()
if st.session_state.current_card + 1 == total_cards:
st.warning("Final card in deck, press Reset to start over.")
if st.button("Reset"):
st.session_state.current_card = 0
st.rerun()
except FileNotFoundError:
st.warning("No deck to learn")
except ValueError as E:
st.warning(E)
def download_deck(filepath: str) -> None:
"""
Allows users to download their decks
Args:
filepath: The .csv filepath that leads to selected deck.
Return:
None
"""
try:
with open(filepath, "r", newline="") as file:
download_button_clicked = st.download_button(
label="Download",
data=file,
file_name=filepath,
mime="text/csv",
)
if download_button_clicked:
st.success("Download successfully")
time.sleep(1.5)
st.rerun()
except FileNotFoundError:
st.warning("No deck to download")
def upload_deck() -> None:
"""
Allows user to upload their card
Return:
None
"""
uploaded_file = st.file_uploader("Upload your deck")
if uploaded_file:
filename = os.path.splitext(uploaded_file.name)[0]
uploaded_file_df = pd.read_csv(uploaded_file)
if not check_deck_name_exist(filename):
filepath = f"{filename}.csv"
uploaded_file_df.to_csv(filepath, index=False)
with open(DECKS_DATA_FILE, "a", newline="") as file:
writer = csv.DictWriter(file, fieldnames=["deck_name", "created_date"])
writer.writerow(
{"deck_name": filename, "created_date": date.today()}
)
st.success("Upload successfully")
time.sleep(1.5)
st.rerun()
else:
st.warning("Invalid deck name")
if __name__ == "__main__":
main()