File size: 28,918 Bytes
ee724af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e7551b
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
import gradio as gr
import json
import re
import random
import time
import os
from transformers import pipeline
from huggingface_hub import HfApi

# Set constants
DEFAULT_NUM_QUESTIONS = 3
DEFAULT_DIFFICULTY = "Medium"
MODEL_GENERATION = "facebook/opt-1.3b"  # Free model for question generation
MODEL_VERIFICATION = "gpt2-large"       # Free model for verification

# Initialize models (with low memory footprint)
try:
    question_generator = pipeline("text-generation", model=MODEL_GENERATION, max_length=1000)
    question_verifier = pipeline("text-generation", model=MODEL_VERIFICATION, max_length=300)
except Exception as e:
    print(f"Model loading error: {str(e)}. Will attempt to load on first use.")
    question_generator = None
    question_verifier = None

# Calculus curriculum from James Stewart's textbooks
calculus_curriculum = [
    {
        "chapter": "1. Functions and Models",
        "subchapters": [
            "1.1 Four Ways to Represent a Function",
            "1.2 Mathematical Models",
            "1.3 New Functions from Old Functions",
            "1.4 Exponential Functions",
            "1.5 Inverse Functions and Logarithms",
            "1.6 Parametric Curves"
        ],
        "key_formulas": [
            "Domain and Range",
            "Function composition: $(f \\circ g)(x) = f(g(x))$",
            "Exponential function: $f(x) = a^x$, where $a > 0$",
            "Natural exponential function: $f(x) = e^x$",
            "Logarithmic function: $f(x) = \\log_a(x)$, where $a > 0, a \\neq 1$",
            "Natural logarithm: $f(x) = \\ln(x)$"
        ]
    },
    {
        "chapter": "2. Limits and Derivatives",
        "subchapters": [
            "2.1 The Tangent and Velocity Problems",
            "2.2 The Limit of a Function",
            "2.3 Calculating Limits",
            "2.4 Continuity",
            "2.5 The Derivative",
            "2.6 The Derivative as a Function",
            "2.7 Derivatives of Trigonometric Functions",
            "2.8 The Chain Rule",
            "2.9 Implicit Differentiation",
            "2.10 Related Rates",
            "2.11 Linear Approximations and Differentials"
        ],
        "key_formulas": [
            "Limit Definition: $\\lim_{x \\to a} f(x) = L$",
            "Derivative Definition: $f'(x) = \\lim_{h \\to 0} \\frac{f(x+h) - f(x)}{h}$",
            "Power Rule: $\\frac{d}{dx}(x^n) = nx^{n-1}$",
            "Product Rule: $\\frac{d}{dx}[f(x)g(x)] = f'(x)g(x) + f(x)g'(x)$",
            "Quotient Rule: $\\frac{d}{dx}\\left[\\frac{f(x)}{g(x)}\\right] = \\frac{f'(x)g(x) - f(x)g'(x)}{[g(x)]^2}$",
            "Chain Rule: $\\frac{d}{dx}[f(g(x))] = f'(g(x)) \\cdot g'(x)$"
        ]
    },
    {
        "chapter": "3. Applications of Differentiation",
        "subchapters": [
            "3.1 Maximum and Minimum Values",
            "3.2 The Mean Value Theorem",
            "3.3 How Derivatives Affect the Shape of a Graph",
            "3.4 Indeterminate Forms and L'Hospital's Rule",
            "3.5 Summary of Curve Sketching",
            "3.6 Optimization Problems",
            "3.7 Newton's Method",
            "3.8 Antiderivatives"
        ],
        "key_formulas": [
            "Critical Points: $f'(x) = 0$ or $f'(x)$ is undefined",
            "Mean Value Theorem: If $f$ is continuous on $[a, b]$ and differentiable on $(a, b)$, then there exists a $c$ in $(a, b)$ such that $f'(c) = \\frac{f(b) - f(a)}{b - a}$",
            "Second Derivative Test: If $f'(c) = 0$ and $f''(c) > 0$, then $f$ has a local minimum at $c$",
            "L'Hospital's Rule: $\\lim_{x \\to a}\\frac{f(x)}{g(x)} = \\lim_{x \\to a}\\frac{f'(x)}{g'(x)}$",
            "Newton's Method: $x_{n+1} = x_n - \\frac{f(x_n)}{f'(x_n)}$"
        ]
    },
    {
        "chapter": "4. Integrals",
        "subchapters": [
            "4.1 Areas and Distances",
            "4.2 The Definite Integral",
            "4.3 The Fundamental Theorem of Calculus",
            "4.4 Indefinite Integrals and the Net Change Theorem",
            "4.5 The Substitution Rule"
        ],
        "key_formulas": [
            "Definite Integral: $\\int_a^b f(x)\\,dx = \\lim_{n \\to \\infty} \\sum_{i=1}^{n} f(x_i^*)\\Delta x$",
            "Fundamental Theorem of Calculus: $\\int_a^b f(x)\\,dx = F(b) - F(a)$ where $F'(x) = f(x)$",
            "Indefinite Integral: $\\int f(x)\\,dx = F(x) + C$ where $F'(x) = f(x)$",
            "Power Rule for Integration: $\\int x^n\\,dx = \\frac{x^{n+1}}{n+1} + C$ for $n \\neq -1$",
            "Substitution Rule: $\\int f(g(x))g'(x)\\,dx = \\int f(u)\\,du$ where $u = g(x)$"
        ]
    },
    {
        "chapter": "5. Applications of Integration",
        "subchapters": [
            "5.1 Areas Between Curves",
            "5.2 Volumes",
            "5.3 Volumes by Cylindrical Shells",
            "5.4 Work",
            "5.5 Average Value of a Function"
        ],
        "key_formulas": [
            "Area Between Curves: $\\int_a^b [f(x) - g(x)]\\,dx$ where $f(x) \\geq g(x)$",
            "Volume by Disk Method: $V = \\pi\\int_a^b [R(x)]^2\\,dx$",
            "Volume by Washer Method: $V = \\pi\\int_a^b [(R(x))^2 - (r(x))^2]\\,dx$",
            "Volume by Cylindrical Shells: $V = 2\\pi\\int_a^b xf(x)\\,dx$ for rotation about y-axis",
            "Average Value of $f$ on $[a,b]$: $f_{avg} = \\frac{1}{b-a}\\int_a^b f(x)\\,dx$",
            "Work: $W = \\int_a^b F(x)\\,dx$"
        ]
    },
    {
        "chapter": "6. Techniques of Integration",
        "subchapters": [
            "6.1 Integration by Parts",
            "6.2 Trigonometric Integrals",
            "6.3 Trigonometric Substitution",
            "6.4 Integration of Rational Functions by Partial Fractions",
            "6.5 Strategy for Integration",
            "6.6 Approximate Integration",
            "6.7 Improper Integrals"
        ],
        "key_formulas": [
            "Integration by Parts: $\\int u\\,dv = uv - \\int v\\,du$",
            "Trigonometric Integrals: $\\int \\sin^n x \\cos^m x\\,dx$ (various formulas)",
            "Trig Substitution: $x = a\\sin\\theta$ for $\\sqrt{a^2-x^2}$, $x = a\\tan\\theta$ for $\\sqrt{a^2+x^2}$",
            "Partial Fractions: $\\frac{P(x)}{Q(x)} = \\frac{A}{(x-a)} + \\frac{B}{(x-a)^2} + \\frac{Cx+D}{x^2+bx+c} + ...$",
            "Improper Integrals: $\\int_a^{\\infty} f(x)\\,dx = \\lim_{t \\to \\infty} \\int_a^t f(x)\\,dx$"
        ]
    },
    {
        "chapter": "7. Differential Equations",
        "subchapters": [
            "7.1 Modeling with Differential Equations",
            "7.2 Direction Fields and Euler's Method",
            "7.3 Separable Equations",
            "7.4 Models for Population Growth",
            "7.5 Linear Equations",
            "7.6 Predator-Prey Systems"
        ],
        "key_formulas": [
            "General form of a first-order differential equation: $\\frac{dy}{dx} = f(x, y)$",
            "Separable equation: $\\frac{dy}{dx} = g(x)h(y)$ → $\\int \\frac{1}{h(y)}dy = \\int g(x)dx + C$",
            "First-order linear differential equation: $\\frac{dy}{dx} + P(x)y = Q(x)$",
            "Integrating factor method: Multiply by $e^{\\int P(x)dx}$",
            "Euler's Method: $y_{n+1} = y_n + hf(x_n, y_n)$"
        ]
    },
    {
        "chapter": "8. Infinite Sequences and Series",
        "subchapters": [
            "8.1 Sequences",
            "8.2 Series",
            "8.3 The Integral Test and Estimates of Sums",
            "8.4 The Comparison Tests",
            "8.5 Alternating Series",
            "8.6 Absolute Convergence and the Ratio and Root Tests",
            "8.7 Strategy for Testing Series",
            "8.8 Power Series",
            "8.9 Representations of Functions as Power Series",
            "8.10 Taylor and Maclaurin Series"
        ],
        "key_formulas": [
            "Geometric Series: $\\sum_{n=0}^{\\infty} ar^n = \\frac{a}{1-r}$ if $|r| < 1$",
            "Taylor Series: $f(x) = \\sum_{n=0}^{\\infty} \\frac{f^{(n)}(a)}{n!}(x-a)^n$",
            "Maclaurin Series: $f(x) = \\sum_{n=0}^{\\infty} \\frac{f^{(n)}(0)}{n!}x^n$",
            "Common Maclaurin Series: $e^x = \\sum_{n=0}^{\\infty} \\frac{x^n}{n!}$, $\\sin(x) = \\sum_{n=0}^{\\infty} \\frac{(-1)^n}{(2n+1)!}x^{2n+1}$",
            "Ratio Test: $\\lim_{n \\to \\infty} |\\frac{a_{n+1}}{a_n}| < 1$ implies convergence"
        ]
    },
    {
        "chapter": "9. Parametric Equations and Polar Coordinates",
        "subchapters": [
            "9.1 Parametric Curves",
            "9.2 Calculus with Parametric Curves",
            "9.3 Polar Coordinates",
            "9.4 Areas and Lengths in Polar Coordinates",
            "9.5 Conic Sections"
        ],
        "key_formulas": [
            "Parametric curve: $x = f(t)$, $y = g(t)$",
            "Arc length of parametric curve: $L = \\int_a^b \\sqrt{[f'(t)]^2 + [g'(t)]^2}\\,dt$",
            "Polar to rectangular coordinates: $x = r\\cos\\theta$, $y = r\\sin\\theta$",
            "Rectangular to polar coordinates: $r = \\sqrt{x^2 + y^2}$, $\\theta = \\arctan(\\frac{y}{x})$",
            "Area in polar coordinates: $A = \\frac{1}{2}\\int_{\\alpha}^{\\beta} [r(\\theta)]^2\\,d\\theta$"
        ]
    },
    {
        "chapter": "10. Vectors and the Geometry of Space",
        "subchapters": [
            "10.1 Three-Dimensional Coordinate Systems",
            "10.2 Vectors",
            "10.3 The Dot Product",
            "10.4 The Cross Product",
            "10.5 Equations of Lines and Planes",
            "10.6 Cylinders and Quadric Surfaces"
        ],
        "key_formulas": [
            "Dot Product: $\\vec{a} \\cdot \\vec{b} = |\\vec{a}||\\vec{b}|\\cos\\theta$",
            "Cross Product: $\\vec{a} \\times \\vec{b} = |\\vec{a}||\\vec{b}|\\sin\\theta\\,\\vec{n}$",
            "Equation of a line: $\\vec{r} = \\vec{r_0} + t\\vec{v}$",
            "Equation of a plane: $\\vec{n} \\cdot (\\vec{r} - \\vec{r_0}) = 0$ or $ax + by + cz + d = 0$",
            "Distance from point to plane: $d = \\frac{|ax_0 + by_0 + cz_0 + d|}{\\sqrt{a^2 + b^2 + c^2}}$"
        ]
    },
    {
        "chapter": "11. Vector Functions",
        "subchapters": [
            "11.1 Vector Functions and Space Curves",
            "11.2 Derivatives and Integrals of Vector Functions",
            "11.3 Arc Length and Curvature",
            "11.4 Motion in Space: Velocity and Acceleration"
        ],
        "key_formulas": [
            "Vector function: $\\vec{r}(t) = x(t)\\vec{i} + y(t)\\vec{j} + z(t)\\vec{k}$",
            "Derivative of vector function: $\\vec{r}'(t) = x'(t)\\vec{i} + y'(t)\\vec{j} + z'(t)\\vec{k}$",
            "Arc length: $L = \\int_a^b |\\vec{r}'(t)|\\,dt$",
            "Unit tangent vector: $\\vec{T}(t) = \\frac{\\vec{r}'(t)}{|\\vec{r}'(t)|}$",
            "Curvature: $\\kappa = \\frac{|\\vec{T}'(t)|}{|\\vec{r}'(t)|}$",
            "Acceleration: $\\vec{a}(t) = \\vec{r}''(t)$"
        ]
    },
    {
        "chapter": "12. Partial Derivatives",
        "subchapters": [
            "12.1 Functions of Several Variables",
            "12.2 Limits and Continuity",
            "12.3 Partial Derivatives",
            "12.4 Tangent Planes and Linear Approximations",
            "12.5 The Chain Rule",
            "12.6 Directional Derivatives and the Gradient Vector",
            "12.7 Maximum and Minimum Values",
            "12.8 Lagrange Multipliers"
        ],
        "key_formulas": [
            "Partial derivative: $\\frac{\\partial f}{\\partial x}(x_0, y_0)$",
            "Gradient: $\\nabla f = \\frac{\\partial f}{\\partial x}\\vec{i} + \\frac{\\partial f}{\\partial y}\\vec{j} + \\frac{\\partial f}{\\partial z}\\vec{k}$",
            "Directional derivative: $D_\\vec{u}f = \\nabla f \\cdot \\vec{u}$",
            "Tangent plane: $z - z_0 = f_x(x_0, y_0)(x - x_0) + f_y(x_0, y_0)(y - y_0)$",
            "Chain Rule: $\\frac{dz}{dt} = \\frac{\\partial z}{\\partial x}\\frac{dx}{dt} + \\frac{\\partial z}{\\partial y}\\frac{dy}{dt}$"
        ]
    },
    {
        "chapter": "13. Multiple Integrals",
        "subchapters": [
            "13.1 Double Integrals over Rectangles",
            "13.2 Iterated Integrals",
            "13.3 Double Integrals over General Regions",
            "13.4 Double Integrals in Polar Coordinates",
            "13.5 Applications of Double Integrals",
            "13.6 Triple Integrals",
            "13.7 Triple Integrals in Cylindrical Coordinates",
            "13.8 Triple Integrals in Spherical Coordinates",
            "13.9 Change of Variables in Multiple Integrals"
        ],
        "key_formulas": [
            "Double integral: $\\iint_R f(x,y)\\,dA = \\int_a^b \\int_c^d f(x,y)\\,dy\\,dx$",
            "Area in polar coordinates: $\\iint_R f(r,\\theta)\\,dA = \\int_{\\alpha}^{\\beta} \\int_{h_1(\\theta)}^{h_2(\\theta)} f(r,\\theta)\\,r\\,dr\\,d\\theta$",
            "Triple integral: $\\iiint_E f(x,y,z)\\,dV$",
            "Cylindrical coordinates: $\\iiint_E f(x,y,z)\\,dV = \\iiint_E f(r\\cos\\theta, r\\sin\\theta, z)\\,r\\,dr\\,d\\theta\\,dz$",
            "Spherical coordinates: $\\iiint_E f(x,y,z)\\,dV = \\iiint_E f(\\rho\\sin\\phi\\cos\\theta, \\rho\\sin\\phi\\sin\\theta, \\rho\\cos\\phi)\\,\\rho^2\\sin\\phi\\,d\\rho\\,d\\phi\\,d\\theta$"
        ]
    },
    {
        "chapter": "14. Vector Calculus",
        "subchapters": [
            "14.1 Vector Fields",
            "14.2 Line Integrals",
            "14.3 The Fundamental Theorem for Line Integrals",
            "14.4 Green's Theorem",
            "14.5 Curl and Divergence",
            "14.6 Surface Integrals",
            "14.7 Stokes' Theorem",
            "14.8 The Divergence Theorem"
        ],
        "key_formulas": [
            "Line integral of scalar function: $\\int_C f(x,y,z)\\,ds = \\int_a^b f(\\vec{r}(t))|\\vec{r}'(t)|\\,dt$",
            "Line integral of vector field: $\\int_C \\vec{F} \\cdot d\\vec{r} = \\int_a^b \\vec{F}(\\vec{r}(t)) \\cdot \\vec{r}'(t)\\,dt$",
            "Green's Theorem: $\\oint_C (P\\,dx + Q\\,dy) = \\iint_D (\\frac{\\partial Q}{\\partial x} - \\frac{\\partial P}{\\partial y})\\,dA$",
            "Divergence: $\\text{div}\\,\\vec{F} = \\nabla \\cdot \\vec{F} = \\frac{\\partial P}{\\partial x} + \\frac{\\partial Q}{\\partial y} + \\frac{\\partial R}{\\partial z}$",
            "Curl: $\\text{curl}\\,\\vec{F} = \\nabla \\times \\vec{F}$",
            "Stokes' Theorem: $\\int_S (\\nabla \\times \\vec{F}) \\cdot d\\vec{S} = \\oint_C \\vec{F} \\cdot d\\vec{r}$",
            "Divergence Theorem: $\\iiint_E (\\nabla \\cdot \\vec{F})\\,dV = \\iint_{\\partial E} \\vec{F} \\cdot d\\vec{S}$"
        ]
    }
]

