-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdata_engine.py
More file actions
814 lines (704 loc) · 29 KB
/
data_engine.py
File metadata and controls
814 lines (704 loc) · 29 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
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
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
import json
import os
import csv
import datetime
import html
import shutil
import glob
import zipfile
import sqlite3
import re
import tempfile
import sys
# --- PATH CONFIGURATION ---
# 1. Detect if we are running as a Flatpak or standard Linux install
if os.environ.get("FLATPAK_ID") or os.environ.get("XDG_DATA_HOME"):
# PRODUCTION MODE
# Uses standard Linux data paths (e.g. ~/.var/app/io.github.dagaza.FlipStack/data/flipstack)
base_data = os.environ.get("XDG_DATA_HOME", os.path.expanduser("~/.local/share"))
BASE_DIR = os.path.join(base_data, "flipstack")
else:
# DEV / GITHUB MODE
# Uses a local folder 'user_data' inside your project so you don't pollute your hard drive
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
BASE_DIR = os.path.join(PROJECT_ROOT, "user_data")
# 2. Define Sub-folders based on that Base Directory
DATA_DIR = os.path.join(BASE_DIR, "decks") # <--- JSON files go here
ASSETS_DIR = os.path.join(BASE_DIR, "assets") # <--- User images/audio go here
BACKUP_DIR = os.path.join(BASE_DIR, "backups")
# 3. Create them if they don't exist
for d in [BASE_DIR, DATA_DIR, ASSETS_DIR, BACKUP_DIR]:
os.makedirs(d, exist_ok=True)
DATA_DIR = os.path.join(BASE_DIR, "decks")
ASSETS_DIR = os.path.join(BASE_DIR, "assets")
BACKUP_DIR = os.path.join(BASE_DIR, "backups")
STATS_FILE = os.path.join(BASE_DIR, "stats.json")
SETTINGS_FILE = os.path.join(BASE_DIR, "settings.json")
HISTORY_FILE = os.path.join(BASE_DIR, "history.json")
CATEGORIES_FILE = os.path.join(BASE_DIR, "categories.json")
DECK_META_FILE = os.path.join(BASE_DIR, "deck_meta.json")
COLORS_FILE = os.path.join(BASE_DIR, "deck_colors.json")
# Ensure directories exist
for d in [BASE_DIR, DATA_DIR, ASSETS_DIR, BACKUP_DIR]:
if not os.path.exists(d):
os.makedirs(d)
# --- Settings ---
def load_settings():
default = {"sound_enabled": True}
if not os.path.exists(SETTINGS_FILE): return default
try:
with open(SETTINGS_FILE, "r") as f:
return {**default, **json.load(f)}
except: return default
def save_settings(settings):
with open(SETTINGS_FILE, "w") as f:
json.dump(settings, f)
# --- Categories ---
def get_categories():
if not os.path.exists(CATEGORIES_FILE):
return ["Uncategorized"]
try:
with open(CATEGORIES_FILE, "r") as f:
cats = json.load(f)
if "Uncategorized" not in cats:
cats.insert(0, "Uncategorized")
return cats
except:
return ["Uncategorized"]
def add_category(name):
cats = get_categories()
if name not in cats:
cats.append(name)
with open(CATEGORIES_FILE, "w") as f:
json.dump(cats, f)
def delete_category(name):
if name == "Uncategorized": return
cats = get_categories()
if name in cats:
cats.remove(name)
with open(CATEGORIES_FILE, "w") as f:
json.dump(cats, f)
def get_deck_category(filename):
meta = {}
if os.path.exists(DECK_META_FILE):
try:
with open(DECK_META_FILE, "r") as f:
meta = json.load(f)
except:
pass
return meta.get(filename, "Uncategorized")
def set_deck_category(filename, category):
meta = {}
if os.path.exists(DECK_META_FILE):
try:
with open(DECK_META_FILE, "r") as f:
meta = json.load(f)
except:
pass
meta[filename] = category
with open(DECK_META_FILE, "w") as f:
json.dump(meta, f)
# --- Global Search & Tags ---
def search_global(query):
"""
Returns a dictionary with structured search results:
{
'decks': [filename, ...],
'cards': [{'front':..., 'back':..., 'deck':...}, ...],
'tags': [tag_name, ...]
}
"""
results = {'decks': [], 'cards': [], 'tags': []}
if not query: return results
query = query.lower().strip()
files = get_all_decks()
# Track unique tags to avoid duplicates
found_tags = set()
for fname in files:
# 1. Search Deck Names
display_name = fname.replace(".json", "").replace("_", " ")
if query in display_name.lower():
results['decks'].append(fname)
# 2. Search Cards & Tags
cards = load_deck(fname)
for card in cards:
# Check Content
f_text = card.get("front", "").lower()
b_text = card.get("back", "").lower()
if query in f_text or query in b_text:
results['cards'].append({
"deck_name": display_name,
"filename": fname,
"front": card["front"],
"back": card["back"],
"id": card["id"]
})
# Check Tags
for tag in card.get("tags", []):
if query in tag.lower():
found_tags.add(tag)
results['tags'] = sorted(list(found_tags))
return results
def get_cards_by_tag(tag):
tag = tag.lower().strip()
files = get_all_decks()
virtual_deck = []
for fname in files:
cards = load_deck(fname)
for card in cards:
if tag in [t.lower() for t in card.get("tags", [])]:
virtual_deck.append(card)
return virtual_deck
# --- Asset Handling ---
def save_asset(source_path):
"""
Copies a user-selected file to the internal ASSETS_DIR.
1. Preserves the original filename if possible.
2. If a file with that name exists, appends a counter (image.png -> image_1.png).
3. Returns the FINAL filename used.
"""
if not source_path or not os.path.exists(source_path):
return None
# 1. Get the original filename (e.g., "my_photo.jpg")
original_filename = os.path.basename(source_path)
name_part, extension = os.path.splitext(original_filename)
# 2. Basic cleanup (remove characters that break Linux filesystems)
# Allows letters, numbers, spaces, hyphens, underscores
safe_name = re.sub(r'[^\w\s-]', '', name_part).strip().replace(' ', '_')
if not safe_name: safe_name = "asset" # Fallback if name was only special chars
final_filename = f"{safe_name}{extension}"
destination_path = os.path.join(ASSETS_DIR, final_filename)
# 3. Collision Detection (The "Smart" part)
counter = 1
while os.path.exists(destination_path):
# Check if it's actually the exact same file (optimization)
# If the file in the folder is identical to the new one, we can just reuse it!
# (This prevents duplicating "icon.png" 50 times if the user re-imports it)
try:
if file_is_identical(source_path, destination_path):
return final_filename
except:
pass # If comparison fails, just rename to be safe
# If different, try new name: "my_photo_1.jpg"
final_filename = f"{safe_name}_{counter}{extension}"
destination_path = os.path.join(ASSETS_DIR, final_filename)
counter += 1
# 4. Perform the Copy
try:
shutil.copy2(source_path, destination_path)
return final_filename
except Exception as e:
print(f"Error copying asset: {e}")
return None
def file_is_identical(file1, file2):
"""Helper to check if two files are effectively the same content."""
# Simple check: same size?
if os.path.getsize(file1) != os.path.getsize(file2):
return False
# (Optional) You could do a hash check here for 100% certainty,
# but size is usually a "good enough" proxy for UI speed.
return True
def get_asset_path(filename):
if not filename: return None
return os.path.join(ASSETS_DIR, filename)
# --- Deck Logic ---
def get_all_decks():
if not os.path.exists(DATA_DIR): return []
return [f for f in os.listdir(DATA_DIR) if f.endswith(".json")]
def load_deck(filename):
path = os.path.join(DATA_DIR, filename)
try:
with open(path, "r") as f:
return json.load(f)
except:
return []
def save_deck(filename, cards):
with open(os.path.join(DATA_DIR, filename), "w") as f:
json.dump(cards, f, indent=2)
def create_empty_deck(name, category="Uncategorized"):
safe = "".join([c for c in name if c.isalnum() or c in (' ', '_')]).strip()
fname = f"{safe.lower().replace(' ', '_')}.json"
save_deck(fname, [])
set_deck_category(fname, category)
return fname
def delete_deck(filename):
path = os.path.join(DATA_DIR, filename)
if os.path.exists(path):
os.remove(path)
if os.path.exists(HISTORY_FILE):
try:
with open(HISTORY_FILE, "r") as f:
history = json.load(f)
new_h = [e for e in history if e.get("deck") != filename]
with open(HISTORY_FILE, "w") as f:
json.dump(new_h, f, indent=2)
except:
pass
def get_deck_mastery(filename):
cards = load_deck(filename)
if not cards: return 0.0
learned = len([c for c in cards if c.get("bucket", 0) > 0 and not c.get("suspended", False)])
return learned / len(cards)
# --- Card Logic ---
def add_card_to_deck(filename, front, back, image_path=None, audio_path=None, tags=None, hint=None):
cards = load_deck(filename)
img_file = save_asset(image_path) if image_path else None
aud_file = save_asset(audio_path) if audio_path else None
cards.append({
"id": str(datetime.datetime.now().timestamp()),
"front": front, "back": back,
"image": img_file,
"audio": aud_file,
"tags": tags or [],
"hint": hint or "",
"bucket": 0, "next_review": None,
"miss_streak": 0,
"suspended": False
})
save_deck(filename, cards)
def edit_card(filename, card_id, f_txt, b_txt, img_path=None, aud_path=None, tags=None, suspended=False, hint=None):
cards = load_deck(filename)
for c in cards:
if c["id"] == card_id:
c["front"] = f_txt
c["back"] = b_txt
if img_path: c["image"] = save_asset(img_path)
if img_path:
if os.sep in img_path: c["image"] = save_asset(img_path)
else: c["image"] = img_path # Keep existing filename
else:
c["image"] = None # Clear it
if aud_path:
if os.sep in aud_path: c["audio"] = save_asset(aud_path)
else: c["audio"] = aud_path
else:
c["audio"] = None
if tags is not None: c["tags"] = tags
c["hint"] = hint or ""
c["suspended"] = suspended
if not suspended: c["miss_streak"] = 0
break
save_deck(filename, cards)
def delete_card(filename, cid):
cards = load_deck(filename)
new_c = [c for c in cards if c["id"] != cid]
save_deck(filename, new_c)
# --- Progress ---
# UPDATED: Added hint_used logic
def log_review(deck, rating, sid=None, hint_used=False):
entry = {
"timestamp": datetime.datetime.now().isoformat(),
"deck": deck,
"rating": rating,
"session_id": sid,
"hint_used": hint_used
}
hist = []
if os.path.exists(HISTORY_FILE):
try:
with open(HISTORY_FILE, "r") as f:
hist = json.load(f)
except:
pass
hist.append(entry)
if len(hist) > 10000:
hist = hist[-10000:]
with open(HISTORY_FILE, "w") as f:
json.dump(hist, f, indent=2)
f.flush()
os.fsync(f.fileno())
def get_deck_history(filename):
if not os.path.exists(HISTORY_FILE): return []
try:
with open(HISTORY_FILE, "r") as f:
data = json.load(f)
return [d for d in data if d["deck"] == filename]
except:
return []
def get_heatmap_data():
if not os.path.exists(HISTORY_FILE): return {}
try:
with open(HISTORY_FILE, "r") as f:
history = json.load(f)
data = {}
for h in history:
ts = h.get("timestamp", h.get("date"))
if not ts: continue
day = ts.split("T")[0]
data[day] = data.get(day, 0) + 1
return data
except:
return {}
# UPDATED: Added hint_used param
def update_card_progress(filename, card_id, rating, session_id=None, hint_used=False):
log_review(filename, rating, session_id, hint_used)
cards = load_deck(filename)
leech_alert = False
for c in cards:
if c["id"] == card_id:
if rating == 1:
c["miss_streak"] = c.get("miss_streak", 0) + 1
if c["miss_streak"] >= 8:
c["suspended"] = True
leech_alert = True
else:
c["miss_streak"] = 0
if rating == 3: c["bucket"] = c.get("bucket", 0) + 1
elif rating == 1: c["bucket"] = 0
if rating == 2 and c.get("bucket", 0) == 0: c["bucket"] = 1
days = 0 if c.get("bucket", 0) == 0 else 2 ** c["bucket"]
c["next_review"] = (datetime.date.today() + datetime.timedelta(days=days)).isoformat()
break
save_deck(filename, cards)
update_streak()
return leech_alert
def create_backup():
ts = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
zip_name = os.path.join(BACKUP_DIR, f"flipstack_backup_{ts}")
try:
shutil.make_archive(zip_name, 'zip', root_dir='.', base_dir=DATA_DIR)
return True
except:
return False
# --- STATISTICS ENGINE ---
def log_stats(deck_name, rating):
"""
Logs a review event to stats.json.
Rating: 3=Good (Correct), 2=Hard (Correct), 1=Miss (Incorrect)
"""
stats_path = os.path.join(DATA_DIR, 'stats.json')
today = datetime.now().strftime("%Y-%m-%d")
data = {}
if os.path.exists(stats_path):
try:
with open(stats_path, 'r') as f:
data = json.load(f)
except: pass
# Initialize structure: data[deck_name][date]
if deck_name not in data: data[deck_name] = {}
if today not in data[deck_name]:
data[deck_name][today] = {"correct": 0, "total": 0}
# Update counts
data[deck_name][today]["total"] += 1
# We count Good (3) and Hard (2) as "Correct" for accuracy tracking
if rating >= 2:
data[deck_name][today]["correct"] += 1
try:
with open(stats_path, 'w') as f:
json.dump(data, f, indent=2)
except Exception as e:
print(f"Failed to save stats: {e}")
def get_stats_history(deck_name):
"""Returns the last 7 days of stats for the graph."""
stats_path = os.path.join(DATA_DIR, 'stats.json')
if not os.path.exists(stats_path): return {}
try:
with open(stats_path, 'r') as f:
full_data = json.load(f)
return full_data.get(deck_name, {})
except: return {}
# --- Utils ---
def load_stats():
if not os.path.exists(STATS_FILE): return {"streak": 0, "last_study_date": None}
try:
with open(STATS_FILE, "r") as f: return json.load(f)
except: return {"streak": 0, "last_study_date": None}
def save_stats(stats):
with open(STATS_FILE, "w") as f: json.dump(stats, f)
def update_streak():
stats = load_stats()
today = datetime.date.today().isoformat()
if stats.get("last_study_date") == today: return stats["streak"]
if stats.get("last_study_date"):
delta = (datetime.date.today() - datetime.date.fromisoformat(stats["last_study_date"])).days
if delta == 1: stats["streak"] += 1
else: stats["streak"] = 1
else: stats["streak"] = 1
stats["last_study_date"] = today
save_stats(stats)
return stats["streak"]
# --- MARKDOWN PARSER (FINAL ROBUST VERSION) ---
def format_text(text):
if not text: return ""
# 1. Escape HTML first (Critical for Pango)
text = html.escape(text)
# 2. Helper function to process code blocks
def code_block_replacer(match):
content = match.group(1)
if re.match(r'^\w+\s*\n', content):
parts = content.split('\n', 1)
if len(parts) > 1:
content = parts[1] # Keep everything after the first line
return f'\n<span font_family="monospace" background="#303030" foreground="#eeeeee" size="small"> {content} </span>\n'
# 3. Apply the Code Block Regex
text = re.sub(r'```([\s\S]*?)```', code_block_replacer, text)
# 4. Inline Code (`...`)
text = re.sub(
r'`([^`\n]+)`',
r'<span font_family="monospace" background="#3d3d3d" foreground="#f2f2f2"> \1 </span>',
text
)
# 5. Bold (**...**)
text = re.sub(r'\*\*(.*?)\*\*', r'<b>\1</b>', text)
# 6. Italic (*...*)
text = re.sub(r'\*(?!\*)(.*?)\*', r'<i>\1</i>', text)
# 7. Strikethrough (~~...~~)
text = re.sub(r'~~(.*?)~~', r'<s>\1</s>', text)
# 8. Headers (# ...)
text = re.sub(r'^# (.*?)$', r'<span size="x-large" weight="bold">\1</span>', text, flags=re.MULTILINE)
text = re.sub(r'^## (.*?)$', r'<span size="large" weight="bold">\1</span>', text, flags=re.MULTILINE)
return text
# --- IMPORTERS ---
def import_csv(path, name):
cards = []
if not path or not os.path.exists(path): return False
encodings = ['utf-8-sig', 'utf-8', 'latin-1']
delimiters = [',', ';', '\t']
for enc in encodings:
try:
with open(path, "r", encoding=enc) as f:
lines = f.readlines()
if not lines: continue
first = lines[0]
best_delim = ','
for d in delimiters:
if d in first:
best_delim = d
break
parsed_cards = []
for line in lines:
line = line.strip()
if not line: continue
parts = line.split(best_delim)
if len(parts) >= 2:
front = parts[0].strip().strip('"')
back = parts[1].strip().strip('"')
if front and back:
parsed_cards.append({
"id": str(datetime.datetime.now().timestamp())+str(len(parsed_cards)),
"front": front, "back": back,
"bucket": 0, "suspended": False,
"hint": ""
})
if parsed_cards:
cards = parsed_cards
break
except Exception:
continue
if cards:
fname = create_empty_deck(name)
save_deck(fname, cards)
return True
return False
def import_anki_apkg(path, name):
if not path or not os.path.exists(path): return False
try:
with tempfile.TemporaryDirectory() as temp_dir:
with zipfile.ZipFile(path, 'r') as z:
z.extractall(temp_dir)
media_map_file = os.path.join(temp_dir, "media")
if os.path.exists(media_map_file):
try:
with open(media_map_file, "r") as f:
media_map = json.load(f)
for k, v in media_map.items():
src = os.path.join(temp_dir, k)
dst = os.path.join(ASSETS_DIR, v)
if os.path.exists(src): shutil.copy(src, dst)
except: pass
db_path = os.path.join(temp_dir, "collection.anki2")
if not os.path.exists(db_path): return False
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
cursor.execute("SELECT flds FROM notes")
rows = cursor.fetchall()
cards = []
for row in rows:
if not row or not row[0]: continue
fields = row[0].split('\x1f')
if len(fields) >= 2:
front_raw = fields[0]
back_raw = fields[1]
img_match = re.search(r'<img src="([^"]+)"', front_raw + back_raw)
image_file = img_match.group(1) if img_match else None
# OLD LINE:
# clean_f = re.sub(r'<[^>]+>', '', front_raw).strip()
# clean_b = re.sub(r'<[^>]+>', '', back_raw).strip()
# NEW FIX: Unescape HTML entities (converts to real space)
clean_f = html.unescape(re.sub(r'<[^>]+>', '', front_raw)).strip()
clean_b = html.unescape(re.sub(r'<[^>]+>', '', back_raw)).strip()
if clean_f and clean_b:
cards.append({
"id": str(datetime.datetime.now().timestamp())+str(len(cards)),
"front": clean_f, "back": clean_b, "image": image_file,
"bucket": 0, "suspended": False, "next_review": None, "hint": ""
})
conn.close()
if cards:
fname = create_empty_deck(name)
save_deck(fname, cards)
return True
except Exception as e:
print(f"Anki Import Error: {e}")
return False
return False
def export_deck_to_csv(fname, path):
cards = load_deck(fname)
try:
with open(path, 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
for c in cards: writer.writerow([c.get('front',''), c.get('back','')])
return True
except: return False
def export_deck_to_json(fname, path):
try:
shutil.copy(os.path.join(DATA_DIR, fname), path)
return True
except: return False
def rename_deck(old_filename, new_display_name):
"""
Renames a deck file and updates all references in history and meta files.
Returns the new filename.
"""
# 1. Generate new safe filename
safe = "".join([c for c in new_display_name if c.isalnum() or c in (' ', '_')]).strip()
new_filename = f"{safe.lower().replace(' ', '_')}.json"
if new_filename == old_filename:
return old_filename
old_path = os.path.join(DATA_DIR, old_filename)
new_path = os.path.join(DATA_DIR, new_filename)
if os.path.exists(new_path):
return None # Prevent overwriting existing deck
try:
# 2. Rename the actual file
os.rename(old_path, new_path)
# 3. Update Category Meta (deck_meta.json)
if os.path.exists(DECK_META_FILE):
with open(DECK_META_FILE, "r") as f:
meta = json.load(f)
if old_filename in meta:
meta[new_filename] = meta.pop(old_filename)
with open(DECK_META_FILE, "w") as f:
json.dump(meta, f)
# 4. Update History (history.json)
if os.path.exists(HISTORY_FILE):
with open(HISTORY_FILE, "r") as f:
history = json.load(f)
changed = False
for entry in history:
if entry.get("deck") == old_filename:
entry["deck"] = new_filename
changed = True
if changed:
with open(HISTORY_FILE, "w") as f:
json.dump(history, f, indent=2)
return new_filename
except Exception as e:
print(f"Rename failed: {e}")
return None
def rename_category(old_name, new_name):
"""
Renames a category in the list and updates all decks assigned to it.
"""
if old_name == "Uncategorized": return False # Can't rename default
# 1. Update Categories List
cats = get_categories()
if old_name in cats:
idx = cats.index(old_name)
cats[idx] = new_name
with open(CATEGORIES_FILE, "w") as f:
json.dump(cats, f)
# 2. Update references in Deck Meta
if os.path.exists(DECK_META_FILE):
try:
with open(DECK_META_FILE, "r") as f:
meta = json.load(f)
changed = False
for filename, cat in meta.items():
if cat == old_name:
meta[filename] = new_name
changed = True
if changed:
with open(DECK_META_FILE, "w") as f:
json.dump(meta, f)
return True
except:
return False
return True
def create_tutorial_deck():
"""Generates a comprehensive tutorial deck for first-time users."""
# 1. Ensure the Category exists
add_category("FlipStack Tutorial")
# 2. Create the empty deck and CAPTURE the sanitized filename
# This function returns "welcome_to_flipstack.json"
deck_name = create_empty_deck("Welcome to FlipStack", "FlipStack Tutorial")
# 3. Check if we actually need to populate it
# (If cards exist, we assume it's done to avoid duplicates)
existing_cards = load_deck(deck_name)
if len(existing_cards) > 0:
return deck_name
# 4. Add cards using the CORRECT sanitized filename
# --- BASICS ---
add_card_to_deck(deck_name,
"**Welcome to FlipStack!**\n\nHow do you flip a card to see the answer?",
"**Tap anywhere** on the card if on mobile, or click/tap the Show Answer button below. You can also press **Space** on your keyboard.\n\n(Try it now!)",
None, None, ["tutorial", "basics"], "Tap to Flip")
# Card 2: Grading (Swipe Gestures)
add_card_to_deck(deck_name,
"**How do you grade a card?**\n\n(Try swiping this card now!)",
"You can use the buttons below, or **Swipe** the card:\n\n• **Swipe Right:** Good (Green)\n• **Swipe Up:** Hard (Yellow)\n• **Swipe Left:** Miss (Red)",
None, None, ["tutorial", "gestures"], "Swipe to Grade")
# Card 3: Mobile Navigation
add_card_to_deck(deck_name,
"**Where are the Deck and Category Options?**\n\n(Edit Deck, Rename, Export, Delete)",
"In the Library list, tap the **Menu Icon (⋮)** on the right side of any deck or category row.",
None, None, ["tutorial", "navigation"], None)
# --- 2. STUDY MODES ---
add_card_to_deck(deck_name,
"What is **Cram Mode**?",
"Click the **Storm** icon (cloud with lightning) in the study header toolbar above.\n\nThis lets you review **all** cards in the deck immediately, ignoring the daily schedule. Useful for last-minute exam prep!",
None, None, ["study-modes"], "Storm Icon")
add_card_to_deck(deck_name,
"What is **Reverse Mode**?",
"Click the **Rotate** icon (circular arrow) in the study header toolbar above to swap the Front and Back of cards temporarily.\n\nGreat for testing your knowledge from both directions.",
None, None, ["study-modes"], "Rotate Icon")
add_card_to_deck(deck_name,
"How do you **Shuffle** cards?",
"Click the **Shuffle** icon (crossed arrows) in the study header toolbar above to randomize the order of the remaining cards in your current session.",
None, None, ["study-modes"], "Randomize")
# --- 3. EDITING & IMAGES ---
add_card_to_deck(deck_name,
"How do you **Edit** a card while studying?",
"Click the **Pencil Icon** in the top-right corner of the card area.\n\nYou can also edit the entire deck via the Library menu.",
None, None, ["editing"], "Pencil Icon")
add_card_to_deck(deck_name,
"**Did you know?**\n\nWhat happens if you tap an image on a card?",
"It opens in a **Lightbox**!\n\nThis lets you zoom in and view large diagrams clearly, even on small screens.",
None, None, ["images"], "Zoom")
# --- 4. DATA MANAGEMENT ---
add_card_to_deck(deck_name,
"How do you see **Performance Stats**?",
"In the Library list, tap the **Menu Icon (⋮)** next to any deck and select **View Stats**.\n\nThis shows your study history and retention rates.",
None, None, ["data"], "Kebab Menu")
add_card_to_deck(deck_name,
"How do you **Import** decks?",
"Open the **Main Menu (≡)** at the top-right of the Library and select **Import Deck**.\n\nWe support **CSV** files and **Anki (.apkg)** packages.",
None, None, ["data"], "Hamburger Menu")
add_card_to_deck(deck_name,
"How do you **Backup** your data?",
"Open the **Main Menu (≡)** and select **Backup Data**.\n\nThis creates a full ZIP backup of all your decks and media.",
None, None, ["data"], "Hamburger Menu")
# --- 5. SETTINGS ---
add_card_to_deck(deck_name,
"How do you toggle **Dark/Light Mode**?",
"Click the **Sun/Moon** icon in the main toolbar at the top of the Library screen.",
None, None, ["appearance"], "Toolbar")
add_card_to_deck(deck_name,
"How do you turn **Sound Effects** On/Off?",
"Click the **Speaker** icon in the main toolbar to mute app sounds (flip/grade effects).\n\n(Note: This does not mute audio attached to specific cards.)",
None, None, ["settings"], "Toolbar")
add_card_to_deck(deck_name,
"How do you change the **Font**?",
"Open the **Main Menu (≡)** and select **Text Settings**.\n\nYou can adjust the font family and size for all cards to improve readability.",
None, None, ["appearance"], "Hamburger Menu")
return deck_name