pocket-tutor 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +171 -2
  3. package/bin/pocket-tutor.js +57 -0
  4. package/config.example.json +12 -0
  5. package/docs/CLIP_RULES.md +38 -0
  6. package/package.json +74 -4
  7. package/scripts/build-ui.mjs +25 -0
  8. package/scripts/clip-judge.js +106 -0
  9. package/scripts/doctor.js +58 -0
  10. package/scripts/setup-visuals.js +27 -0
  11. package/scripts/visual_scene.py +279 -0
  12. package/src/astryx-themes.js +18 -0
  13. package/src/browser.js +38 -0
  14. package/src/config.js +84 -0
  15. package/src/graph.js +114 -0
  16. package/src/helper.ps1 +67 -0
  17. package/src/main.js +490 -0
  18. package/src/model.js +283 -0
  19. package/src/native.js +50 -0
  20. package/src/place.js +29 -0
  21. package/src/preload.js +17 -0
  22. package/src/privacy.js +40 -0
  23. package/src/project.js +252 -0
  24. package/src/search.js +111 -0
  25. package/src/themes/lens/lens.css +1165 -0
  26. package/src/themes/lens/lens.css.d.ts +9 -0
  27. package/src/themes/lens/lens.d.ts +14 -0
  28. package/src/themes/lens/lens.fonts.css +2 -0
  29. package/src/themes/lens/lens.js +627 -0
  30. package/src/themes/lens/lens.variants.d.ts +22 -0
  31. package/src/themes/lens/lensTheme.doc.mjs +10 -0
  32. package/src/themes/lens/lensTheme.ts +2 -0
  33. package/src/ui/app.jsx +268 -0
  34. package/src/ui/dist/assets/KaTeX_AMS-Regular-CYEKBG2K.woff +0 -0
  35. package/src/ui/dist/assets/KaTeX_AMS-Regular-JKX5W2C4.ttf +0 -0
  36. package/src/ui/dist/assets/KaTeX_AMS-Regular-U6PRYMIZ.woff2 +0 -0
  37. package/src/ui/dist/assets/KaTeX_Caligraphic-Bold-5QL5CMTE.woff2 +0 -0
  38. package/src/ui/dist/assets/KaTeX_Caligraphic-Bold-WZ3QSGD3.woff +0 -0
  39. package/src/ui/dist/assets/KaTeX_Caligraphic-Bold-ZTS3R3HK.ttf +0 -0
  40. package/src/ui/dist/assets/KaTeX_Caligraphic-Regular-3LKEU76G.woff +0 -0
  41. package/src/ui/dist/assets/KaTeX_Caligraphic-Regular-A7XRTZ5Q.ttf +0 -0
  42. package/src/ui/dist/assets/KaTeX_Caligraphic-Regular-KX5MEWCF.woff2 +0 -0
  43. package/src/ui/dist/assets/KaTeX_Fraktur-Bold-2QVFK6NQ.woff2 +0 -0
  44. package/src/ui/dist/assets/KaTeX_Fraktur-Bold-T4SWXBMT.woff +0 -0
  45. package/src/ui/dist/assets/KaTeX_Fraktur-Bold-WGHVTYOR.ttf +0 -0
  46. package/src/ui/dist/assets/KaTeX_Fraktur-Regular-2PEIFJSJ.woff2 +0 -0
  47. package/src/ui/dist/assets/KaTeX_Fraktur-Regular-5U4OPH2X.ttf +0 -0
  48. package/src/ui/dist/assets/KaTeX_Fraktur-Regular-PQMHCIK6.woff +0 -0
  49. package/src/ui/dist/assets/KaTeX_Main-Bold-2GA4IZIN.woff +0 -0
  50. package/src/ui/dist/assets/KaTeX_Main-Bold-W5FBVCZM.ttf +0 -0
  51. package/src/ui/dist/assets/KaTeX_Main-Bold-YP5VVQRP.woff2 +0 -0
  52. package/src/ui/dist/assets/KaTeX_Main-BoldItalic-4P4C7HJH.woff +0 -0
  53. package/src/ui/dist/assets/KaTeX_Main-BoldItalic-N4V3DX7S.woff2 +0 -0
  54. package/src/ui/dist/assets/KaTeX_Main-BoldItalic-ODMLBJJQ.ttf +0 -0
  55. package/src/ui/dist/assets/KaTeX_Main-Italic-I43T2HSR.ttf +0 -0
  56. package/src/ui/dist/assets/KaTeX_Main-Italic-RELBIK7M.woff2 +0 -0
  57. package/src/ui/dist/assets/KaTeX_Main-Italic-SASNQFN2.woff +0 -0
  58. package/src/ui/dist/assets/KaTeX_Main-Regular-ARRPAO67.woff2 +0 -0
  59. package/src/ui/dist/assets/KaTeX_Main-Regular-P5I74A2A.woff +0 -0
  60. package/src/ui/dist/assets/KaTeX_Main-Regular-W74P5G27.ttf +0 -0
  61. package/src/ui/dist/assets/KaTeX_Math-BoldItalic-6EBV3DK5.woff +0 -0
  62. package/src/ui/dist/assets/KaTeX_Math-BoldItalic-K4WTGH3J.woff2 +0 -0
  63. package/src/ui/dist/assets/KaTeX_Math-BoldItalic-VB447A4D.ttf +0 -0
  64. package/src/ui/dist/assets/KaTeX_Math-Italic-6KGCHLFN.woff2 +0 -0
  65. package/src/ui/dist/assets/KaTeX_Math-Italic-KKK3USB2.woff +0 -0
  66. package/src/ui/dist/assets/KaTeX_Math-Italic-SON4MRCA.ttf +0 -0
  67. package/src/ui/dist/assets/KaTeX_SansSerif-Bold-RRNVJFFW.woff2 +0 -0
  68. package/src/ui/dist/assets/KaTeX_SansSerif-Bold-STQ6RXC7.ttf +0 -0
  69. package/src/ui/dist/assets/KaTeX_SansSerif-Bold-X5M5EMOD.woff +0 -0
  70. package/src/ui/dist/assets/KaTeX_SansSerif-Italic-HMPFTM52.woff2 +0 -0
  71. package/src/ui/dist/assets/KaTeX_SansSerif-Italic-PSN4QKYX.woff +0 -0
  72. package/src/ui/dist/assets/KaTeX_SansSerif-Italic-WTBAZBGY.ttf +0 -0
  73. package/src/ui/dist/assets/KaTeX_SansSerif-Regular-2TL3USAE.ttf +0 -0
  74. package/src/ui/dist/assets/KaTeX_SansSerif-Regular-OQCII6EP.woff +0 -0
  75. package/src/ui/dist/assets/KaTeX_SansSerif-Regular-XIQ62X4E.woff2 +0 -0
  76. package/src/ui/dist/assets/KaTeX_Script-Regular-72OLXYNA.ttf +0 -0
  77. package/src/ui/dist/assets/KaTeX_Script-Regular-A5IFOEBS.woff +0 -0
  78. package/src/ui/dist/assets/KaTeX_Script-Regular-APUWIHLP.woff2 +0 -0
  79. package/src/ui/dist/assets/KaTeX_Size1-Regular-4HRHTS65.woff +0 -0
  80. package/src/ui/dist/assets/KaTeX_Size1-Regular-5LRUTBFT.woff2 +0 -0
  81. package/src/ui/dist/assets/KaTeX_Size1-Regular-7K6AASVL.ttf +0 -0
  82. package/src/ui/dist/assets/KaTeX_Size2-Regular-222HN3GT.ttf +0 -0
  83. package/src/ui/dist/assets/KaTeX_Size2-Regular-K5ZHAIS6.woff +0 -0
  84. package/src/ui/dist/assets/KaTeX_Size2-Regular-LELKET5D.woff2 +0 -0
  85. package/src/ui/dist/assets/KaTeX_Size3-Regular-TLFPAHDE.woff +0 -0
  86. package/src/ui/dist/assets/KaTeX_Size3-Regular-UFCO6WCA.ttf +0 -0
  87. package/src/ui/dist/assets/KaTeX_Size3-Regular-WQRQ47UD.woff2 +0 -0
  88. package/src/ui/dist/assets/KaTeX_Size4-Regular-7PGNVPQK.ttf +0 -0
  89. package/src/ui/dist/assets/KaTeX_Size4-Regular-CDMV7U5C.woff2 +0 -0
  90. package/src/ui/dist/assets/KaTeX_Size4-Regular-PKMWZHNC.woff +0 -0
  91. package/src/ui/dist/assets/KaTeX_Typewriter-Regular-3F5K6SQ6.ttf +0 -0
  92. package/src/ui/dist/assets/KaTeX_Typewriter-Regular-MJMFSK64.woff +0 -0
  93. package/src/ui/dist/assets/KaTeX_Typewriter-Regular-VBYJ4NRC.woff2 +0 -0
  94. package/src/ui/dist/assets/figtree-latin-400-normal-PORFSHKN.woff2 +0 -0
  95. package/src/ui/dist/assets/figtree-latin-500-normal-AHYR5JKA.woff2 +0 -0
  96. package/src/ui/dist/assets/figtree-latin-600-normal-5C6Z7QEI.woff2 +0 -0
  97. package/src/ui/dist/assets/figtree-latin-700-normal-M33EANAW.woff2 +0 -0
  98. package/src/ui/dist/assets/figtree-latin-ext-400-normal-CK4ZBFIX.woff2 +0 -0
  99. package/src/ui/dist/assets/figtree-latin-ext-500-normal-M4H6A6MQ.woff2 +0 -0
  100. package/src/ui/dist/assets/figtree-latin-ext-600-normal-KUZFNAIE.woff2 +0 -0
  101. package/src/ui/dist/assets/figtree-latin-ext-700-normal-U3DQVDYX.woff2 +0 -0
  102. package/src/ui/dist/popup.css +1 -0
  103. package/src/ui/dist/popup.js +546 -0
  104. package/src/ui/popup.html +13 -0
  105. package/src/ui/state.js +89 -0
  106. package/src/visual.js +229 -0