def load_models_if_needed():
    """Ensures models are loaded when needed"""
    global question_generator, question_verifier
    
    if question_generator is None:
        try:
            question_generator = pipeline("text-generation", model=MODEL_GENERATION, max_length=1000)
        except Exception as e:
            return f"Error loading question generator: {str(e)}"
    
    if question_verifier is None:
        try:
            question_verifier = pipeline("text-generation", model=MODEL_VERIFICATION, max_length=300)
        except Exception as e:
            return f"Error loading question verifier: {str(e)}"
    
    return None

def get_chapter_summary(chapter_idx, subchapter_idx=None):
    """Get summary of selected chapter and subchapter"""
    if chapter_idx < 0 or chapter_idx >= len(calculus_curriculum):
        return "Invalid chapter selection."
    
    chapter = calculus_curriculum[chapter_idx]
    
    if subchapter_idx is None or subchapter_idx < 0 or subchapter_idx >= len(chapter["subchapters"]):
        # Return chapter summary only
        summary = f"# {chapter['chapter']}\n\n"
        summary += "## Key Formulas\n"
        for formula in chapter.get("key_formulas", []):
            summary += f"- {formula}\n"
        return summary
    
    # Return specific subchapter
    subchapter = chapter["subchapters"][subchapter_idx]
    summary = f"# {chapter['chapter']}\n## {subchapter}\n\n"
    summary += "### Key Formulas\n"
    for formula in chapter.get("key_formulas", []):
        summary += f"- {formula}\n"
    
    return summary

