File size: 6,465 Bytes
e82864c
 
 
 
 
 
 
 
 
 
c904774
e82864c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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

# src/app/flashcards_tools.py

import json
import re
from pathlib import Path
from typing import Dict, List, Tuple, Optional

from deep_translator import GoogleTranslator

from .config import get_user_dir


def _get_decks_dir(username: str) -> Path:
    """
    Returns the directory where all of a user's decks are stored.
    """
    user_dir = get_user_dir(username)
    decks_dir = user_dir / "decks"
    decks_dir.mkdir(parents=True, exist_ok=True)
    return decks_dir


def list_user_decks(username: str) -> Dict[str, Path]:
    """
    Returns a mapping of deck name -> deck json path.
    Deck name is taken from the deck's "name" field if present,
    otherwise the filename stem.
    """
    decks_dir = _get_decks_dir(username)
    deck_files = sorted(decks_dir.glob("*.json"))
    decks: Dict[str, Path] = {}

    for path in deck_files:
        try:
            data = json.loads(path.read_text(encoding="utf-8"))
            name = data.get("name") or path.stem
        except Exception:
            name = path.stem

        # ensure uniqueness by appending stem if needed
        if name in decks and decks[name] != path:
            name = f"{name} ({path.stem})"
        decks[name] = path

    return decks


def _ensure_card_stats(card: Dict) -> None:
    """
    Ensure that a card has simple spaced-repetition stats.
    """
    if "score" not in card:  # learning strength
        card["score"] = 0
    if "reviews" not in card:
        card["reviews"] = 0


def load_deck(path: Path) -> Dict:
    """
    Loads a deck from JSON, ensuring 'cards' exists and that
    each card has basic stats for spaced repetition.
    """
    try:
        data = json.loads(path.read_text(encoding="utf-8"))
    except Exception:
        data = {}
    if "cards" not in data or not isinstance(data["cards"], list):
        data["cards"] = []
    if "name" not in data:
        data["name"] = path.stem
    if "tags" not in data or not isinstance(data["tags"], list):
        data["tags"] = []

    for card in data["cards"]:
        _ensure_card_stats(card)

    return data


def save_deck(path: Path, deck: Dict) -> None:
    """
    Saves deck to JSON.
    """
    if "cards" not in deck:
        deck["cards"] = []
    if "name" not in deck:
        deck["name"] = path.stem
    if "tags" not in deck or not isinstance(deck["tags"], list):
        deck["tags"] = []

    # make sure stats are present
    for card in deck["cards"]:
        _ensure_card_stats(card)

    path.write_text(json.dumps(deck, indent=2, ensure_ascii=False), encoding="utf-8")


# ------------------------------------------------------------
# Shared tokenization
# ------------------------------------------------------------

def _extract_candidate_words(text: str) -> List[str]:
    """
    Simple tokenizer & filter for candidate vocab words.
    """
    tokens = re.findall(r"\b\w+\b", text, flags=re.UNICODE)
    out = []
    seen = set()
    for t in tokens:
        t_norm = t.strip()
        if len(t_norm) < 2:
            continue
        if any(ch.isdigit() for ch in t_norm):
            continue
        lower = t_norm.lower()
        if lower in seen:
            continue
        seen.add(lower)
        out.append(t_norm)
    return out


# ------------------------------------------------------------
# OCR → Flashcards
# ------------------------------------------------------------

def generate_flashcards_from_ocr_results(
    username: str,
    ocr_results: List[Dict],
    deck_name: str = "ocr",
    target_lang: str = "en",
    tags: Optional[List[str]] = None,
) -> Path:
    """
    Takes OCR results (as produced by ocr_tools.ocr_and_translate_batch)
    and constructs a simple vocab deck.

    ocr_results: list of dict with keys:
        - "text": original text
        - optionally other fields (ignored)
    """
    all_text = []
    for res in ocr_results:
        t = res.get("text") or res.get("raw_text") or ""
        if t:
            all_text.append(t)
    joined = "\n".join(all_text)

    words = _extract_candidate_words(joined)
    if not words:
        raise ValueError("No candidate words found in OCR results.")

    translator = GoogleTranslator(source="auto", target=target_lang)
    cards = []
    for w in words:
        try:
            trans = translator.translate(w)
        except Exception:
            continue
        if not trans:
            continue
        if trans.strip().lower() == w.strip().lower():
            continue
        card = {
            "front": w,
            "back": trans,
            "content_type": "ocr_vocab",
            "language": target_lang,
        }
        _ensure_card_stats(card)
        cards.append(card)

    if not cards:
        raise ValueError("No translatable words found to build cards.")

    decks_dir = _get_decks_dir(username)
    deck_path = decks_dir / f"{deck_name}.json"

    deck = {
        "name": deck_name,
        "cards": cards,
        "tags": tags or [],
    }
    save_deck(deck_path, deck)
    return deck_path


# ------------------------------------------------------------
# Conversation/Text → Flashcards
# ------------------------------------------------------------

def generate_flashcards_from_text(
    username: str,
    text: str,
    deck_name: str = "conversation",
    target_lang: str = "en",
    tags: Optional[List[str]] = None,
) -> Path:
    """
    Build a vocab deck from raw conversation text.
    """
    words = _extract_candidate_words(text)
    if not words:
        raise ValueError("No candidate words found in text.")

    translator = GoogleTranslator(source="auto", target=target_lang)
    cards = []
    for w in words:
        try:
            trans = translator.translate(w)
        except Exception:
            continue
        if not trans:
            continue
        if trans.strip().lower() == w.strip().lower():
            continue
        card = {
            "front": w,
            "back": trans,
            "content_type": "conversation_vocab",
            "language": target_lang,
        }
        _ensure_card_stats(card)
        cards.append(card)

    if not cards:
        raise ValueError("No translatable words found to build cards.")

    decks_dir = _get_decks_dir(username)
    deck_path = decks_dir / f"{deck_name}.json"

    deck = {
        "name": deck_name,
        "cards": cards,
        "tags": tags or ["conversation"],
    }
    save_deck(deck_path, deck)
    return deck_path