@@ -0,0 +1,279 @@
1
+ # The one ManimGL scene Pocket Tutor renders (3b1b/manim, `manimgl`), only for math. It teaches one formula the
2
+ # way 3Blue1Brown does: the formula is written piece by piece, then each part in turn gets its own colour, a
3
+ # brace and a plain-English note while the rest dims, and it ends on one takeaway line with every part still in
4
+ # its colour. The rules it follows are in docs/CLIP_RULES.md; scripts/clip-judge.js checks the frames.
5
+ #
6
+ # The model only fills in a JSON spec; it never writes Python, so nothing it says is run as code. The formula
7
+ # is a small LaTeX subset typeset by matplotlib's mathtext (outlines, no LaTeX install): each part becomes its
8
+ # own path, so it can be coloured and braced on its own. If mathtext can't read it, the formula is drawn as
9
+ # plain Unicode text instead.
10
+ #
11
+ # POCKET_TUTOR_SPEC=spec.json manimgl visual_scene.py Formula -w -r 960x540 --video_dir <dir> --file_name lens --config_file cfg.yml
12
+ #
13
+ # spec.json: {"title": "Cost of one forward pass", "formula": "\\mathcal{O}(N_L(Ld^2 + L^2 d))",
14
+ # "parts": [{"tex": "N_L", "note": "repeated once per layer"}, ...], (1-4 parts, each tex in formula)
15
+ # "takeaway": "Long inputs cost most: L² grows fastest"}
16
+ import json
17
+ import os
18
+ import re
19
+
20
+ import matplotlib
21
+
22
+ matplotlib.use("Agg")
23
+ from matplotlib.font_manager import FontProperties # noqa: E402
24
+ from matplotlib.path import Path # noqa: E402
25
+ from matplotlib.transforms import Affine2D # noqa: E402
26
+ from matplotlib.textpath import TextPath, TextToPath # noqa: E402
27
+ from manimlib import (DOWN, UP, RIGHT, FRAME_WIDTH, GREY_B, FadeIn, FadeOut, GrowFromCenter, LaggedStart, Scene, # noqa: E402
28
+ SVGMobject, Text, VGroup, VMobject, Write)
29
+
30
+ FONT = "Segoe UI" # words; ManimGL's default (Consolas) made the first clips look like a terminal
31
+ COLORS = ["#58C4DD", "#F4D345", "#83C167", "#FC6255"] # 3b1b's blue, yellow, green, red: one per part, kept to the end
32
+ SIZE = 10.0 # mathtext units; the formula is scaled to the frame afterwards
33
+ MATH_FONT = "stix" # STIX sets L²d tight; mathtext's Computer Modern leaves a gap before every superscript
34
+ BINARY = {"+", "-", "=", "\\cdot", "\\times", "\\approx", "\\le", "\\leq", "\\ge", "\\geq", "\\to", "\\propto", "\\neq", "<", ">"}
35
+ MAX_W, MAX_H = 11.5, 2.6 # frame units (the frame is 14.2 × 8): big, but never touching the edges
36
+
37
+
38
+ def load_spec():
39
+ with open(os.environ["POCKET_TUTOR_SPEC"], encoding="utf-8") as f:
40
+ spec = json.load(f)
41
+ clip = lambda s, n: str(s or "").replace("\n", " ").strip()[:n]
42
+ formula = clip(spec.get("formula"), 120)
43
+ parts = [{"tex": clip(p.get("tex") or p.get("text"), 60), "note": clip(p.get("note"), 70)}
44
+ for p in spec.get("parts", []) if isinstance(p, dict)]
45
+ parts = [p for p in parts if p["tex"] and p["tex"] in formula][:4]
46
+ return clip(spec.get("title"), 48), formula, parts, clip(spec.get("takeaway"), 80)
47
+
48
+
49
+ def parses(tex):
50
+ try:
51
+ TextPath((0, 0), f"${tex}$", prop=FontProperties(size=SIZE, math_fontfamily=MATH_FONT))
52
+ return True
53
+ except Exception:
54
+ return False
55
+
56
+
57
+ def split(formula, parts):
58
+ """formula → ordered pieces [(tex, part_index or None)], every piece typesettable on its own.
59
+ A part that can't be cut out cleanly (it would split a \\frac or a brace group) is dropped, not faked."""
60
+ keep = list(parts)
61
+ while True:
62
+ spans, used = [], []
63
+ for i, p in enumerate(keep):
64
+ start = 0
65
+ while True:
66
+ j = formula.find(p["tex"], start)
67
+ if j < 0:
68
+ break
69
+ end = j + len(p["tex"])
70
+ if all(end <= a or j >= b for a, b, _ in spans):
71
+ spans.append((j, end, i))
72
+ break
73
+ start = j + 1
74
+ spans.sort()
75
+ pieces, pos = [], 0
76
+ for a, b, i in spans:
77
+ if formula[pos:a].strip():
78
+ pieces.append((formula[pos:a].strip(), None))
79
+ pieces.append((formula[a:b].strip(), i))
80
+ pos = b
81
+ if formula[pos:].strip():
82
+ pieces.append((formula[pos:].strip(), None))
83
+ pieces = peel(pieces)
84
+ bad = [i for tex, i in pieces if not parses(tex)]
85
+ if not bad:
86
+ return pieces, keep
87
+ cut = next((i for i in bad if i is not None), None)
88
+ if cut is None: # a gap between parts won't parse: give up on cutting at all
89
+ if not keep:
90
+ return [(formula, None)], []
91
+ keep = keep[:-1]
92
+ else:
93
+ keep = [p for k, p in enumerate(keep) if k != cut]
94
+
95
+
96
+ OPEN, CLOSE = "([", ")]"
97
+
98
+
99
+ def peel(pieces):
100
+ """Give each bracket at the edge of an unexplained piece its own piece ("\\mathrm{softmax}(" → two), so
101
+ formula_svg can stretch it to the fraction beside it, as LaTeX's \\left( \\right) would."""
102
+ out = []
103
+ for tex, i in pieces:
104
+ if i is not None:
105
+ out.append((tex, i))
106
+ continue
107
+ head, tail = [], []
108
+ while len(tex) > 1 and tex[0] in CLOSE:
109
+ head.append((tex[0], None)); tex = tex[1:].strip()
110
+ while len(tex) > 1 and tex[-1] in OPEN and not tex.endswith("\\" + tex[-1]):
111
+ tail.insert(0, (tex[-1], None)); tex = tex[:-1].strip()
112
+ out += head + ([(tex, None)] if tex else []) + tail
113
+ return out
114
+
115
+
116
+ def formula_svg(pieces, path):
117
+ """One SVG with one <path> per piece, baselines aligned, so ManimGL sees each piece as its own submobject.
118
+ A lone bracket is stretched to the piece it encloses: plain ( ) stayed short beside QKᵀ/√d_k."""
119
+ prop = FontProperties(size=SIZE, math_fontfamily=MATH_FONT)
120
+ t2p = TextToPath()
121
+ metrics = [t2p.get_text_width_height_descent(f"${tex}$", prop, ismath=True) for tex, _ in pieces]
122
+
123
+ def neighbour(k, step): # the nearest piece that isn't a bracket, looking inwards
124
+ j = k + step
125
+ while 0 <= j < len(pieces) and pieces[j][0] in OPEN + CLOSE:
126
+ j += step
127
+ return metrics[j] if 0 <= j < len(pieces) else None
128
+
129
+ x, out, top, bottom = 0.0, [], 0.0, 0.0
130
+ for k, (tex, _) in enumerate(pieces):
131
+ gap = 0.28 * SIZE if tex in BINARY or (k and pieces[k - 1][0] in BINARY) else 0.02 * SIZE
132
+ if k:
133
+ x += gap
134
+ w, h, d = metrics[k] # h is the full height, d the part below the baseline
135
+ p = TextPath((x, 0), f"${tex}$", prop=prop)
136
+ hi, lo = h - d, -d # the piece's extent above and below the baseline
137
+ nb = neighbour(k, 1 if tex in OPEN else -1) if tex in OPEN + CLOSE else None
138
+ if nb and nb[1] > 1.2 * h:
139
+ s = 1.08 * nb[1] / h # a little taller than what it encloses
140
+ sx = 1 + 0.3 * (s - 1) # and a little wider, as TeX's big delimiters are
141
+ c, cn = (h - 2 * d) / 2, (nb[1] - 2 * nb[2]) / 2 # vertical centres of the bracket and its content
142
+ p = p.transformed(Affine2D().translate(-x, -c).scale(sx, s).translate(x, cn))
143
+ w, hi, lo = w * sx, cn + h * s / 2, cn - h * s / 2
144
+ out.append(svg_d(p))
145
+ top, bottom = max(top, hi), min(bottom, lo)
146
+ x += w
147
+ pad = 0.5
148
+ paths = "".join(f'<path d="{d}" fill="#ffffff"/>' for d in out)
149
+ with open(path, "w", encoding="utf-8") as f:
150
+ f.write(f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="{-pad} {-top - pad} {x + 2 * pad} {top - bottom + 2 * pad}">{paths}</svg>')
151
+
152
+
153
+ def svg_d(p):
154
+ d, i, v, codes = [], 0, p.vertices, p.codes
155
+ while i < len(v):
156
+ c = codes[i]
157
+ if c == Path.MOVETO:
158
+ d.append(f"M{v[i][0]:.3f} {-v[i][1]:.3f}"); i += 1
159
+ elif c == Path.LINETO:
160
+ d.append(f"L{v[i][0]:.3f} {-v[i][1]:.3f}"); i += 1
161
+ elif c == Path.CURVE3:
162
+ d.append(f"Q{v[i][0]:.3f} {-v[i][1]:.3f} {v[i + 1][0]:.3f} {-v[i + 1][1]:.3f}"); i += 2
163
+ elif c == Path.CURVE4:
164
+ d.append(f"C{v[i][0]:.3f} {-v[i][1]:.3f} {v[i + 1][0]:.3f} {-v[i + 1][1]:.3f} {v[i + 2][0]:.3f} {-v[i + 2][1]:.3f}"); i += 3
165
+ else:
166
+ d.append("Z"); i += 1
167
+ return " ".join(d)
168
+
169
+
170
+ def brace(piece, color, floor):
171
+ """3b1b's under-brace, drawn as a curve (ManimGL's Brace needs a LaTeX install). It hangs from the
172
+ formula's bottom line, not the part's: a note under `g` once sat on top of the tall fraction beside it."""
173
+ x0, x1 = piece.get_left()[0] - 0.04, piece.get_right()[0] + 0.04
174
+ y, xm, dep = floor - 0.14, (x0 + x1) / 2, 0.26
175
+ r = min(0.14, (x1 - x0) / 6)
176
+ b = VMobject(stroke_color=color, stroke_width=4)
177
+ b.start_new_path([x0, y, 0])
178
+ b.add_quadratic_bezier_curve_to([x0, y - dep / 2, 0], [x0 + r, y - dep / 2, 0])
179
+ b.add_line_to([xm - r, y - dep / 2, 0])
180
+ b.add_quadratic_bezier_curve_to([xm, y - dep / 2, 0], [xm, y - dep, 0])
181
+ b.add_quadratic_bezier_curve_to([xm, y - dep / 2, 0], [xm + r, y - dep / 2, 0])
182
+ b.add_line_to([x1 - r, y - dep / 2, 0])
183
+ b.add_quadratic_bezier_curve_to([x1, y - dep / 2, 0], [x1, y, 0])
184
+ return b
185
+
186
+
187
+ def words(text, size, color, max_w=12.4):
188
+ t = Text(text, font=FONT, font_size=size).set_color(color) # Text(color=...) is ignored
189
+ if t.get_width() > max_w:
190
+ t.set_width(max_w)
191
+ return t
192
+
193
+
194
+ def inside(m, margin=0.45):
195
+ """Slide m back into the frame. A note centred under a part near the edge once ran off the right side."""
196
+ half = FRAME_WIDTH / 2 - margin
197
+ if m.get_right()[0] > half:
198
+ m.shift((half - m.get_right()[0]) * RIGHT)
199
+ if m.get_left()[0] < -half:
200
+ m.shift((-half - m.get_left()[0]) * RIGHT)
201
+ return m
202
+
203
+
204
+ def repair(formula, parts):
205
+ r"""An unknown command is usually a made-up operator name (\softmax, \argmax): typeset it upright as
206
+ \mathrm{name} instead of giving up on the typesetting. Parts get the same change, so they still match."""
207
+ if parses(formula):
208
+ return formula, parts
209
+ for name in sorted(set(re.findall(r"\\([A-Za-z]+)", formula)), key=len, reverse=True):
210
+ if not (parses(f"\\{name} x") or parses(f"\\{name}{{x}}{{y}}")):
211
+ fix = lambda t: re.sub(rf"\\{name}(?![A-Za-z])", lambda _: f"\\mathrm{{{name}}}", t)
212
+ formula = fix(formula)
213
+ parts = [{**p, "tex": fix(p["tex"])} for p in parts]
214
+ return formula, parts
215
+
216
+
217
+ def unicode_formula(formula):
218
+ """Last resort when mathtext still can't read the formula: readable Unicode, never raw backslashes."""
219
+ s = formula
220
+ for _ in range(3): # \frac{a}{b} → (a)/(b), innermost first
221
+ s = re.sub(r"\\frac\{([^{}]*)\}\{([^{}]*)\}", r"(\1)/(\2)", s)
222
+ s = re.sub(r"\\(?:mathcal|mathrm|mathbf|mathit|mathbb|text|operatorname)\{([^{}]*)\}", r"\1", s)
223
+ for k, v in {r"\cdot": "·", r"\times": "×", r"\sqrt": "√", r"\sum": "Σ", r"\top": "ᵀ", r"\leq": "≤",
224
+ r"\geq": "≥", r"\approx": "≈", r"\alpha": "α", r"\beta": "β", r"\theta": "θ",
225
+ r"\epsilon": "ε", r"\lambda": "λ", r"\sigma": "σ", r"\mu": "μ", r"\pi": "π",
226
+ "^{2}": "²", "^{3}": "³", "^2": "²", "^3": "³", r"^{\top}": "ᵀ"}.items():
227
+ s = s.replace(k, v)
228
+ s = re.sub(r"\\([A-Za-z]+)", r"\1", s) # any other command: its name, upright
229
+ return s.replace("{", "").replace("}", "").replace("\\", "")
230
+
231
+
232
+ class Formula(Scene):
233
+ def construct(self):
234
+ title, formula, parts, takeaway = load_spec()
235
+ if not formula:
236
+ return
237
+ formula, parts = repair(formula, parts)
238
+ pieces, parts = split(formula, parts)
239
+ heading = words(title, 38, GREY_B).to_edge(UP, buff=0.45) if title else None
240
+ if parses(formula):
241
+ svg = os.path.join(os.path.dirname(os.environ["POCKET_TUTOR_SPEC"]), "formula.svg")
242
+ formula_svg(pieces, svg)
243
+ eq = SVGMobject(svg, stroke_width=0, fill_color="#FFFFFF")
244
+ mobs = list(eq.submobjects)
245
+ if len(mobs) != len(pieces): # a piece with no ink (a lone space): can't map parts safely
246
+ mobs, parts = [eq], []
247
+ else:
248
+ eq = words(unicode_formula(formula), 56, "#FFFFFF")
249
+ mobs, parts = [eq], []
250
+ eq.scale(min(MAX_W / eq.get_width(), MAX_H / eq.get_height())) # as big as the frame allows
251
+ eq.move_to(0.55 * UP)
252
+ part_mob = {i: m for m, (_, i) in zip(mobs, pieces) if i is not None} if len(mobs) == len(pieces) else {}
253
+
254
+ # 1. title, then the formula written left to right, one piece at a time
255
+ if heading:
256
+ self.play(FadeIn(heading, shift=0.2 * DOWN), run_time=0.4)
257
+ self.play(LaggedStart(*[Write(m) for m in mobs], lag_ratio=0.55), run_time=min(2.4, 0.6 + 0.3 * len(mobs)))
258
+ self.wait(0.4)
259
+
260
+ # 2. each part in turn: its colour, a brace and a note under it, everything else dimmed
261
+ for k, p in enumerate(parts):
262
+ m = part_mob.get(k)
263
+ if m is None:
264
+ continue
265
+ color = COLORS[k % len(COLORS)]
266
+ others = [o for o in mobs if o is not m]
267
+ b = brace(m, color, eq.get_bottom()[1])
268
+ note = inside(words(p["note"], 40, color).next_to(b, DOWN, buff=0.2)) if p["note"] else None
269
+ self.play(m.animate.set_fill(color, opacity=1), *[o.animate.set_fill(opacity=0.3) for o in others],
270
+ GrowFromCenter(b), *([FadeIn(note, shift=0.15 * UP)] if note else []), run_time=0.7)
271
+ self.wait(1.2 + 0.035 * len(p["note"]))
272
+ self.play(FadeOut(b), *([FadeOut(note)] if note else []), run_time=0.35)
273
+
274
+ # 3. everything back, each part still in its colour, and the one line to remember
275
+ self.play(*[o.animate.set_fill(opacity=1) for o in mobs], run_time=0.4)
276
+ if takeaway:
277
+ line = words(takeaway, 40, "#FFFFFF").to_edge(DOWN, buff=0.7)
278
+ self.play(FadeIn(line, shift=0.15 * UP), run_time=0.5)
279
+ self.wait(2.0 if parts else 3.5) # with no parts to explain, hold longer so the loop isn't frantic
@@ -0,0 +1,18 @@
1
+ /**
2
+ * @generated by `astryx theme` — do not edit manually.
3
+ * @astryx-theme-record {"themes":{"lens":"./src/themes"},"defaultThemeSlug":"lens"}
4
+ */
5
+
6
+ import {lensTheme as _astryxTheme0} from "./themes/lens/lens.js";
7
+ import "./themes/lens/lens.css";
8
+ import "./themes/lens/lens.fonts.css";
9
+
10
+ export const themes = {
11
+ "lens": _astryxTheme0,
12
+ };
13
+
14
+ export const defaultThemeSlug = "lens";
15
+
16
+ export const themeModes = {
17
+ "lens": "dark",
18
+ };
package/src/browser.js ADDED
@@ -0,0 +1,38 @@
1
+ // Opens links in a new Chrome window (falls back to the default browser), and code hits in VS Code.
2
+ const fs = require('fs')
3
+ const path = require('path')
4
+ const { spawn } = require('child_process')
5
+
6
+ function findChrome(configured) {
7
+ const candidates = [configured,
8
+ path.join(process.env.PROGRAMFILES || 'C:\\Program Files', 'Google', 'Chrome', 'Application', 'chrome.exe'),
9
+ path.join(process.env['PROGRAMFILES(X86)'] || 'C:\\Program Files (x86)', 'Google', 'Chrome', 'Application', 'chrome.exe'),
10
+ path.join(process.env.LOCALAPPDATA || '', 'Google', 'Chrome', 'Application', 'chrome.exe')]
11
+ return candidates.find((p) => p && fs.existsSync(p)) || null
12
+ }
13
+
14
+ const isWeb = (url) => /^https?:\/\//i.test(String(url || ''))
15
+
16
+ function openUrl(url, cfg, shell) {
17
+ if (!isWeb(url)) return false
18
+ const chrome = findChrome(cfg.browser)
19
+ if (chrome) {
20
+ const child = spawn(chrome, ['--new-window', url], { detached: true, stdio: 'ignore', windowsHide: false })
21
+ child.on('error', () => shell.openExternal(url))
22
+ child.unref()
23
+ } else {
24
+ shell.openExternal(url)
25
+ }
26
+ return true
27
+ }
28
+
29
+ // vscode://file/C:/path/file.js:12 opens the file at that line in VS Code
30
+ function openInEditor(root, file, line, shell) {
31
+ if (!root || !file) return false
32
+ const full = path.resolve(root, file)
33
+ if (!full.startsWith(path.resolve(root) + path.sep)) return false
34
+ shell.openExternal(`vscode://file/${full.replace(/\\/g, '/')}:${Number(line) || 1}`)
35
+ return true
36
+ }
37
+
38
+ module.exports = { openUrl, openInEditor, findChrome, isWeb }
package/src/config.js ADDED
@@ -0,0 +1,84 @@
1
+ // Settings: ~/.pocket-tutor/config.json, then environment variables for the keys.
2
+ // No Electron here, so scripts/doctor.js and the tests can use it too.
3
+ const fs = require('fs')
4
+ const os = require('os')
5
+ const path = require('path')
6
+
7
+ const HOME = process.env.POCKET_TUTOR_HOME || path.join(os.homedir(), '.pocket-tutor')
8
+ // settings from the first release (named explain-lens) move over once
9
+ if (!process.env.POCKET_TUTOR_HOME) {
10
+ const old = path.join(os.homedir(), '.explain-lens')
11
+ try { if (fs.existsSync(old) && !fs.existsSync(HOME)) fs.cpSync(old, HOME, { recursive: true }) } catch { /* start fresh */ }
12
+ }
13
+ const FILE = path.join(HOME, 'config.json')
14
+ const GRAPH = path.join(HOME, 'graph.json')
15
+
16
+ // Any OpenAI-compatible endpoint works. The default is NVIDIA's Nemotron 3.5 Lightning through Vercel's
17
+ // AI Gateway, free as `nvidia/nemotron-3.5-lightning-free` (key: AI_GATEWAY_API_KEY). Gemini and Groq stay as
18
+ // presets for when only their key is set. The popup never names the model.
19
+ const PROVIDERS = {
20
+ vercel: { base_url: 'https://ai-gateway.vercel.sh/v1', model: 'nvidia/nemotron-3.5-lightning-free', plan_model: 'nvidia/nemotron-3.5-lightning-free', fallback_model: null },
21
+ // fallback_model answers when the main model says it is busy (Hydrogen often is, right after launch)
22
+ // the plan is only a search query, so the fast lite model does it; Hydrogen writes the answer
23
+ gemini: { base_url: 'https://generativelanguage.googleapis.com/v1beta/openai', model: 'gemini-4-hydrogen', plan_model: 'gemini-flash-lite-latest', fallback_model: 'gemini-flash-lite-latest' },
24
+ groq: { base_url: 'https://api.groq.com/openai/v1', model: 'openai/gpt-oss-120b', plan_model: 'openai/gpt-oss-20b', fallback_model: null },
25
+ // Any OpenAI-compatible server works through these presets or through base_url + llm_api_key. Change `model` freely.
26
+ openai: { base_url: 'https://api.openai.com/v1', model: 'gpt-4o-mini', plan_model: 'gpt-4o-mini', fallback_model: null },
27
+ openrouter: { base_url: 'https://openrouter.ai/api/v1', model: 'openai/gpt-4o-mini', plan_model: 'openai/gpt-4o-mini', fallback_model: null },
28
+ ollama: { base_url: 'http://localhost:11434/v1', model: 'llama3.2', plan_model: 'llama3.2', fallback_model: null }, // local, no key
29
+ }
30
+
31
+ const DEFAULTS = {
32
+ hotkey: 'CommandOrControl+Alt+Space',
33
+ provider: 'vercel',
34
+ ...PROVIDERS.vercel,
35
+ // where to look for a project folder when the editor's title only gives its name
36
+ roots: ['C:\\Projects'],
37
+ browser: null, // path to chrome.exe; found automatically when null
38
+ max_snippets: 6,
39
+ web_results: 5,
40
+ visuals: true, // for math only: a short ManimGL clip of the formula (pocket-tutor setup-visuals)
41
+ remember: true, // keep the context graph in ~/.pocket-tutor/graph.json
42
+ }
43
+
44
+ // A server on this machine needs no key (Ollama, LM Studio, llama.cpp, vLLM).
45
+ const isLocal = (url) => /^https?:\/\/(localhost|127\.0\.0\.1|\[::1\])(:|\/|$)/i.test(String(url || ''))
46
+
47
+ // file settings + environment → the settings the app uses. Pure, so tests can pass their own env.
48
+ // Provider order when none is named: your own endpoint (POCKET_TUTOR_BASE_URL or OPENAI_BASE_URL), then the
49
+ // first key found: Vercel, OpenAI, OpenRouter, Gemini, Groq.
50
+ function resolve(file = {}, env = {}) {
51
+ const keys = {
52
+ vercel: file.vercel_api_key || env.AI_GATEWAY_API_KEY || '',
53
+ openai: file.openai_api_key || env.OPENAI_API_KEY || '',
54
+ openrouter: file.openrouter_api_key || env.OPENROUTER_API_KEY || '',
55
+ gemini: file.gemini_api_key || env.GEMINI_API_KEY || env.GOOGLE_API_KEY || '',
56
+ groq: file.groq_api_key || env.GROQ_API_KEY || '',
57
+ }
58
+ const custom = file.llm_api_key || env.POCKET_TUTOR_LLM_KEY || ''
59
+ const baseUrl = file.base_url || env.POCKET_TUTOR_BASE_URL || env.OPENAI_BASE_URL || ''
60
+ const named = file.provider || env.POCKET_TUTOR_PROVIDER || ''
61
+ const firstKey = Object.keys(keys).find((p) => keys[p])
62
+ // a base_url of your own beats the presets: OPENAI_API_KEY + OPENAI_BASE_URL is the usual way to point at another server
63
+ const provider = named || (baseUrl ? 'custom' : firstKey || 'vercel')
64
+ const cfg = { ...DEFAULTS, ...(PROVIDERS[provider] || {}), ...file, provider }
65
+ if (baseUrl) cfg.base_url = baseUrl
66
+ const model = file.model || env.POCKET_TUTOR_MODEL
67
+ if (model) { cfg.model = model; cfg.plan_model = file.plan_model || env.POCKET_TUTOR_PLAN_MODEL || model; cfg.fallback_model = null }
68
+ cfg.llm_key = custom || keys[provider] || (provider === 'custom' ? env.OPENAI_API_KEY || '' : '') || (isLocal(cfg.base_url) ? 'local' : '')
69
+ // Brave is optional: without it, search goes through DuckDuckGo and Wikipedia with no key
70
+ cfg.brave_key = file.brave_api_key || env.BRAVE_API_KEY || env.BRAVE_SEARCH_API_KEY || ''
71
+ // Search engines: duckduckgo (no key, the default), brave (key), searxng (your own instance).
72
+ cfg.searxng_url = file.searxng_url || env.SEARXNG_URL || ''
73
+ cfg.search_engine = file.search_engine || env.POCKET_TUTOR_SEARCH ||
74
+ (cfg.brave_key ? 'brave' : cfg.searxng_url ? 'searxng' : 'duckduckgo')
75
+ return cfg
76
+ }
77
+
78
+ function load() {
79
+ let file = {}
80
+ try { file = JSON.parse(fs.readFileSync(FILE, 'utf8')) } catch { /* no config yet: defaults and env */ }
81
+ return resolve(file, process.env)
82
+ }
83
+
84
+ module.exports = { load, resolve, isLocal, HOME, FILE, GRAPH, DEFAULTS, PROVIDERS }
package/src/graph.js ADDED
@@ -0,0 +1,114 @@
1
+ // The context graph: what you have looked up before, kept only on this laptop (~/.pocket-tutor/graph.json).
2
+ //
3
+ // concept ──related── concept "RMSNorm" ── "LayerNorm"
4
+ // concept ──seen_in── file (line) "RMSNorm" ── my-project/src/model/norm.py:7
5
+ // file ──part_of── project norm.py ── C:\Projects\my-project
6
+ //
7
+ // Each lookup adds to it (remember). Before the next answer, recall() finds the concepts the selection
8
+ // mentions, walks one step to their neighbours, and hands the model a few short lines: what you were told
9
+ // before, what it connects to, and where it sits in your code. That's the "RAG" part, with no vector store.
10
+ // Everything here except load/save is pure, so test/pure.test.js drives it with an in-memory graph.
11
+ const fs = require('fs')
12
+ const path = require('path')
13
+
14
+ const MAX_NODES = 3000
15
+ const empty = () => ({ version: 1, nodes: {}, edges: [] })
16
+ const norm = (s) => String(s || '').replace(/\s+/g, ' ').trim()
17
+ const keyOf = (type, label) => `${type}:${norm(label).toLowerCase()}`
18
+
19
+ function upsert(g, type, label, extra = {}, now = Date.now()) {
20
+ const id = keyOf(type, label)
21
+ const n = g.nodes[id] || (g.nodes[id] = { type, label: norm(label), count: 0 })
22
+ Object.assign(n, extra, { last: now })
23
+ return n
24
+ }
25
+
26
+ function link(g, a, rel, b, line = null) {
27
+ if (a === b) return
28
+ const e = g.edges.find((x) => x.rel === rel && ((x.a === a && x.b === b) || (rel === 'related' && x.a === b && x.b === a)))
29
+ if (e) { if (line) e.line = line; return }
30
+ g.edges.push(line ? { a, rel, b, line } : { a, rel, b })
31
+ }
32
+
33
+ // one lookup → the graph. lookup: { concept, summary, related[], files: [{file, line}], root }
34
+ function remember(g, lookup, now = Date.now()) {
35
+ const concept = norm(lookup.concept).slice(0, 80)
36
+ if (!concept) return g
37
+ const c = upsert(g, 'concept', concept, lookup.summary ? { summary: norm(lookup.summary).slice(0, 240) } : {}, now)
38
+ c.count++
39
+ const cid = keyOf('concept', concept)
40
+ for (const r of (lookup.related || []).slice(0, 6)) {
41
+ const label = norm(r).slice(0, 80)
42
+ if (!label || label.toLowerCase() === concept.toLowerCase()) continue
43
+ upsert(g, 'concept', label, {}, now)
44
+ link(g, cid, 'related', keyOf('concept', label))
45
+ }
46
+ if (lookup.root) {
47
+ upsert(g, 'project', lookup.root, { name: path.basename(lookup.root) }, now)
48
+ for (const f of (lookup.files || []).slice(0, 4)) {
49
+ const fileLabel = `${lookup.root}|${f.file}`
50
+ upsert(g, 'file', fileLabel, { file: f.file, root: lookup.root }, now)
51
+ link(g, cid, 'seen_in', keyOf('file', fileLabel), f.line || null)
52
+ link(g, keyOf('file', fileLabel), 'part_of', keyOf('project', lookup.root))
53
+ }
54
+ }
55
+ return prune(g)
56
+ }
57
+
58
+ // keep the graph small: drop the least used, oldest nodes and their edges
59
+ function prune(g, max = MAX_NODES) {
60
+ const ids = Object.keys(g.nodes)
61
+ if (ids.length <= max) return g
62
+ const drop = new Set(ids.sort((a, b) => (g.nodes[a].count - g.nodes[b].count) || (g.nodes[a].last - g.nodes[b].last)).slice(0, ids.length - max))
63
+ for (const id of drop) delete g.nodes[id]
64
+ g.edges = g.edges.filter((e) => !drop.has(e.a) && !drop.has(e.b))
65
+ return g
66
+ }
67
+
68
+ const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
69
+
70
+ // the selection → a few lines of what the graph already knows. root: the current project, preferred.
71
+ function recall(g, text, root = null, limit = 6) {
72
+ const hay = ` ${norm(text).toLowerCase()} `
73
+ const hits = Object.entries(g.nodes)
74
+ .filter(([, n]) => n.type === 'concept' && n.label.length >= 2 &&
75
+ new RegExp(`(^|[^a-z0-9_])${escapeRe(n.label.toLowerCase())}($|[^a-z0-9_])`).test(hay))
76
+ .sort((a, b) => b[1].label.length - a[1].label.length || b[1].count - a[1].count)
77
+ .slice(0, limit)
78
+ const lines = []
79
+ for (const [id, n] of hits) {
80
+ const near = g.edges.filter((e) => e.a === id || e.b === id)
81
+ const related = near.filter((e) => e.rel === 'related').map((e) => g.nodes[e.a === id ? e.b : e.a]).filter(Boolean).map((x) => x.label)
82
+ const files = near.filter((e) => e.rel === 'seen_in').map((e) => ({ f: g.nodes[e.b], line: e.line }))
83
+ .filter((x) => x.f && (!root || x.f.root === root)).map((x) => `${x.f.file}${x.line ? `:${x.line}` : ''}`)
84
+ const bits = [n.summary ? `${n.label}: ${n.summary}` : n.label]
85
+ if (related.length) bits.push(`connects to ${related.slice(0, 5).join(', ')}`)
86
+ if (files.length) bits.push(`seen in this project at ${files.slice(0, 3).join(', ')}`)
87
+ lines.push(`- ${bits.join('; ')}`)
88
+ }
89
+ return lines
90
+ }
91
+
92
+ // the first sentence of an answer, without Markdown, as the concept's short summary
93
+ function summaryOf(answer) {
94
+ const plain = String(answer || '').replace(/```[\s\S]*?```/g, ' ').replace(/[*_`#>]/g, '').replace(/\s+/g, ' ').trim()
95
+ const m = /^(.{20,240}?[.!?])(\s|$)/.exec(plain)
96
+ return (m ? m[1] : plain.slice(0, 240)).trim()
97
+ }
98
+
99
+ function load(file) {
100
+ try {
101
+ const g = JSON.parse(fs.readFileSync(file, 'utf8'))
102
+ return g && g.nodes && Array.isArray(g.edges) ? g : empty()
103
+ } catch { return empty() }
104
+ }
105
+
106
+ // write to a temp file, then rename, so a crash never leaves half a graph
107
+ function save(file, g) {
108
+ fs.mkdirSync(path.dirname(file), { recursive: true })
109
+ const tmp = `${file}.tmp`
110
+ fs.writeFileSync(tmp, JSON.stringify(g))
111
+ fs.renameSync(tmp, file)
112
+ }
113
+
114
+ module.exports = { empty, remember, recall, summaryOf, prune, load, save, keyOf }
package/src/helper.ps1 ADDED
@@ -0,0 +1,67 @@
1
+ # Pocket Tutor's hands. Started once by native.js and kept running, so the Win32 code below compiles only once.
2
+ # Reads one command per line on stdin, answers one JSON line on stdout:
3
+ # fg -> {"app": "...", "title": "...", "pid": n} the window you were in when you pressed the hotkey
4
+ # copy -> {"ok": true} waits until you let go of Shift/Alt/Win/Space, then presses Ctrl+C
5
+ # copyterminal -> {"ok": true} the same with Ctrl+Shift+C, because Ctrl+C in a terminal stops the running program
6
+ # It never reads the clipboard or writes anything to disk; main.js does the clipboard.
7
+
8
+ [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
9
+ Add-Type @"
10
+ using System;
11
+ using System.Runtime.InteropServices;
12
+ using System.Text;
13
+ using System.Threading;
14
+ public static class LensWin {
15
+ [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
16
+ [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid);
17
+ [DllImport("user32.dll", CharSet=CharSet.Unicode)] public static extern int GetWindowText(IntPtr h, StringBuilder s, int n);
18
+ [DllImport("user32.dll")] public static extern short GetAsyncKeyState(int vk);
19
+ [DllImport("user32.dll")] public static extern void keybd_event(byte vk, byte scan, uint flags, UIntPtr extra);
20
+ const uint UP = 0x0002;
21
+ public static string Title(IntPtr h) { var s = new StringBuilder(512); GetWindowText(h, s, 512); return s.ToString(); }
22
+ static bool Down(int vk) { return (GetAsyncKeyState(vk) & 0x8000) != 0; }
23
+ // Shift, Alt, left/right Win, Space: wait (at most 1.5 s) so they don't turn Ctrl+C into another shortcut
24
+ public static void WaitForRelease() {
25
+ for (int i = 0; i < 75; i++) {
26
+ if (!Down(0x10) && !Down(0x12) && !Down(0x5B) && !Down(0x5C) && !Down(0x20)) return;
27
+ Thread.Sleep(20);
28
+ }
29
+ }
30
+ public static void Copy(bool terminal) {
31
+ WaitForRelease();
32
+ keybd_event(0x11, 0, 0, UIntPtr.Zero); // Ctrl down
33
+ if (terminal) keybd_event(0x10, 0, 0, UIntPtr.Zero); // Shift down
34
+ keybd_event(0x43, 0, 0, UIntPtr.Zero); // C
35
+ keybd_event(0x43, 0, UP, UIntPtr.Zero);
36
+ if (terminal) keybd_event(0x10, 0, UP, UIntPtr.Zero);
37
+ keybd_event(0x11, 0, UP, UIntPtr.Zero);
38
+ }
39
+ }
40
+ "@
41
+
42
+ [Console]::Out.WriteLine('{"ready":true}')
43
+ [Console]::Out.Flush()
44
+ while ($true) {
45
+ $cmd = [Console]::In.ReadLine()
46
+ if ($null -eq $cmd) { break }
47
+ $cmd = $cmd.Trim()
48
+ try {
49
+ if ($cmd -eq 'fg') {
50
+ $h = [LensWin]::GetForegroundWindow()
51
+ $procId = [uint32]0
52
+ [void][LensWin]::GetWindowThreadProcessId($h, [ref]$procId)
53
+ $name = ''
54
+ try { $name = (Get-Process -Id $procId -ErrorAction Stop).ProcessName } catch {}
55
+ $out = @{ app = $name.ToLower(); title = [LensWin]::Title($h); pid = $procId } | ConvertTo-Json -Compress
56
+ } elseif ($cmd -eq 'copy' -or $cmd -eq 'copyterminal') {
57
+ [LensWin]::Copy($cmd -eq 'copyterminal')
58
+ $out = '{"ok":true}'
59
+ } else {
60
+ $out = (@{ error = "unknown command: $cmd" } | ConvertTo-Json -Compress)
61
+ }
62
+ } catch {
63
+ $out = (@{ error = $_.Exception.Message } | ConvertTo-Json -Compress)
64
+ }
65
+ [Console]::Out.WriteLine($out)
66
+ [Console]::Out.Flush()
67
+ }