def generate_question_prompt(chapter, subchapter, difficulty, num_questions=3):
    """Generate a prompt for the model to create questions"""
    prompt = f"""Create {num_questions} university-level mathematics questions about {subchapter} from {chapter} at {difficulty} difficulty.

For each question:
1. Write a clear, university-level calculus problem that requires understanding of the concepts and techniques.
2. Include a step-by-step solution showing all work and mathematical reasoning.
3. Provide the final answer.

Format your response exactly as follows:

## Question 1
[Question text]

### Solution
Step 1: [First step of solution]
Step 2: [Second step]
...

### Answer
[Final answer]

## Question 2
...

Make sure all mathematics is correct and your solution steps are clear and logical.
"""
    return prompt

def verify_question(question_text, solution_text):
    """Verify if the question and solution are mathematically sound"""
    error_msg = load_models_if_needed()
    if error_msg:
        return False, error_msg
    
    verification_prompt = f"""Verify if this calculus question and solution are mathematically correct:
    
Question: {question_text}

Solution: {solution_text}

Is the solution mathematically correct? Answer Yes or No and briefly explain why."""

    try:
        # Get verification response
        verification = question_verifier(verification_prompt, max_length=300)[0]['generated_text']
        
        # Check response for indication that the solution is correct
        if "yes" in verification.lower() and "incorrect" not in verification.lower() and "error" not in verification.lower():
            return True, "Verification passed"
        else:
            # Extract the explanation for why it's incorrect
            explanation = verification.split("No")[1] if "No" in verification else "Unable to determine specific issue"
            return False, f"Verification failed: {explanation}"
    except Exception as e:
        return False, f"Error during verification: {str(e)}"

