AskTim 0.1.0__py3-none-any.whl

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.
asktim/render.py ADDED
@@ -0,0 +1,511 @@
1
+ """Printing to the terminal: answers as they stream in (light Markdown), notes, questions.
2
+
3
+ Code blocks are printed without any border, so that a command can be copied and pasted
4
+ straight from the answer. Colour is used when the output is a terminal (and NO_COLOR is not
5
+ set); piped output stays plain Markdown.
6
+ """
7
+
8
+ import os
9
+ import re
10
+ import shutil
11
+ import sys
12
+
13
+ STYLES = {
14
+ "bold": "1", "dim": "2", "italic": "3", "underline": "4", "red": "31", "green": "32", "yellow": "33",
15
+ "blue": "34", "magenta": "35", "cyan": "36", "gray": "90", "bright": "97",
16
+ }
17
+
18
+
19
+ def _supports_color(stream, setting="auto"):
20
+ if setting == "always":
21
+ return True
22
+ if setting == "never" or os.environ.get("NO_COLOR"):
23
+ return False
24
+ if os.environ.get("FORCE_COLOR"):
25
+ return True
26
+ try:
27
+ if not stream.isatty():
28
+ return False
29
+ except Exception:
30
+ return False
31
+ if os.name == "nt":
32
+ try:
33
+ os.system("") # turns on ANSI escape codes in the Windows console
34
+ except Exception:
35
+ return False
36
+ return os.environ.get("TERM") != "dumb"
37
+
38
+
39
+ def _unicode_ok(stream):
40
+ enc = (getattr(stream, "encoding", None) or "").lower()
41
+ return "utf" in enc
42
+
43
+
44
+ class Term(object):
45
+ def __init__(self, color="auto", stream=None, err=None):
46
+ self.out = stream or sys.stdout
47
+ self.err = err or sys.stderr
48
+ self.color = _supports_color(self.out, color)
49
+ self.uni = _unicode_ok(self.out)
50
+
51
+ # -- basics -------------------------------------------------------------------------------
52
+
53
+ def s(self, text, *styles):
54
+ if not self.color or not styles:
55
+ return text
56
+ codes = ";".join(STYLES[x] for x in styles if x in STYLES)
57
+ return "\x1b[%sm%s\x1b[0m" % (codes, text)
58
+
59
+ def write(self, text):
60
+ try:
61
+ self.out.write(text)
62
+ except UnicodeEncodeError:
63
+ self.out.write(text.encode("ascii", "replace").decode("ascii"))
64
+ self.out.flush()
65
+
66
+ def line(self, text=""):
67
+ self.write(text + "\n")
68
+
69
+ def width(self):
70
+ try:
71
+ return max(40, min(100, shutil.get_terminal_size((80, 24)).columns))
72
+ except Exception:
73
+ return 80
74
+
75
+ def rule(self, title="", style="gray"):
76
+ ch = "─" if self.uni else "-"
77
+ w = self.width()
78
+ if title:
79
+ t = " %s " % title
80
+ self.line(self.s(ch * 2 + t + ch * max(2, w - len(t) - 2), style))
81
+ else:
82
+ self.line(self.s(ch * w, style))
83
+
84
+ def note(self, text):
85
+ self.line(self.s(text, "gray"))
86
+
87
+ def info(self, text):
88
+ self.line(self.s(text, "cyan"))
89
+
90
+ def good(self, text):
91
+ self.line(self.s(text, "green"))
92
+
93
+ def warn(self, text):
94
+ self.line(self.s(text, "yellow"))
95
+
96
+ def error(self, text):
97
+ self.line(self.s(text, "red"))
98
+
99
+ def bullet(self):
100
+ return "•" if self.uni else "-"
101
+
102
+ # -- asking ---------------------------------------------------------------------------------
103
+
104
+ def interactive(self):
105
+ try:
106
+ return sys.stdin.isatty()
107
+ except Exception:
108
+ return False
109
+
110
+ def ask(self, prompt, default=""):
111
+ try:
112
+ ans = input(self.s(prompt, "bold"))
113
+ except EOFError:
114
+ return None
115
+ return ans.strip() if ans.strip() else default
116
+
117
+ def edit(self, prompt, text):
118
+ """Let the student change a line of text (pre-filled where readline allows)."""
119
+ if "\n" not in text:
120
+ try:
121
+ import readline # noqa: F401 (gives input() line editing)
122
+
123
+ def hook():
124
+ readline.insert_text(text)
125
+ readline.redisplay()
126
+
127
+ readline.set_startup_hook(hook)
128
+ try:
129
+ return input(prompt)
130
+ finally:
131
+ readline.set_startup_hook()
132
+ except (ImportError, AttributeError):
133
+ pass
134
+ editor = os.environ.get("VISUAL") or os.environ.get("EDITOR")
135
+ if editor and shutil.which(editor.split()[0]):
136
+ import subprocess
137
+ import tempfile
138
+
139
+ with tempfile.NamedTemporaryFile("w", suffix=".sh", delete=False) as f:
140
+ f.write(text)
141
+ path = f.name
142
+ try:
143
+ subprocess.call(editor.split() + [path])
144
+ with open(path) as f:
145
+ return f.read().rstrip("\n")
146
+ finally:
147
+ os.unlink(path)
148
+ self.line(self.s("Type the new version (one line); press Enter alone to keep it as it is:", "gray"))
149
+ ans = input(prompt)
150
+ return ans if ans.strip() else text
151
+
152
+ # -- streaming Markdown ---------------------------------------------------------------------
153
+
154
+ def markdown(self):
155
+ return MarkdownStream(self)
156
+
157
+
158
+ # C0/C1 control characters (but not tab and newline), and the invisible characters that can reorder
159
+ # or hide text on screen (bidirectional overrides, zero-width space, byte-order mark)
160
+ _CTRL = re.compile("[\x00-\x08\x0b-\x1f\x7f-\x9f\u200b\u200e\u200f\u202a-\u202e\u2066-\u2069\ufeff]")
161
+
162
+
163
+ def _shown(ch):
164
+ o = ord(ch)
165
+ if o < 0x80:
166
+ return "^" + chr((o + 64) % 128)
167
+ return "\\x%02x" % o if o < 0x100 else "\\u%04x" % o
168
+
169
+
170
+ def visible(text):
171
+ """Control characters (escape codes, carriage returns ...) written as ^X.
172
+
173
+ Text that came from the AI goes through this before it reaches the terminal, so it cannot move the
174
+ cursor, recolour or overwrite what is on the screen: what the student reads is what will run.
175
+ """
176
+ if not text:
177
+ return text
178
+ return _CTRL.sub(lambda m: _shown(m.group()), text)
179
+
180
+
181
+ class MarkdownStream(object):
182
+ """Prints Markdown as it arrives, character by character, with light styling."""
183
+
184
+ def __init__(self, term):
185
+ self.t = term
186
+ self.raw = []
187
+ self.line_start = True
188
+ self.pending = ""
189
+ self.in_code = False
190
+ self.code_lang = ""
191
+ self.code_buf = []
192
+ self.blocks = [] # (language, code) of every code block
193
+ self.inline_code = False
194
+ self.bold = False
195
+ self.star = False
196
+ self.heading = False
197
+ self.styled = term.color
198
+ self._segs = []
199
+
200
+ def feed(self, text):
201
+ if not text:
202
+ return
203
+ text = visible(text.replace("\r", ""))
204
+ self.raw.append(text)
205
+ if not self.styled:
206
+ self.t.write(text)
207
+ self._track_blocks_plain(text)
208
+ return
209
+ for ch in text:
210
+ self._char(ch)
211
+ self._flush()
212
+
213
+ def _track_blocks_plain(self, text):
214
+ # keep the code blocks also when printing plain text
215
+ for ch in text:
216
+ if self.line_start:
217
+ self.pending += ch
218
+ if ch == "\n" or len(self.pending) > 200:
219
+ ln = self.pending
220
+ self.pending = ""
221
+ self._plain_line(ln)
222
+ self.line_start = True
223
+ continue
224
+
225
+ def _plain_line(self, ln):
226
+ s = ln.strip()
227
+ if s.startswith("```") or s.startswith("~~~"):
228
+ if self.in_code:
229
+ self.blocks.append((self.code_lang, "".join(self.code_buf).rstrip("\n")))
230
+ self.in_code = False
231
+ self.code_buf = []
232
+ else:
233
+ self.in_code = True
234
+ self.code_lang = s[3:].strip().split()[0].lower() if s[3:].strip() else ""
235
+ elif self.in_code:
236
+ self.code_buf.append(ln)
237
+
238
+ def _out(self, text, *styles):
239
+ if self._segs and self._segs[-1][1] == styles:
240
+ self._segs[-1][0].append(text)
241
+ else:
242
+ self._segs.append(([text], styles))
243
+
244
+ def _flush(self):
245
+ if self._segs:
246
+ self.t.write("".join(self.t.s("".join(parts), *st) if st else "".join(parts) for parts, st in self._segs))
247
+ self._segs = []
248
+
249
+ def _char(self, ch):
250
+ if self.line_start:
251
+ self.pending += ch
252
+ p = self.pending
253
+ stripped = p.lstrip(" ")
254
+ if ch == "\n":
255
+ self._decide_line(final=True)
256
+ return
257
+ # wait until the start of the line tells what it is
258
+ if stripped in ("", "`", "``", "~", "~~", "#", "##", "###", "####", "-", "*", "+") or (stripped[:3] in ("```", "~~~")):
259
+ if stripped[:3] in ("```", "~~~"):
260
+ return # a fence line: wait for its end
261
+ if len(p) < 8:
262
+ return
263
+ self._decide_line()
264
+ return
265
+ self._body_char(ch)
266
+
267
+ def _decide_line(self, final=False):
268
+ p = self.pending
269
+ self.pending = ""
270
+ stripped = p.lstrip(" ")
271
+ if stripped[:3] in ("```", "~~~"):
272
+ if p.endswith("\n") or final:
273
+ self._fence(stripped.strip())
274
+ self.line_start = True
275
+ return
276
+ if self.in_code:
277
+ self.line_start = False
278
+ self.code_buf.append("")
279
+ for ch in p:
280
+ self._body_char(ch)
281
+ return
282
+ self.line_start = False
283
+ m = re.match(r"^(#{1,4})\s+", stripped)
284
+ if m:
285
+ self.heading = True
286
+ rest = stripped[m.end():]
287
+ for ch in rest:
288
+ self._body_char(ch)
289
+ return
290
+ m = re.match(r"^([-*+])\s", stripped)
291
+ if m:
292
+ indent = p[: len(p) - len(stripped)]
293
+ self._out(indent + self.t.bullet() + " ")
294
+ for ch in stripped[2:]:
295
+ self._body_char(ch)
296
+ return
297
+ for ch in p:
298
+ self._body_char(ch)
299
+
300
+ def _fence(self, line):
301
+ if not self.in_code:
302
+ self.in_code = True
303
+ self.code_lang = line[3:].strip().split()[0].lower() if line[3:].strip() else ""
304
+ self.code_buf = []
305
+ label = self.code_lang or "code"
306
+ self._out(("┄┄ %s ┄┄" if self.t.uni else "-- %s --") % label, "gray")
307
+ self._out("\n")
308
+ else:
309
+ self.in_code = False
310
+ self.blocks.append((self.code_lang, "".join(self.code_buf).rstrip("\n")))
311
+ self.code_buf = []
312
+ self._out("┄┄" if self.t.uni else "--", "gray")
313
+ self._out("\n")
314
+
315
+ def _body_char(self, ch):
316
+ if ch == "\n":
317
+ if self.star:
318
+ self._emit("*")
319
+ self.star = False
320
+ self._out("\n")
321
+ if self.in_code:
322
+ if self.code_buf:
323
+ self.code_buf[-1] += "\n"
324
+ self.line_start = True
325
+ self.heading = False
326
+ self.inline_code = False
327
+ self.bold = False
328
+ return
329
+ if self.in_code:
330
+ if self.code_buf:
331
+ self.code_buf[-1] += ch
332
+ else:
333
+ self.code_buf.append(ch)
334
+ self._out(ch, "green")
335
+ return
336
+ if ch == "`":
337
+ if self.star:
338
+ self._emit("*")
339
+ self.star = False
340
+ self.inline_code = not self.inline_code
341
+ return
342
+ if self.inline_code:
343
+ self._out(ch, "cyan")
344
+ return
345
+ if ch == "*":
346
+ if self.star:
347
+ self.star = False
348
+ self.bold = not self.bold
349
+ return
350
+ self.star = True
351
+ return
352
+ if self.star:
353
+ self.star = False
354
+ self._emit("*")
355
+ self._emit(ch)
356
+
357
+ def _emit(self, ch):
358
+ styles = []
359
+ if self.bold or self.heading:
360
+ styles.append("bold")
361
+ self._out(ch, *styles)
362
+
363
+ def close(self):
364
+ if self.pending:
365
+ if self.styled:
366
+ self._decide_line(final=True)
367
+ else:
368
+ self._plain_line(self.pending)
369
+ self.pending = ""
370
+ if self.in_code:
371
+ self.blocks.append((self.code_lang, "".join(self.code_buf).rstrip("\n")))
372
+ self.in_code = False
373
+ if self.styled:
374
+ self._out("\n")
375
+ self._flush()
376
+ text = "".join(self.raw)
377
+ if text and not text.endswith("\n"):
378
+ self.t.write("\n")
379
+ return text
380
+
381
+
382
+ def code_blocks(markdown):
383
+ """(language, code) for each fenced block of a Markdown text."""
384
+ out = []
385
+ for m in re.finditer(r"^[ \t]*(```|~~~)[ \t]*([\w+#.\-]*)[^\n]*\n(.*?)^[ \t]*\1[ \t]*$", markdown or "", re.S | re.M):
386
+ out.append((m.group(2).lower(), m.group(3).rstrip("\n")))
387
+ return out
388
+
389
+
390
+ # -----------------------------------------------------------------------------------------------
391
+ # Markdown from the AI, made safe for a notebook
392
+ # -----------------------------------------------------------------------------------------------
393
+
394
+ _SAFE_SCHEMES = ("http", "https", "mailto")
395
+ _FENCE = re.compile(r"^([ \t]*)(`{3,}|~{3,})(.*)$")
396
+ # MathJax commands that can make links, load extensions or change styles
397
+ _MATHJAX = re.compile(r"\\(href|url|require|class|cssId|style|html|unicode|data|attr)(?![A-Za-z])")
398
+
399
+
400
+ def _escape_text(s):
401
+ """A line of Markdown text with raw HTML made inert: & < " ' become entities, links that are not
402
+ http(s) or mailto stop being links, and MathJax commands that could make links are broken up."""
403
+ # quotes too: some Markdown parsers copy an image's text into its alt="..." unescaped
404
+ s = s.replace("&", "&amp;").replace("<", "&lt;").replace('"', "&quot;").replace("'", "&#39;")
405
+
406
+ # every "](" is looked at (they may nest), and those whose destination is not http(s), mailto or
407
+ # a relative path - or is on the next line, where it cannot be checked here - lose their "("
408
+ out, i = [], 0
409
+ while True:
410
+ j = s.find("](", i)
411
+ if j < 0:
412
+ break
413
+ d = re.sub(r"^\s*(?:&lt;)?\s*", "", s[j + 2:]).lower()
414
+ sm = re.match(r"([a-z][a-z0-9+.\-]*):", d)
415
+ out.append(s[i:j])
416
+ out.append("]&#40;" if (not d or (sm and sm.group(1) not in _SAFE_SCHEMES)) else "](")
417
+ i = j + 2
418
+ out.append(s[i:])
419
+ s = "".join(out)
420
+ # link reference definitions ([id]: url), which may sit in a list or a quote and may have their
421
+ # destination on the next line, are all turned into text (it looks the same: &#91; is "[")
422
+ s = re.sub(r"\[([^\]]*)\]:", lambda m: "&#91;" + m.group(1) + "]:", s)
423
+ return _MATHJAX.sub(lambda m: "\\ " + m.group(1), s)
424
+
425
+
426
+ _CODE_PUNCT = {c: "&#%d;" % ord(c) for c in "[]()!*_`~|\\:$"}
427
+
428
+
429
+ def _code_text(text):
430
+ """The text of a code span or block, as HTML that shows it exactly and that no Markdown parser,
431
+ nor MathJax, can turn into anything else: < & > and every character with a meaning in Markdown
432
+ become character references (a parser may treat <code> as inline HTML and read on inside it)."""
433
+ import html as _h
434
+
435
+ t = _h.escape(text, quote=True)
436
+ return "".join(_CODE_PUNCT.get(c, c) for c in t)
437
+
438
+
439
+ def _escape_line(line):
440
+ """A line outside code blocks: inline code becomes <code> with its text escaped; the rest goes through _escape_text."""
441
+ import html as _h
442
+
443
+ out, i = [], 0
444
+ for m in re.finditer(r"(?<!\\)(`+)(.+?)(?<!`)\1(?!`)", line):
445
+ out.append(_escape_text(line[i:m.start()]))
446
+ body = m.group(2)
447
+ if body.startswith(" ") and body.endswith(" ") and body.strip():
448
+ body = body[1:-1]
449
+ out.append("<code>%s</code>" % _code_text(body))
450
+ i = m.end()
451
+ out.append(_escape_text(line[i:]))
452
+ return "".join(out)
453
+
454
+
455
+ def _indent(line):
456
+ return len(line.expandtabs(4)) - len(line.expandtabs(4).lstrip(" "))
457
+
458
+
459
+ def safe_markdown(md):
460
+ """Markdown written by the AI, ready to be shown in a notebook.
461
+
462
+ Jupyter renders the HTML inside Markdown that it trusts, and output made while a notebook runs is
463
+ trusted, so an <img onerror=...> from the model would run as script in the notebook's page - with
464
+ the power to run code in the kernel without the student's approval. So nothing the model writes
465
+ reaches the page as HTML: code blocks and inline code are turned into <pre>/<code> with their text
466
+ escaped, everything else has & and < escaped, and only http(s) and mailto links stay links. (The
467
+ price: code in answers is not colour-highlighted in notebooks.)
468
+ """
469
+ import html as _h
470
+
471
+ if not md:
472
+ return md
473
+ out = []
474
+ lines = md.split("\n")
475
+ i = 0
476
+ while i < len(lines):
477
+ line = lines[i]
478
+ m = _FENCE.match(line)
479
+ if not m or (m.group(2)[0] == "`" and "`" in m.group(3)):
480
+ out.append(_escape_line(line))
481
+ i += 1
482
+ continue
483
+ lead, fence, info = m.group(1), m.group(2), m.group(3).strip()
484
+ k = _indent(line)
485
+ body = []
486
+ i += 1
487
+ while i < len(lines):
488
+ ln = lines[i]
489
+ if ln.strip() and _indent(ln) < k:
490
+ break # the list item (or quote) the block was in has ended
491
+ if ln.lstrip().startswith(fence[0] * len(fence)):
492
+ i += 1
493
+ break
494
+ body.append(ln) # kept indented, so that a block in a list item stays in it
495
+ i += 1
496
+ if body:
497
+ body[0] = body[0][len(lead):] if body[0].startswith(lead) else body[0].lstrip()
498
+ lang = re.sub(r"[^\w+#.\-]", "", info.split()[0]) if info else ""
499
+ cls = ' class="language-%s"' % lang if lang else ""
500
+ out.append("%s<pre><code%s>%s</code></pre>" % (lead, cls, _code_text("\n".join(body))))
501
+ return "\n".join(out)
502
+
503
+
504
+ def inline_markdown(text):
505
+ """A short piece of the AI's text (a reason, a 'why') for one line of Markdown."""
506
+ return safe_markdown(" ".join((text or "").split()))
507
+
508
+
509
+ def inline_code(text):
510
+ """A path or a command for one line of Markdown, as <code> that shows it exactly."""
511
+ return "<code>%s</code>" % _code_text(" ".join(str(text or "").split()))