File size: 8,979 Bytes
7563305
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Recall — Gradio app.  OWNER: Arturo (Module C)

Three views (Upload / Study / Recap) over a single Session held in gr.State.
Wired to content_pipeline + learning_engine. Runs against stubs immediately:

    pip install -r requirements.txt
    python app.py            # opens at http://127.0.0.1:7860 in stub mode

Flip RECALL_STUB=0 once the real model is wired:
    RECALL_STUB=0 python app.py
"""
from __future__ import annotations

import gradio as gr

import content_pipeline as cp
import learning_engine as le


# ---- Actions (UI <-> modules glue) -----------------------------------------

def start_session(file, pasted_text):
    if pasted_text and pasted_text.strip():
        text = pasted_text.strip()
    else:
        try:
            text = cp.extract_text(file)
        except cp.ExtractionError as e:
            return (None, gr.update(visible=True), gr.update(visible=False),
                    f"⚠️ {e}", "", "", gr.update(visible=False), None)
    if not text:
        return (None, gr.update(visible=True), gr.update(visible=False),
                "⚠️ No text found. Upload a PDF or paste some notes.", "", "",
                gr.update(visible=False), None)
    chunks = cp.chunk_text(text)
    debug = {
        "total_chars": len(text),
        "extracted_text_preview": text[:800] + ("…" if len(text) > 800 else ""),
        "chunk_count": len(chunks),
        "chunks": [
            {
                "index": i,
                "chars": len(c),
                "tokens_approx": len(c) // 4,
                "text": c,
            }
            for i, c in enumerate(chunks)
        ],
    }
    try:
        deck = cp.generate_deck(text)
    except Exception as e:
        return (None, gr.update(visible=True), gr.update(visible=False),
                f"⚠️ generate_deck failed ({type(e).__name__}: {e}). "
                "Extraction & chunks are shown below.",
                "", "", gr.update(visible=True), debug)
    if not deck:
        return (None, gr.update(visible=True), gr.update(visible=False),
                "⚠️ Couldn't generate questions from that. Try different material.",
                "", "", gr.update(visible=True), debug)
    session = le.init_session(deck)
    card = le.next_card(session)
    return (session, gr.update(visible=False), gr.update(visible=True),
            "", _progress(session), card["question"] if card else "",
            gr.update(visible=True), debug)


def submit_answer(session, user_answer):
    if not session:
        return session, "", "", "", gr.update()

    grade, fups = le.grade_and_adapt(session, user_answer or "")
    if grade is None:
        return session, "🎉 Deck complete!", "", "", gr.update(visible=False)

    followup_note = ""
    if fups:
        followup_note = ("🎯 Added " + str(len(fups)) +
                         " new question(s) targeting what you missed.")

    verdict = ("✅ " if grade["correct"] else "❌ ") + grade["explanation"]
    return session, verdict, followup_note, _progress(session), gr.update()


def change_difficulty(session, direction):
    """Difficulty dial (NAH-32): rewrite the current card harder/easier on the
    same concept and re-show it. No-op if there's no current card."""
    if not session:
        return session, "", ""
    card = le.next_card(session)
    if card is None:
        return session, "", ""
    new = cp.regenerate(card, direction)
    session = le.replace_card(session, card["id"], new)
    label = "harder" if direction == "harder" else "easier"
    return session, new["question"], f"🎚️ Rewrote this question to be {label}."


def show_next(session):
    card = le.next_card(session)
    if card is None:
        return session, "", gr.update(visible=False), gr.update(visible=True), _render_recap(session)
    return session, card["question"], gr.update(), gr.update(visible=False), ""


def finish_session(session):
    """End the session on demand and show the recap (NAH-35). The spaced-
    repetition queue never empties on its own, so this is the user's way out."""
    if not session:
        return gr.update(), gr.update(), ""
    return gr.update(visible=False), gr.update(visible=True), _render_recap(session)


def resume_study(session):
    """Return from the recap to keep studying (so recap isn't a dead end)."""
    card = le.next_card(session)
    return (gr.update(visible=True), gr.update(visible=False),
            card["question"] if card else "")