def generate_questions(chapter_index, subchapter_index, difficulty, num_questions):
    """Generate mathematics questions based on chapter/subchapter"""
    error_msg = load_models_if_needed()
    if error_msg:
        return f"## Error Loading Models\n\n{error_msg}\n\nPlease try again later or contact the administrator."

    # Get chapter and subchapter information
    if chapter_index < 0 or chapter_index >= len(calculus_curriculum):
        return "Please select a valid chapter."
        
    chapter = calculus_curriculum[chapter_index]
    
    if subchapter_index < 0 or subchapter_index >= len(chapter["subchapters"]):
        return "Please select a valid subchapter."
    
    subchapter = chapter["subchapters"][subchapter_index]
    
    # Generate prompt for the model
    prompt = generate_question_prompt(chapter["chapter"], subchapter, difficulty, num_questions)
    
    try:
        # Generate questions
        result = question_generator(prompt, max_length=1500, do_sample=True, 
                                   temperature=0.7, top_p=0.85, num_return_sequences=1)[0]['generated_text']
        
        # Extract generated questions and solutions
        result = result.replace(prompt, "")
        
        # Basic formatting fixes
        result = re.sub(r'#+\s*Question', '## Question', result)
        result = re.sub(r'#+\s*Solution', '### Solution', result)
        result = re.sub(r'#+\s*Answer', '### Answer', result)
        
        # Check if we got properly formatted output
        if "## Question" not in result:
            # Fallback to template questions for the topic
            result = generate_fallback_questions(chapter["chapter"], subchapter, num_questions)
        
        # Add chapter summary at the top
        summary = get_chapter_summary(chapter_index, subchapter_index)
        result = f"{summary}\n\n# Generated Questions\n\n{result}"
        
        return result
        
    except Exception as e:
        return f"Error generating questions: {str(e)}\n\nPlease try again or select a different topic."

