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/privacy.py ADDED
@@ -0,0 +1,804 @@
1
+ """What may go to the AI, and what may not.
2
+
3
+ Everything AskTim! sends to an AI service passes through this module.
4
+
5
+ 1. Secrets are removed: API keys, tokens, passwords, credentials in URLs, private keys.
6
+ 2. Personal details are removed: e-mail addresses, NHS numbers, UK phone and National
7
+ Insurance numbers, and long DNA/RNA/protein sequences written into a command or a message.
8
+ 3. The student's user name, home folder and computer name are replaced by "user", "~", "host".
9
+ 4. Output of commands and code is filtered line by line (DataFilter). Lines that look like
10
+ data - sequences, reads, alignments, variants, intervals, table rows, columns of numbers,
11
+ lists of IDs, encoded blobs - are withheld, and a note says how many lines were withheld
12
+ and what they looked like. What gets through is the kind of text a tutor needs: error
13
+ messages, warnings, help text, versions, counts and summaries, file listings.
14
+
15
+ The filter works on the shape of the text, so it errs on the side of withholding. It cannot
16
+ promise to recognise every piece of data in every format: a value quoted in an error message,
17
+ for example, can still get through (the "strict" setting replaces quoted values too).
18
+ """
19
+
20
+ import getpass
21
+ import os
22
+ import re
23
+ import socket
24
+ from collections import Counter
25
+
26
+ ANSI = re.compile(r"\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07]*\x07")
27
+
28
+ # -----------------------------------------------------------------------------------------------
29
+ # secrets
30
+ # -----------------------------------------------------------------------------------------------
31
+
32
+ _SECRET_PATTERNS = [
33
+ (re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----.*?(-----END [A-Z ]*PRIVATE KEY-----|\Z)", re.S), "[private key]"),
34
+ (re.compile(r"\bsk-ant-[A-Za-z0-9_\-]{10,}"), "[API key]"),
35
+ (re.compile(r"\bsk-(?:proj-|svcacct-|admin-)?[A-Za-z0-9_\-]{20,}"), "[API key]"),
36
+ (re.compile(r"\bAIza[0-9A-Za-z_\-]{30,}"), "[API key]"),
37
+ (re.compile(r"\bAQ\.[0-9A-Za-z_\-]{20,}"), "[API key]"),
38
+ (re.compile(r"\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,}|\bgithub_pat_[A-Za-z0-9_]{20,}"), "[token]"),
39
+ (re.compile(r"\bglpat-[A-Za-z0-9_\-]{20,}"), "[token]"),
40
+ (re.compile(r"\bhf_[A-Za-z0-9]{20,}"), "[token]"),
41
+ (re.compile(r"\bxox[abprs]-[A-Za-z0-9\-]{10,}"), "[token]"),
42
+ (re.compile(r"\b(?:AKIA|ASIA)[0-9A-Z]{16}\b"), "[access key]"),
43
+ (re.compile(r"\beyJ[A-Za-z0-9_\-]{8,}\.[A-Za-z0-9_\-]{8,}\.[A-Za-z0-9_\-]{8,}"), "[token]"),
44
+ # credentials inside URLs: https://name:password@host
45
+ (re.compile(r"(\b[a-zA-Z][a-zA-Z0-9+.\-]*://)[^/\s:@]+:[^/\s@]+@"), r"\1[credentials]@"),
46
+ # Authorization headers
47
+ (re.compile(r"(?i)\b(authorization\s*[:=]\s*(?:bearer|basic|token)\s+)(?!\[)[^\s'\"]+"), r"\1[secret]"),
48
+ (re.compile(r"(?i)\b(x-api-key|x-goog-api-key|api-key|apikey)(\s*[:=]\s*)(?!\[)[^\s'\"]+"), r"\1\2[secret]"),
49
+ # NAME_KEY=value, PASSWORD=value, export TOKEN="value" ... : see _assignments() below
50
+ # --password VALUE, --token=VALUE, -p VALUE for mysql-like tools is too ambiguous to touch
51
+ (re.compile(r"(?i)(--(?:password|passwd|token|api[-_]?key|secret|auth[-_]?token)(?:=|\s+))(?!\[)(\"[^\"]*\"|'[^']*'|[^\s;&|]+)"), r"\1[secret]"),
52
+ ]
53
+
54
+ # AskTim!'s own set-up command: AskTim! Claude sk-... (the key may not match a pattern above)
55
+ _SETUP = re.compile(r"(?i)\b(asktim!?\s+(?:claude|anthropic|gemini|google|openai|chatgpt|gpt|local)\s+)(\S{12,})")
56
+
57
+
58
+ _SECRET_WORDS = {"key", "apikey", "token", "secret", "password", "passwd", "pass", "pwd", "credential", "credentials", "auth", "pat"}
59
+ _ASSIGN = re.compile(r"(?i)\b([A-Za-z_][A-Za-z0-9_]*)(\s*[=:]\s*)(\"[^\"\n]*\"|'[^'\n]*'|[^\s;&|'\"]+)")
60
+
61
+
62
+ def _assignments(text):
63
+ """NAME=value where NAME holds a word such as KEY, TOKEN, SECRET or PASSWORD, and the value
64
+ is a literal (not code: secret_rows = df.head() stays as it is)."""
65
+ count = [0]
66
+
67
+ def rep(m):
68
+ name, sep, val = m.group(1), m.group(2), m.group(3)
69
+ words = set(w.lower() for w in re.split(r"_+|(?<=[a-z])(?=[A-Z])", name) if w)
70
+ if not words & _SECRET_WORDS or name in ("PWD", "OLDPWD") or val.startswith("[") or val.startswith("$"):
71
+ return m.group(0)
72
+ if val[:1] in "\"'":
73
+ inner = val[1:-1]
74
+ if len(inner) < 4 or re.fullmatch(r"[A-Za-z_][\w]*", inner) and len(inner) < 16 and not re.search(r"\d", inner):
75
+ return m.group(0) # a short word, such as sort_key = "length"
76
+ count[0] += 1
77
+ return name + sep + val[0] + "[secret]" + val[0]
78
+ if re.search(r"[()\[\]{}]", val) or re.fullmatch(r"[A-Za-z_][\w.]*", val) and not re.search(r"\d", val) or len(val) < 4:
79
+ return m.group(0) # code (df.head(), other_variable) or nothing worth hiding
80
+ count[0] += 1
81
+ return name + sep + "[secret]"
82
+
83
+ out = _ASSIGN.sub(rep, text)
84
+ return out, count[0]
85
+
86
+
87
+ def redact_secrets(text):
88
+ """(text without secrets, number of replacements)."""
89
+ if not text:
90
+ return text, 0
91
+ n = 0
92
+ text, k = _SETUP.subn(r"\1[API key]", text)
93
+ n += k
94
+ text, k = _assignments(text)
95
+ n += k
96
+ for pat, rep in _SECRET_PATTERNS:
97
+ text, k = pat.subn(rep, text)
98
+ n += k
99
+ # long random-looking tokens (mixed case and digits, 32+ characters) are treated as secrets
100
+ def _entropy(m):
101
+ tok = m.group(0)
102
+ if _is_checksum(tok) or _is_sequence(tok):
103
+ return tok
104
+ if re.search(r"[A-Z]", tok) and re.search(r"[a-z]", tok) and re.search(r"\d", tok) and not re.search(r"[/\\.]", tok):
105
+ return "[secret]"
106
+ return tok
107
+
108
+ new = re.sub(r"(?<![\w/.\-])[A-Za-z0-9_\-+=]{32,}(?![\w/.])", _entropy, text)
109
+ if new != text:
110
+ n += 1
111
+ return new, n
112
+
113
+
114
+ def _is_checksum(tok):
115
+ return bool(re.fullmatch(r"[0-9a-f]{32}|[0-9a-f]{40}|[0-9a-f]{56}|[0-9a-f]{64}|[0-9a-f]{96}|[0-9a-f]{128}", tok, re.I))
116
+
117
+
118
+ def _is_sequence(tok):
119
+ return bool(re.fullmatch(r"[ACGTUNacgtun\-.]+", tok))
120
+
121
+
122
+ # -----------------------------------------------------------------------------------------------
123
+ # personal details and sequences inside text
124
+ # -----------------------------------------------------------------------------------------------
125
+
126
+ _EMAIL = re.compile(r"\b[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}\b")
127
+ _NHS = re.compile(r"(?<![\d.:/\-])(\d{3})[ \-]?(\d{3})[ \-]?(\d{4})(?![\d.:/\-])")
128
+ _UK_PHONE = re.compile(r"(?<![\w+])(?:\+44\s?7\d{3}|\(?07\d{3}\)?)\s?\d{3}\s?\d{3}(?!\d)|(?<![\w+])(?:\+44\s?|0)(?:1\d{2,4}|2\d)\)?\s?\d{3,4}\s?\d{3,4}(?!\d)")
129
+ _NI = re.compile(r"\b(?!BG|GB|NK|KN|TN|NT|ZZ)[A-CEGHJ-PR-TW-Z][A-CEGHJ-NPR-TW-Z]\s?\d{2}\s?\d{2}\s?\d{2}\s?[A-D]\b")
130
+ _SEQ_IN_TEXT = re.compile(r"(?<![A-Za-z])[ACGTUNacgtun]{40,}(?![A-Za-z])")
131
+ _PROT_IN_TEXT = re.compile(r"(?<![A-Za-z])[ACDEFGHIKLMNPQRSTVWY]{50,}(?![A-Za-z])")
132
+ _BLOB = re.compile(r"(?<![\w/+=])[A-Za-z0-9+/]{48,}={0,2}(?![\w/+=])")
133
+
134
+ # Adapters and primers that are not data (they appear in commands such as cutadapt -a ...)
135
+ _COMMON_ADAPTERS = {
136
+ "AGATCGGAAGAGCACACGTCTGAACTCCAGTCA",
137
+ "AGATCGGAAGAGCGTCGTGTAGGGAAAGAGTGT",
138
+ "CTGTCTCTTATACACATCTCCGAGCCCACGAGAC",
139
+ "CTGTCTCTTATACACATCTGACGCTGCCGACGA",
140
+ "AATGATACGGCGACCACCGAGATCTACACTCTTTCCCTACACGACGCTCTTCCGATCT",
141
+ }
142
+
143
+
144
+ def _nhs_valid(digits):
145
+ if len(digits) != 10 or len(set(digits)) == 1:
146
+ return False
147
+ total = sum(int(d) * w for d, w in zip(digits[:9], range(10, 1, -1)))
148
+ check = 11 - total % 11
149
+ if check == 11:
150
+ check = 0
151
+ return check != 10 and check == int(digits[9])
152
+
153
+
154
+ def redact_personal(text, strict=False):
155
+ if not text:
156
+ return text, 0
157
+ n = 0
158
+ text, k = _EMAIL.subn("[e-mail]", text)
159
+ n += k
160
+
161
+ def nhs(m):
162
+ digits = "".join(m.groups())
163
+ return "[NHS number]" if _nhs_valid(digits) else m.group(0)
164
+
165
+ new = _NHS.sub(nhs, text)
166
+ n += new != text
167
+ text = new
168
+ text, k = _UK_PHONE.subn("[phone number]", text)
169
+ n += k
170
+ text, k = _NI.subn("[NI number]", text)
171
+ n += k
172
+
173
+ def quoted_row(m):
174
+ body = m.group(2)
175
+ if (body.count(",") >= 2 and ", " not in body) or body.count("\t") >= 2 or body.count("\\t") >= 2:
176
+ return m.group(1) + "[data]" + m.group(1)
177
+ return m.group(0)
178
+
179
+ new = re.sub(r"([\"'])([^\"'\n]{5,400})\1", quoted_row, text)
180
+ n += new != text
181
+ text = new
182
+
183
+ def seq(m):
184
+ s = m.group(0)
185
+ return s if s.upper() in _COMMON_ADAPTERS else "[sequence]"
186
+
187
+ text, k = _SEQ_IN_TEXT.subn(seq, text)
188
+ n += k
189
+ text, k = _PROT_IN_TEXT.subn("[protein sequence]", text)
190
+ n += k
191
+
192
+ def blob(m):
193
+ s = m.group(0)
194
+ return s if _is_checksum(s) or "/" in s.strip("/") and s.count("/") > 2 and not re.search(r"[+=]", s) else "[encoded data]"
195
+
196
+ text, k = _BLOB.subn(blob, text)
197
+ n += k
198
+ if strict:
199
+ short = re.compile(r"[ACGTUNacgtun]{20,}")
200
+ text, k = short.subn("[sequence]", text)
201
+ n += k
202
+ return text, n
203
+
204
+
205
+ # -----------------------------------------------------------------------------------------------
206
+ # who and where
207
+ # -----------------------------------------------------------------------------------------------
208
+
209
+
210
+ def _identity():
211
+ home = os.path.expanduser("~")
212
+ try:
213
+ user = getpass.getuser()
214
+ except Exception:
215
+ user = os.environ.get("USER") or os.environ.get("USERNAME") or ""
216
+ try:
217
+ host = socket.gethostname().split(".")[0]
218
+ except Exception:
219
+ host = ""
220
+ return home, user, host
221
+
222
+
223
+ _IDENT = None
224
+
225
+
226
+ def mask_identity(text):
227
+ """The student's home folder becomes ~, their user name 'user', the computer's name 'host'."""
228
+ global _IDENT
229
+ if not text:
230
+ return text
231
+ if _IDENT is None:
232
+ _IDENT = _identity()
233
+ home, user, host = _IDENT
234
+ if home and len(home) > 1:
235
+ text = re.sub(r"(?<![\w/.\-~])" + re.escape(home) + r"(?=/|\s|$|['\":;,)])", "~", text)
236
+ if user and len(user) >= 3 and user not in ("root", "user", "jovyan", "student", "ubuntu"):
237
+ text = re.sub(r"(?<![\w.\-])" + re.escape(user) + r"(?![\w\-])", "user", text)
238
+ if host and len(host) >= 3 and host.lower() not in ("localhost", "host"):
239
+ text = re.sub(r"(?<![\w.\-])" + re.escape(host) + r"(?![\w\-])", "host", text)
240
+ return text
241
+
242
+
243
+ def clean(text, strict=False):
244
+ """Secrets, personal details and identity out of any text that is going to the AI."""
245
+ if not text:
246
+ return text, 0
247
+ text, a = redact_secrets(text)
248
+ text, b = redact_personal(text, strict=strict)
249
+ return mask_identity(text), a + b
250
+
251
+
252
+ def clean_question(text, strict=False):
253
+ """A student's question, ready for the AI: (text, details removed, data lines withheld).
254
+
255
+ Text pasted into a question goes through the data filter first, while its shape is intact
256
+ (four FASTQ lines are recognisable as a read; after redaction they are not), then through clean().
257
+ """
258
+ text = (text or "").strip()
259
+ withheld = 0
260
+ if text.count("\n") >= 2:
261
+ fr = filter_output(text, strict=strict)
262
+ text, withheld = fr.text, fr.withheld
263
+ text, n = clean(text, strict=strict)
264
+ return text, n, withheld
265
+
266
+
267
+ # -----------------------------------------------------------------------------------------------
268
+ # the data filter for output
269
+ # -----------------------------------------------------------------------------------------------
270
+
271
+ _NUM = re.compile(r"^[-+]?(?:\d{1,3}(?:,\d{3})+|\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?%?$")
272
+ _WORD = re.compile(r"^[A-Za-z][A-Za-z'\-]*[A-Za-z]$")
273
+ _STRIP = "()[]{}<>\"'`,;:.!?*"
274
+ _SEQ_LINE = re.compile(r"^[ACGTUNRYKMSWBDHVacgtunrykmswbdhv.\-*]{20,}$")
275
+ _PROT_LINE = re.compile(r"^[ACDEFGHIKLMNPQRSTVWYXBZJUO*\-]{30,}$")
276
+ _QUAL_LINE = re.compile(r"^[!-~]{12,}$")
277
+ _LS_L = re.compile(r"^[-dlcbpsD][rwxsStT\-]{9}[.+@]?\s+\d+\s")
278
+ _WC = re.compile(r"^\s*\d+(?:\s+\d+){0,3}\s+\S+\s*$")
279
+ _SUM = re.compile(r"^[0-9a-fA-F]{32,128}\s+\*?\S")
280
+ _DU = re.compile(r"^\s*[\d.,]+[KMGTPkB]?i?B?\s+\S+\s*$")
281
+ _FLAGSTAT = re.compile(r"^\d+ \+ \d+ [a-z]")
282
+ _SN = re.compile(r"^SN\t")
283
+ _KV = re.compile(r"^\s*\"?([A-Za-z][A-Za-z0-9 _./()%#\-]{1,60})\"?\s*[:=]\s*(.*)$")
284
+ _LOGTAG = re.compile(r"^\s*(\[(?:[A-Za-z][\w:.*\-/]{0,60}|\d{4}-\d\d-\d\d[ T][\d:.,]+)\]|(?:INFO|WARN|WARNING|ERROR|Error|Warning|FATAL|DEBUG|NOTE|Note|Traceback|Exception|Usage|usage)\b:?)")
285
+ _OPTION_HELP = re.compile(r"^\s*--?[A-Za-z0-9@?][\w\-]*[,=]?(\s|$)")
286
+ _CODE = re.compile(r"^\s*(?:[A-Za-z_][\w.]*(?:\[[^\]]*\])?\s*(?:[-+*/]?=|<-)\s*\S|(?:def|class|import|from|return|for|while|if|elif|else|try|except|with|raise|assert|lambda|library|function|echo|printf|export|local|set)\b|[A-Za-z_][\w.]*\(.*\)\s*:?\s*$|\s*#|%|!)")
287
+ _SAM_HEADER = re.compile(r"^@(HD|SQ|RG|PG|CO)\t")
288
+ _VCF_META_KEEP = re.compile(r"^##(fileformat|INFO=<ID=|FORMAT=<ID=|FILTER=<ID=|ALT=<ID=|source=)")
289
+ _PATHLIKE = re.compile(r"^[\w.\-~/]*(/|\.[A-Za-z0-9]{1,8}(\.gz|\.bz2|\.xz|\.zst)?)$")
290
+
291
+
292
+ def _tokens(line):
293
+ return line.split()
294
+
295
+
296
+ def _core(tok):
297
+ return tok.strip(_STRIP)
298
+
299
+
300
+ def _is_word(tok):
301
+ c = _core(tok)
302
+ if not _WORD.match(c):
303
+ return False
304
+ # a run of A/C/G/T letters is a sequence, not a word, from 8 letters on
305
+ return not (len(c) >= 8 and re.fullmatch(r"[ACGTUNacgtun]+", c))
306
+
307
+
308
+ def _is_num(tok):
309
+ c = _core(tok)
310
+ return bool(c) and bool(_NUM.match(c))
311
+
312
+
313
+ def _textlike(s):
314
+ """Mostly words: prose, messages, help text."""
315
+ toks = _tokens(s)
316
+ if not toks:
317
+ return True
318
+ words = sum(1 for t in toks if _is_word(t))
319
+ if len(toks) <= 2:
320
+ return words == len(toks)
321
+ return words / float(len(toks)) >= 0.5
322
+
323
+
324
+ def _numeric_heavy(s):
325
+ toks = _tokens(s)
326
+ if len(toks) < 3:
327
+ return False
328
+ nums = sum(1 for t in toks if _is_num(t) or re.fullmatch(r"[0-9a-fA-F]{2,8}:?", _core(t) or "x"))
329
+ return nums / float(len(toks)) >= 0.5
330
+
331
+
332
+ def _csv_row(line):
333
+ if line.count(",") < 2 or ", " in line:
334
+ return False
335
+ fields = line.split(",")
336
+ return len(fields) >= 3 and all(len(f) <= 120 for f in fields)
337
+
338
+
339
+ def _fields(line):
340
+ if line.count("\t") >= 2:
341
+ return line.rstrip("\n").split("\t"), "\t"
342
+ if _csv_row(line):
343
+ return line.split(","), ","
344
+ if line.count(";") >= 2 and "; " not in line and " " not in line.strip():
345
+ return line.split(";"), ";"
346
+ if line.count("|") >= 2 and " | " not in line and " " not in line.strip():
347
+ return line.split("|"), "|"
348
+ return None, None
349
+
350
+
351
+ def _name_like(field):
352
+ f = field.strip().strip("\"'")
353
+ return bool(f) and len(f) <= 40 and not _is_num(f) and not _SEQ_LINE.match(f) and bool(re.match(r"^[A-Za-z_#.][\w .()%/\-#]*$", f))
354
+
355
+
356
+ def _codecall(s):
357
+ """A line of code with a call or an index: df['x'].mean(), print(n), x[0] = f(y)."""
358
+ return bool(re.match(r"^[A-Za-z_][\w.]*(?:\[[^\]]*\])*(?:\.[A-Za-z_]\w*)*(?:\(.*\))?(?:\[[^\]]*\])*\s*(?:[-+*/]?=.*)?$", s)) and bool(re.search(r"[a-z]{2}", s)) and bool(re.search(r"[(\[=]", s))
359
+
360
+
361
+ def _pathish(s):
362
+ return bool(_PATHLIKE.match(s)) and len(s) <= 200
363
+
364
+
365
+ def _keep_special(s, strict):
366
+ """Output that is not data although it is not prose: listings, counts, checksums, summaries,
367
+ log lines, code. In strict mode only counts, checksums and log/error lines."""
368
+ if _FLAGSTAT.match(s) or _SUM.match(s):
369
+ return True
370
+ if _WC.match(s) and not all(_is_num(t) for t in _tokens(s)):
371
+ label = _tokens(s)[-1]
372
+ return label == "total" or _pathish(label)
373
+ if _LS_L.match(s) or (_DU.match(s) and (re.match(r"^\s*[\d.,]+[KMGTPk]", s) or _pathish(_tokens(s)[-1]))):
374
+ return not strict
375
+ if _OPTION_HELP.match(s) and not _numeric_heavy(s):
376
+ return True
377
+ m = _LOGTAG.match(s)
378
+ if m:
379
+ rest = s[m.end():]
380
+ return _textlike(rest) or (not _numeric_heavy(rest) and len(_tokens(rest)) <= 8)
381
+ m = _KV.match(s)
382
+ if m and _keylike(m.group(1)) and len(_tokens(m.group(2))) <= 6 and not _numeric_heavy(m.group(2)):
383
+ return not strict
384
+ if _kv_summary(s):
385
+ return not strict
386
+ if _CODE.match(s) and not _numeric_heavy(s):
387
+ return True
388
+ if _commandlike(s):
389
+ return True
390
+ return False
391
+
392
+
393
+ _KV_PAIR = re.compile(r"\s*([A-Za-z][A-Za-z0-9 _./%#\-]{0,40}?)\s*[:=]\s*([-+]?\d[\d.,]*\s*%?(?:\s*\([^()]{0,24}\))?)\s*[,;|]?")
394
+
395
+
396
+ def _kv_summary(s):
397
+ """A summary line with a few counts: "Total reads: 1000 Mapped: 950 (95.00%)"."""
398
+ pos, pairs = 0, 0
399
+ while pos < len(s):
400
+ m = _KV_PAIR.match(s, pos)
401
+ if not m or m.end() == pos or not _keylike(m.group(1)):
402
+ return False
403
+ pairs += 1
404
+ pos = m.end()
405
+ return 2 <= pairs <= 8
406
+
407
+
408
+ def _keylike(key):
409
+ """A key of a summary line: words, possibly joined by _ . - or spaces (total_reads, Q20 bases)."""
410
+ parts = [p for p in re.split(r"[\s_.\-/()]+", key) if p]
411
+ if not parts:
412
+ return False
413
+ words = sum(1 for p in parts if _WORD.match(p) or re.fullmatch(r"[A-Za-z]\d{1,3}", p))
414
+ return words / float(len(parts)) >= 0.5
415
+
416
+
417
+ _OPTION = re.compile(r"^--?[A-Za-z][\w\-]*=?")
418
+
419
+
420
+ def _commandlike(s):
421
+ """A command line (echoed by set -x, or written in a log): a program name and options."""
422
+ toks = _tokens(s.lstrip("+$> "))
423
+ if len(toks) < 2 or not re.match(r"^[A-Za-z_][\w.\-]*$", toks[0]):
424
+ return False
425
+ return any(_OPTION.match(t) for t in toks[1:]) or toks[0] in ("cd", "mkdir", "cp", "mv", "rm", "cat", "for", "while", "if", "then", "do", "done", "fi")
426
+
427
+
428
+ def _gaps(line):
429
+ """Character positions of runs of 2+ spaces inside the line (column separators)."""
430
+ body = line.rstrip()
431
+ start = len(body) - len(body.lstrip())
432
+ return set(i for m in re.finditer(r" +", body[start:]) for i in range(m.start() + start, m.end() + start))
433
+
434
+
435
+ def _aligned_blocks(lines, labels):
436
+ """Blocks of 3+ lines laid out in columns (pandas/R prints, column -t): their rows are data."""
437
+ n = len(lines)
438
+ i = 0
439
+ while i < n:
440
+ j = i
441
+ common = None
442
+ while j < n and lines[j].strip() and len(_tokens(lines[j])) >= 2:
443
+ g = _gaps(lines[j])
444
+ if not g:
445
+ break
446
+ nc = g if common is None else (common & g)
447
+ if common is not None and len(_runs(nc)) < 1:
448
+ break
449
+ common = nc
450
+ j += 1
451
+ if j - i >= 3 and common is not None and len(_runs(common)) >= 1:
452
+ rows = range(i, j)
453
+ texty = sum(1 for k in rows if _textlike(lines[k].strip()))
454
+ indexed = _incrementing_index(lines[i + 1:j]) or _incrementing_index(lines[i:j])
455
+ ends_in_number = sum(1 for k in rows if _is_num(_tokens(lines[k])[-1]))
456
+ if indexed or texty < (j - i) * 0.5 or ends_in_number >= (j - i) * 0.6:
457
+ first = i
458
+ if not indexed and _textlike(lines[i].strip()) and all(_name_like(t) for t in _tokens(lines[i])):
459
+ first = i + 1 # a header line of column names
460
+ elif indexed and not _incrementing_index(lines[i:i + 2]):
461
+ first = i + 1 # pandas: the header is the line before the numbered rows
462
+ for k in range(first, j):
463
+ if labels[k] is None and not _keep_special(lines[k].strip(), False):
464
+ labels[k] = "table rows"
465
+ i = j
466
+ else:
467
+ i += 1
468
+
469
+
470
+ def _numbered_rows(lines, labels):
471
+ """3+ lines that start 0, 1, 2 ... or 1, 2, 3 ... (or [1], [2] ...) followed by values: printed rows."""
472
+ n = len(lines)
473
+ i = 0
474
+ while i < n:
475
+ j = i
476
+ prev = None
477
+ while j < n:
478
+ toks = _tokens(lines[j])
479
+ if len(toks) < 2:
480
+ break
481
+ m = re.fullmatch(r"\[?(\d+)[\],]?", toks[0])
482
+ if not m or (prev is not None and int(m.group(1)) != prev + 1):
483
+ break
484
+ prev = int(m.group(1))
485
+ j += 1
486
+ if j - i >= 3:
487
+ for k in range(i, j):
488
+ if labels[k] is None:
489
+ labels[k] = "table rows"
490
+ i = j
491
+ else:
492
+ i += 1
493
+
494
+
495
+ def _runs(positions):
496
+ runs, prev = [], None
497
+ for p in sorted(positions):
498
+ if prev is None or p != prev + 1:
499
+ runs.append(p)
500
+ prev = p
501
+ return runs
502
+
503
+
504
+ def _incrementing_index(lines):
505
+ if len(lines) < 2:
506
+ return False
507
+ try:
508
+ idx = [int(_tokens(ln)[0]) for ln in lines if _tokens(ln) and _tokens(ln)[0].isdigit()]
509
+ except ValueError:
510
+ return False
511
+ if len(idx) < max(2, len(lines) - 1):
512
+ return False
513
+ return all(b - a == 1 for a, b in zip(idx, idx[1:]))
514
+
515
+
516
+ _SEQ_KINDS = ("sequences", "protein sequences", "alignments", "FASTA sequences", "FASTQ reads")
517
+ _NT_TOKEN = re.compile(r"^[ACGTUNRYKMSWBDHVacgtunrykmswbdhv.\-*]{20,}$")
518
+ _AA_TOKEN = re.compile(r"^[ACDEFGHIKLMNPQRSTVWYXBZJUO*\-.]{30,}$")
519
+ _NT_GROUP = re.compile(r"^[ACGTUNacgtun]+$")
520
+ _AA_GROUP = re.compile(r"^[ACDEFGHIKLMNPQRSTVWYX*]+$")
521
+
522
+
523
+ def _seq_tokens(s):
524
+ """The kind of sequence data in a line that is not a table row, or None: a sequence among other words
525
+ (an alignment line: "seq1 ACG-TTA...", "Query 1 MKTAY... 60"), or a sequence written in groups
526
+ ("ATG GCC TTA ...", GenBank and EMBL blocks of ten, codons)."""
527
+ toks = s.split()
528
+ for t in toks:
529
+ letters = sum(c.isalpha() for c in t)
530
+ if letters >= 12 and letters >= len(t) * 0.5 and (_NT_TOKEN.match(t) or _AA_TOKEN.match(t)):
531
+ return "alignments" if ("-" in t or "." in t) else "sequences"
532
+ groups = [t for t in toks if not t.isdigit()]
533
+ if len(groups) >= 4:
534
+ if all(_NT_GROUP.match(t) for t in groups) and sum(map(len, groups)) >= 20:
535
+ return "sequences"
536
+ if all(_AA_GROUP.match(t) for t in groups) and sum(map(len, groups)) >= 30:
537
+ lengths = [len(t) for t in groups]
538
+ if max(lengths.count(k) for k in set(lengths) if k >= 5) >= 3 if any(k >= 5 for k in lengths) else False:
539
+ return "protein sequences"
540
+ return None
541
+
542
+
543
+ def _classify(lines, strict):
544
+ """For each line: None (it may go to the AI) or the kind of data it is."""
545
+ n = len(lines)
546
+ labels = [None] * n
547
+ # records that span lines: FASTQ (4 lines) and FASTA (a header and its sequence lines)
548
+ i = 0
549
+ while i < n:
550
+ s = lines[i].strip()
551
+ if s.startswith("@") and i + 1 < n and _SEQ_LINE.match(lines[i + 1].strip() or "x"):
552
+ labels[i] = labels[i + 1] = "FASTQ reads"
553
+ k = i + 2
554
+ if k < n and lines[k].startswith("+"):
555
+ labels[k] = "FASTQ reads"
556
+ if k + 1 < n and " " not in lines[k + 1].strip() and _QUAL_LINE.match(lines[k + 1].strip() or "x"):
557
+ labels[k + 1] = "FASTQ reads"
558
+ k += 1
559
+ k += 1
560
+ i = k
561
+ continue
562
+ if s.startswith("+") and i + 1 < n and labels[i - 1 if i else 0] == "sequences" and _QUAL_LINE.match(lines[i + 1].strip() or "x"):
563
+ labels[i] = labels[i + 1] = "FASTQ reads"
564
+ i += 2
565
+ continue
566
+ if s.startswith(">") and i + 1 < n and (_SEQ_LINE.match(lines[i + 1].strip() or "x") or _PROT_LINE.match(lines[i + 1].strip() or "x")):
567
+ labels[i] = "FASTA sequences"
568
+ i += 1
569
+ while i < n and lines[i].strip() and not lines[i].lstrip().startswith(">") and re.fullmatch(r"[A-Za-z*\-.]+", lines[i].strip()):
570
+ labels[i] = "FASTA sequences"
571
+ i += 1
572
+ continue
573
+ i += 1
574
+ for i, L in enumerate(lines):
575
+ if labels[i]:
576
+ continue
577
+ s = L.strip()
578
+ if not s:
579
+ continue
580
+ if _SEQ_LINE.match(s):
581
+ labels[i] = "sequences"
582
+ elif _PROT_LINE.match(s):
583
+ labels[i] = "protein sequences"
584
+ elif _SAM_HEADER.match(L):
585
+ labels[i] = "SAM header"
586
+ elif L.startswith("##"):
587
+ if strict or not _VCF_META_KEEP.match(L):
588
+ labels[i] = "VCF header"
589
+ elif L.startswith("#CHROM\t"):
590
+ if strict:
591
+ labels[i] = "VCF header"
592
+ elif L.startswith(">") and not _textlike(s[1:]):
593
+ labels[i] = "FASTA sequences"
594
+ else:
595
+ fields, delim = _fields(L)
596
+ if fields is not None and len(fields) >= 3:
597
+ if _SN.match(L):
598
+ labels[i] = None if not strict else "summary table"
599
+ elif len(fields) >= 11 and fields[1].isdigit() and fields[3].isdigit():
600
+ labels[i] = "SAM/BAM alignments"
601
+ elif delim == "\t" and len(fields) >= 8 and fields[1].isdigit() and not fields[0].isdigit():
602
+ labels[i] = "VCF records"
603
+ elif delim == "\t" and len(fields) == 9 and fields[3].strip().isdigit() and fields[4].strip().isdigit():
604
+ labels[i] = "intervals (GFF/GTF)"
605
+ elif delim == "\t" and fields[1].strip().isdigit() and fields[2].strip().isdigit():
606
+ labels[i] = "intervals (BED-like)"
607
+ else:
608
+ labels[i] = "table rows"
609
+ elif _seq_tokens(s):
610
+ labels[i] = _seq_tokens(s)
611
+ elif _keep_special(s, strict):
612
+ labels[i] = None
613
+ elif _numeric_heavy(s):
614
+ labels[i] = "numbers"
615
+ elif re.fullmatch(r"[\s~^\-=_*+|.:]+", s):
616
+ labels[i] = None # decoration: Python's ~~~^^^ markers, rules, underlines
617
+ elif " " not in s and _QUAL_LINE.match(s) and sum(1 for c in s if not c.isalnum()) >= len(s) * 0.25 and not _pathish(s) and not _codecall(s):
618
+ labels[i] = "quality strings or encoded data"
619
+ elif _BLOB.fullmatch(s) and not _is_checksum(s):
620
+ labels[i] = "encoded data"
621
+ elif _textlike(s):
622
+ labels[i] = None
623
+ elif len(_tokens(s)) <= 2:
624
+ labels[i] = None # a single value or name; long lists of them are caught below
625
+ else:
626
+ labels[i] = "values"
627
+ # the middle line of an alignment (BLAST's line of matching residues between Query and Sbjct)
628
+ for i in range(1, n - 1):
629
+ if labels[i] is None and labels[i - 1] in _SEQ_KINDS and labels[i + 1] in _SEQ_KINDS:
630
+ body = lines[i].strip()
631
+ if len(re.sub(r"[^A-Za-z]", "", body)) >= 5 and re.fullmatch(r"[A-Za-z+|:.*\- ]+", body):
632
+ labels[i] = "alignments"
633
+ # tables laid out with spaces (print(df), R data frames, column -t)
634
+ _aligned_blocks(lines, labels)
635
+ _numbered_rows(lines, labels)
636
+ # runs of short, value-like lines (lists of IDs, positions or numbers) are data
637
+ i = 0
638
+ while i < n:
639
+ j = i
640
+ while j < n and labels[j] is None and lines[j].strip() and len(_tokens(lines[j])) <= 2 and not _textlike(lines[j].strip()) and not _pathish(lines[j].strip()) and not _keep_special(lines[j].strip(), strict):
641
+ j += 1
642
+ if j - i >= 5:
643
+ for k in range(i, j):
644
+ labels[k] = "lists of values"
645
+ i = max(j, i + 1)
646
+ # a short piece of sequence next to other data (the end of a wrapped sequence, for example)
647
+ for i in range(n):
648
+ if labels[i] is None and re.fullmatch(r"[ACGTUNacgtun]{4,}", lines[i].strip() or "x") and (
649
+ (i > 0 and labels[i - 1] is not None) or (i + 1 < n and labels[i + 1] is not None)):
650
+ labels[i] = "sequences"
651
+ # the line before table rows: a header of column names may stay (not in strict); a row of values may not
652
+ for i in range(n):
653
+ if labels[i] is not None or not lines[i].strip() or i + 1 >= n:
654
+ continue
655
+ if labels[i + 1] in ("table rows", "numbers", "values", "intervals (BED-like)"):
656
+ fields, delim = _fields(lines[i])
657
+ nfields, ndelim = _fields(lines[i + 1])
658
+ same_shape = fields is not None and ndelim == delim and len(fields) == len(nfields)
659
+ if strict and labels[i + 1] in ("table rows", "numbers"):
660
+ labels[i] = "table header"
661
+ elif same_shape and not all(_name_like(f) for f in fields if f.strip()):
662
+ labels[i] = "table rows"
663
+ if strict:
664
+ # in strict mode only text-like lines (messages, help, errors) and counts stay
665
+ for i in range(n):
666
+ s = lines[i].strip()
667
+ if labels[i] is None and s and not (_textlike(s) or _keep_special(s, True)):
668
+ labels[i] = "values"
669
+ return labels
670
+
671
+
672
+ def _redact_line(line, strict):
673
+ line, _ = redact_secrets(line)
674
+ line, _ = redact_personal(line, strict=strict)
675
+ if strict:
676
+ line = re.sub(r"'[^']{1,200}'", "'[value]'", line)
677
+ line = re.sub(r"\"[^\"]{1,200}\"", '"[value]"', line)
678
+ return line
679
+
680
+
681
+ def _vcf_header_line(line):
682
+ cols = line.rstrip("\n").split("\t")
683
+ if len(cols) > 9:
684
+ k = len(cols) - 9
685
+ return "\t".join(cols[:9]) + "\t[%d sample column%s – names withheld]" % (k, "" if k == 1 else "s")
686
+ return line
687
+
688
+
689
+ def _mask_ls_owner(line):
690
+ # -rw-r--r-- 1 owner group size date name: owner and group become "user"
691
+ lead = line[: len(line) - len(line.lstrip())]
692
+ parts = line.split(None, 4)
693
+ if len(parts) == 5 and parts[1].isdigit():
694
+ return lead + " ".join([parts[0], parts[1], "user", "user", parts[4]])
695
+ return line
696
+
697
+
698
+ class FilterResult(object):
699
+ def __init__(self, text, kept, withheld, kinds, total):
700
+ self.text = text # what the AI gets
701
+ self.kept = kept
702
+ self.withheld = withheld
703
+ self.kinds = kinds # Counter: kind of data -> lines withheld
704
+ self.total = total # lines in the original
705
+
706
+ def summary(self):
707
+ if not self.withheld:
708
+ return "nothing withheld"
709
+ what = ", ".join(k for k, _ in self.kinds.most_common(3))
710
+ return "%d of %d lines withheld (%s)" % (self.withheld, self.total, what)
711
+
712
+
713
+ def filter_output(text, kind="default", strict=False):
714
+ """Filter the output of a command or of code before the AI sees it.
715
+
716
+ kind: "default" - classify every line; "help" (help or version text), "code" (a script
717
+ being read) and "summary" (counts, checksums, listings, flagstat ...) are only cleaned of
718
+ secrets and personal details - except in strict mode, where every line is classified.
719
+ """
720
+ text = ANSI.sub("", text or "")
721
+ # progress bars: keep what a terminal finally shows on each line
722
+ lines = [ln.split("\r")[-1] for ln in text.replace("\r\n", "\n").split("\n")]
723
+ if lines and lines[-1] == "":
724
+ lines.pop()
725
+ total = len(lines)
726
+ if kind in ("help", "code", "summary") and not strict:
727
+ out = [mask_identity(_redact_line(ln, strict)) for ln in lines]
728
+ return FilterResult("\n".join(out), total, 0, Counter(), total)
729
+ if kind == "help" and strict:
730
+ labels = [None if (_textlike(ln.strip()) or not ln.strip() or _keep_special(ln.strip(), True) or ln.lstrip().startswith("-")) else "values" for ln in lines]
731
+ else:
732
+ labels = _classify(lines, strict)
733
+ vcf_meta = 0
734
+ for i, ln in enumerate(lines):
735
+ if labels[i] is None and ln.startswith("##"):
736
+ vcf_meta += 1
737
+ if vcf_meta > 25:
738
+ labels[i] = "VCF header"
739
+ out, kinds, withheld = [], Counter(), 0
740
+ i = 0
741
+ while i < total:
742
+ if labels[i] is None:
743
+ ln = lines[i]
744
+ if ln.startswith("#CHROM\t"):
745
+ ln = _vcf_header_line(ln)
746
+ if _LS_L.match(ln.strip()):
747
+ ln = _mask_ls_owner(ln)
748
+ out.append(mask_identity(_redact_line(ln, strict)))
749
+ i += 1
750
+ continue
751
+ j = i
752
+ run = Counter()
753
+ while j < total and (labels[j] is not None or (not lines[j].strip() and j + 1 < total and labels[j + 1] is not None)):
754
+ if labels[j]:
755
+ run[labels[j]] += 1
756
+ j += 1
757
+ count = j - i
758
+ withheld += count
759
+ kinds.update(run)
760
+ what = ", ".join(k for k, _ in run.most_common(2)) or "data"
761
+ out.append("[AskTim!: %d line%s withheld – %s like data (%s); the student can see %s]" % (count, "" if count == 1 else "s", "it looks" if count == 1 else "they look", what, "it" if count == 1 else "them"))
762
+ i = j
763
+ return FilterResult("\n".join(out), total - withheld, withheld, kinds, total)
764
+
765
+
766
+ _TRIPLE = re.compile(r'("""|\'\'\')(.*?)(\1)', re.S)
767
+ _ONE_NUMBER = r"-?\d+(?:\.\d+)?(?:[eE][-+]?\d+)?"
768
+ _NUM_LIST = re.compile(r"([\[(]\s*)((?:%s\s*,\s*){7,}%s)(\s*,?\s*[\])])" % (_ONE_NUMBER, _ONE_NUMBER))
769
+
770
+
771
+ def filter_code(code, strict=False):
772
+ """Code from a notebook cell, with the data that can be typed into code withheld: a text block in a
773
+ string (a CSV pasted between triple quotes) goes through the data filter, and a literal list of
774
+ eight or more numbers is shortened. (text, lines or lists withheld)"""
775
+ if not code:
776
+ return code, 0
777
+ count = [0]
778
+
779
+ def block(m):
780
+ body = m.group(2)
781
+ if body.count("\n") < 2:
782
+ return m.group(0)
783
+ fr = filter_output(body, kind="default", strict=strict)
784
+ count[0] += fr.withheld
785
+ return m.group(1) + fr.text + m.group(3)
786
+
787
+ def nums(m):
788
+ count[0] += 1
789
+ n = m.group(2).count(",") + 1
790
+ return "%s...AskTim!: %d numbers withheld...%s" % (m.group(1), n, m.group(3))
791
+
792
+ code = _TRIPLE.sub(block, code)
793
+ code = _NUM_LIST.sub(nums, code)
794
+ return code, count[0]
795
+
796
+
797
+ def shorten(text, limit):
798
+ """Keep the beginning and the end of long text (the end matters most for errors)."""
799
+ if text is None or len(text) <= limit:
800
+ return text
801
+ head = int(limit * 0.3)
802
+ tail = limit - head
803
+ cut = len(text) - head - tail
804
+ return "%s\n[AskTim!: %d characters left out here]\n%s" % (text[:head], cut, text[-tail:])