def _progress(session):
    total = len(session["deck"])
    answered = len(session["history"])
    current = min(answered + 1, total)
    remaining = len(session["queue"])
    return (f"**Card {current} of {total}**  ·  ✅ {answered} answered"
            f"  ·  🔥 Streak: {session['streak']}  ·  {remaining} left in queue")


def _render_recap(session):
    r = le.recap(session)
    return (
        f"### Session recap\n\n"
        f"**Answered:** {r['answered']}  ·  **🔥 Streak:** {r['streak']}\n\n"
        f"**Mastered:** {', '.join(r['mastered']) or '—'}\n\n"
        f"**Still weak:** {', '.join(r['weak_topics']) or '—'}\n\n"
        f"_{r['reflection']}_"
    )


# ---- UI ---------------------------------------------------------------------

with gr.Blocks(title="Recall — your AI study partner") as demo:
    session = gr.State(None)
    gr.Markdown("# 📚 Recall\n*Upload your material. Get quizzed. It adapts to what you miss.*")

    # Upload view
    with gr.Group(visible=True) as upload_view:
        gr.Markdown("### 1 · Add your study material")
        file_in = gr.File(label="Upload a PDF or .txt", file_types=[".pdf", ".txt"])
        text_in = gr.Textbox(label="…or paste notes", lines=4,
                             placeholder="Paste any text to study from")
        start_btn = gr.Button("Generate deck & start", variant="primary")
        upload_msg = gr.Markdown("")

    # Study view
    with gr.Group(visible=False) as study_view:
        progress = gr.Markdown("")
        question = gr.Markdown("")
        answer_in = gr.Textbox(label="Your answer", lines=2)
        with gr.Row():
            easier_btn = gr.Button("😌 Make it easier", size="sm")
            harder_btn = gr.Button("🔥 Make it harder", size="sm")
        submit_btn = gr.Button("Submit", variant="primary")
        verdict = gr.Markdown("")
        followup = gr.Markdown("")
        with gr.Row():
            next_btn = gr.Button("Next question →", variant="primary")
            finish_btn = gr.Button("🏁 Finish & see recap")

    # Recap view
    with gr.Group(visible=False) as recap_view:
        recap_md = gr.Markdown("")
        resume_btn = gr.Button("↩️ Keep studying")

    # Debug panel — visible after each upload so you can verify extraction & chunks
    with gr.Accordion("🔍 Debug: extraction & chunks", open=False, visible=False) as debug_accordion:
        debug_data = gr.JSON(label="Content pipeline output")

    # Every handler that can hit the model shows a spinner (show_progress="full")
    # and disables its button while working, so a slow call never reads as a dead
    # or double-clickable screen.
    start_btn.click(
        lambda: gr.update(value="⏳ Generating deck…", interactive=False), None, start_btn,
    ).then(
        start_session, [file_in, text_in],
        [session, upload_view, study_view, upload_msg, progress, question,
         debug_accordion, debug_data],
        show_progress="full",
    ).then(
        lambda: gr.update(value="Generate deck & start", interactive=True), None, start_btn,
    )

    submit_btn.click(
        lambda: gr.update(value="⏳ Grading…", interactive=False), None, submit_btn,
    ).then(
        submit_answer, [session, answer_in],
        [session, verdict, followup, progress, next_btn],
        show_progress="full",
    ).then(
        lambda: gr.update(value="Submit", interactive=True), None, submit_btn,
    )

    next_btn.click(
        show_next, [session],
        [session, question, study_view, recap_view, recap_md],
        show_progress="full",
    ).then(lambda: ("", "", ""), None, [answer_in, verdict, followup])

    finish_btn.click(
        finish_session, [session],
        [study_view, recap_view, recap_md],
        show_progress="full",
    )
    resume_btn.click(
        resume_study, [session],
        [study_view, recap_view, question],
    ).then(lambda: ("", "", ""), None, [answer_in, verdict, followup])

    # Difficulty dial — regenerate the current card harder/easier (NAH-32).
    easier_btn.click(
        lambda s: change_difficulty(s, "easier"), [session],
        [session, question, followup], show_progress="full",
    )
    harder_btn.click(
        lambda s: change_difficulty(s, "harder"), [session],
        [session, question, followup], show_progress="full",
    )


if __name__ == "__main__":
    # Gradio 6 moved `theme` from the Blocks constructor to launch().
    demo.launch(theme=gr.themes.Soft())