def generate_fallback_questions(chapter, subchapter, num_questions):
    """Generate fallback questions when model generation fails"""
    # Basic templates for different calculus topics
    if "Limits" in chapter or "Limits" in subchapter:
        questions = [
            {
                "question": "Evaluate the limit: $\\lim_{x \\to 2} \\frac{x^3 - 8}{x - 2}$",
                "solution": "Step 1: Note that this is an indeterminate form (0/0) when x = 2.\n" +
                           "Step 2: Factor the numerator: $x^3 - 8 = (x - 2)(x^2 + 2x + 4)$\n" +
                           "Step 3: Simplify: $\\lim_{x \\to 2} \\frac{(x - 2)(x^2 + 2x + 4)}{x - 2} = \\lim_{x \\to 2} (x^2 + 2x + 4)$\n" +
                           "Step 4: Evaluate by direct substitution: $2^2 + 2(2) + 4 = 4 + 4 + 4 = 12$",
                "answer": "12"
            },
            {
                "question": "Find the limit: $\\lim_{x \\to 0} \\frac{\\sin(3x)}{x}$",
                "solution": "Step 1: Rewrite using the limit property $\\lim_{x \\to 0} \\frac{\\sin x}{x} = 1$\n" +
                           "Step 2: $\\lim_{x \\to 0} \\frac{\\sin(3x)}{x} = \\lim_{x \\to 0} 3 \\cdot \\frac{\\sin(3x)}{3x}$\n" +
                           "Step 3: Apply the limit property: $3 \\cdot \\lim_{x \\to 0} \\frac{\\sin(3x)}{3x} = 3 \\cdot 1 = 3$",
                "answer": "3"
            }
        ]
    elif "Derivative" in chapter or "Derivative" in subchapter:
        questions = [
            {
                "question": "Find the derivative of $f(x) = x^3\\ln(x) - \\frac{x^3}{3}$",
                "solution": "Step 1: Use the product rule on $x^3\\ln(x)$\n" +
                           "$\\frac{d}{dx}[x^3\\ln(x)] = x^3 \\cdot \\frac{1}{x} + \\ln(x) \\cdot 3x^2$\n" +
                           "$= x^2 + 3x^2\\ln(x)$\n" +
                           "Step 2: Find the derivative of $\\frac{x^3}{3}$\n" +
                           "$\\frac{d}{dx}[\\frac{x^3}{3}] = \\frac{3x^2}{3} = x^2$\n" +
                           "Step 3: Combine the results\n" +
                           "$f'(x) = x^2 + 3x^2\\ln(x) - x^2 = 3x^2\\ln(x)$",
                "answer": "$f'(x) = 3x^2\\ln(x)$"
            }
        ]
    elif "Integration" in chapter or "Integral" in chapter or "Integration" in subchapter or "Integral" in subchapter:
        questions = [
            {
                "question": "Evaluate the integral: $\\int x^2\\ln(x) dx$",
                "solution": "Step 1: Use integration by parts with $u = \\ln(x)$ and $dv = x^2 dx$\n" +
                           "Then $du = \\frac{1}{x}dx$ and $v = \\frac{x^3}{3}$\n" +
                           "Step 2: Apply the formula $\\int u dv = uv - \\int v du$\n" +
                           "$\\int x^2\\ln(x) dx = \\ln(x) \\cdot \\frac{x^3}{3} - \\int \\frac{x^3}{3} \\cdot \\frac{1}{x} dx$\n" +
                           "$= \\frac{x^3\\ln(x)}{3} - \\frac{1}{3}\\int x^2 dx$\n" +
                           "$= \\frac{x^3\\ln(x)}{3} - \\frac{1}{3} \\cdot \\frac{x^3}{3} + C$\n" +
                           "$= \\frac{x^3\\ln(x)}{3} - \\frac{x^3}{9} + C$",
                "answer": "$\\frac{x^3\\ln(x)}{3} - \\frac{x^3}{9} + C$"
            }
        ]
    else:
        # Generic calculus questions
        questions = [
            {
                "question": "Find the critical points of $f(x) = x^3 - 6x^2 + 12x + 5$ and determine their nature.",
                "solution": "Step 1: Find the derivative: $f'(x) = 3x^2 - 12x + 12$\n" +
                           "Step 2: Set $f'(x) = 0$ and solve: $3x^2 - 12x + 12 = 0$\n" +
                           "Step 3: Simplify: $x^2 - 4x + 4 = 0$\n" +
                           "Step 4: Factor: $(x - 2)^2 = 0$\n" +
                           "Step 5: Therefore $x = 2$ is a critical point (with multiplicity 2)\n" +
                           "Step 6: Find the second derivative: $f''(x) = 6x - 12$\n" +
                           "Step 7: Evaluate at $x = 2$: $f''(2) = 6(2) - 12 = 0$\n" +
                           "Step 8: Since $f''(2) = 0$, the second derivative test is inconclusive\n" +
                           "Step 9: Checking $f'(x)$ around $x = 2$:\n" +
                           "For $x < 2$, $f'(x) < 0$ and for $x > 2$, $f'(x) > 0$\n" +
                           "Step 10: Therefore, $x = 2$ is a point of inflection",
                "answer": "$x = 2$ is a critical point and an inflection point"
            }
        ]
    
    # Get a random subset of questions or duplicate if we need more
    result_questions = []
    for i in range(num_questions):
        idx = i % len(questions)
        q = questions[idx]
        result_questions.append({
            "id": i+1,
            "question": q["question"],
            "solution": q["solution"],
            "answer": q["answer"]
        })
    
    # Format the output
    result = ""
    for q in result_questions:
        result += f"## Question {q['id']}\n{q['question']}\n\n"
        result += f"### Solution\n{q['solution']}\n\n"
        result += f"### Answer\n{q['answer']}\n\n"
    
    return result

def on_chapter_change(chapter_index):
    """Update subchapter dropdown based on selected chapter"""
    if chapter_index < 0 or chapter_index >= len(calculus_curriculum):
        return gr.Dropdown(choices=[], value=None)
    
    subchapters = calculus_curriculum[chapter_index]["subchapters"]
    return gr.Dropdown(choices=subchapters, value=subchapters[0] if subchapters else None)

def create_interface():
    """Create the Gradio interface"""
    # Extract chapter titles for dropdown
    chapters = [chapter["chapter"] for chapter in calculus_curriculum]
    
    with gr.Blocks(title="Calculus Question Generator", theme=gr.themes.Soft()) as demo:
        gr.Markdown("# 🧮 Calculus Question Generator")
        gr.Markdown("Generate university-level calculus questions with step-by-step solutions.")
        
        with gr.Row():
            with gr.Column(scale=2):
                chapter_dropdown = gr.Dropdown(
                    choices=chapters,
                    value=chapters[0] if chapters else None,
                    label="Chapter",
                    info="Select a chapter from Stewart's Calculus"
                )
                
                subchapter_dropdown = gr.Dropdown(
                    choices=calculus_curriculum[0]["subchapters"] if calculus_curriculum else [],
                    value=calculus_curriculum[0]["subchapters"][0] if calculus_curriculum and calculus_curriculum[0]["subchapters"] else None,
                    label="Subchapter",
                    info="Select a specific subchapter"
                )
                
                with gr.Row():
                    num_questions = gr.Slider(
                        minimum=1,
                        maximum=5,
                        value=DEFAULT_NUM_QUESTIONS,
                        step=1,
                        label="Number of Questions"
                    )
                    
                    difficulty = gr.Dropdown(
                        choices=["Easy", "Medium", "Hard", "Advanced"],
                        value=DEFAULT_DIFFICULTY,
                        label="Difficulty Level"
                    )
                
                generate_button = gr.Button("Generate Questions", variant="primary")
                
        output = gr.Markdown(label="Generated Questions & Solutions")
        
        # Handle chapter selection change
        chapter_dropdown.change(
            fn=on_chapter_change,
            inputs=[chapter_dropdown],
            outputs=[subchapter_dropdown]
        )
        
        # Handle generate button click
        generate_button.click(
            fn=generate_questions,
            inputs=[
                gr.State(lambda: chapters.index(chapter_dropdown.value) if chapter_dropdown.value in chapters else 0),
                gr.State(lambda: calculus_curriculum[chapters.index(chapter_dropdown.value) if chapter_dropdown.value in chapters else 0]["subchapters"].index(subchapter_dropdown.value) if subchapter_dropdown.value in calculus_curriculum[chapters.index(chapter_dropdown.value) if chapter_dropdown.value in chapters else 0]["subchapters"] else 0),
                difficulty,
                num_questions
            ],
            outputs=[output]
        )
        
        gr.Markdown("---")
        gr.Markdown("Created by Kamagelo Mosia | Based on James Stewart's Calculus curriculum")
    
    return demo

# Create and launch the interface
demo = create_interface()
demo.launch()