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/fileinfo.py ADDED
@@ -0,0 +1,593 @@
1
+ """Describe a file without sending what is in it.
2
+
3
+ `describe(path)` reads the start of a file (decompressing .gz) to work out its format, and
4
+ counts records where that is quick. It returns a short description such as
5
+
6
+ data/reads_R1.fastq.gz: FASTQ (gzip), 12.4 MB; about 152,000 reads (estimated);
7
+ read length 76-76 (mean 76.0); qualities look like Phred+33.
8
+
9
+ For tables it gives the number of rows and columns, and - when the first line is a header -
10
+ the column names and the kind of values in each column (numbers, text, true/false), but
11
+ never the values. Sequence names are given only when they look like reference names
12
+ (chr1, NC_000913.3 ...), and sample names never.
13
+ """
14
+
15
+ import csv
16
+ import gzip
17
+ import io
18
+ import json
19
+ import os
20
+ import re
21
+ import shutil
22
+ import subprocess
23
+
24
+ from . import paths
25
+
26
+ SAMPLE_BYTES = 1 << 20 # what is read to recognise a format
27
+ COUNT_LIMIT = 200 << 20 # files up to this size (uncompressed reading) are counted exactly
28
+
29
+ _REF_NAME = re.compile(r"^(chr[\w.]+|\d{1,2}|[XYM]T?|NC_\d+(\.\d+)?|NZ_\w+|NT_\d+(\.\d+)?|NW_\d+(\.\d+)?|CM\d+(\.\d+)?|[A-Z]{1,2}\d{5,8}(\.\d+)?|contig_?\d+|scaffold_?\d+|NODE_\d+\w*|human_\w+|ENS\w+|[OPQ]\d[A-Z0-9]{3}\d|sp\|\w+\|\w+|tr\|\w+\|\w+)$")
30
+
31
+ INDEX_EXT = {
32
+ ".bai": "a BAM index (made by samtools index)", ".csi": "a CSI index (samtools or bcftools)", ".crai": "a CRAM index",
33
+ ".tbi": "a tabix index (made by tabix)", ".fai": "a FASTA index (made by samtools faidx)", ".gzi": "a bgzip index",
34
+ ".amb": "part of a BWA index (bwa index)", ".ann": "part of a BWA index (bwa index)", ".bwt": "part of a BWA index (bwa index)",
35
+ ".pac": "part of a BWA index (bwa index)", ".sa": "part of a BWA index (bwa index)", ".bt2": "part of a Bowtie 2 index (bowtie2-build)",
36
+ ".bt2l": "part of a Bowtie 2 index (bowtie2-build)", ".ht2": "part of a HISAT2 index (hisat2-build)", ".mmi": "a minimap2 index (minimap2 -d)",
37
+ ".dict": "a sequence dictionary (Picard/GATK CreateSequenceDictionary)", ".idx": "an index file",
38
+ }
39
+
40
+ CODE_EXT = {
41
+ ".py", ".r", ".rmd", ".qmd", ".sh", ".bash", ".zsh", ".smk", ".nf", ".pl", ".awk", ".sed", ".md", ".rst", ".txt",
42
+ ".yaml", ".yml", ".toml", ".cfg", ".ini", ".config", ".wdl", ".cwl", ".ipynb", ".json", ".js", ".html", ".css", ".tex",
43
+ }
44
+ CODE_NAMES = {"snakefile", "makefile", "dockerfile", "readme", "license", "nextflow.config", "environment.yml", "requirements.txt"}
45
+
46
+
47
+ def human(n):
48
+ for unit in ("bytes", "KB", "MB", "GB", "TB"):
49
+ if n < 1024 or unit == "TB":
50
+ return ("%d %s" % (n, unit)) if unit == "bytes" else ("%.1f %s" % (n, unit))
51
+ n /= 1024.0
52
+
53
+
54
+ def _open_text(path, gz):
55
+ raw = gzip.open(path, "rb") if gz else open(path, "rb")
56
+ return raw
57
+
58
+
59
+ def _magic(path):
60
+ try:
61
+ with open(path, "rb") as f:
62
+ return f.read(512)
63
+ except OSError:
64
+ return b""
65
+
66
+
67
+ def _bgzf(head):
68
+ return head[:4] == b"\x1f\x8b\x08\x04" and b"BC" in head[12:20]
69
+
70
+
71
+ def _read_sample(path, gz, limit=SAMPLE_BYTES):
72
+ try:
73
+ with _open_text(path, gz) as f:
74
+ data = f.read(limit)
75
+ except (OSError, EOFError, gzip.BadGzipFile if hasattr(gzip, "BadGzipFile") else OSError):
76
+ return None
77
+ return data
78
+
79
+
80
+ def _count_lines(path, gz, cap=COUNT_LIMIT):
81
+ """(lines, exact): exact if the whole file was read."""
82
+ n = 0
83
+ read = 0
84
+ try:
85
+ with _open_text(path, gz) as f:
86
+ while True:
87
+ chunk = f.read(1 << 20)
88
+ if not chunk:
89
+ return n, True
90
+ n += chunk.count(b"\n")
91
+ read += len(chunk)
92
+ if read > cap:
93
+ return n, False
94
+ except (OSError, EOFError):
95
+ return n, False
96
+
97
+
98
+ def _estimate(path, gz, sample, per_record_lines):
99
+ """Records in the whole file, from the sample (for big or compressed files)."""
100
+ size = os.path.getsize(path)
101
+ lines = sample.count(b"\n")
102
+ if not lines:
103
+ return None
104
+ if gz:
105
+ try:
106
+ with open(path, "rb") as f:
107
+ comp = f.read(1 << 20)
108
+ ratio = len(sample) / float(max(1, min(len(comp), size)))
109
+ approx_uncompressed = size * max(1.0, ratio) if len(sample) >= SAMPLE_BYTES else len(sample)
110
+ except OSError:
111
+ return None
112
+ else:
113
+ approx_uncompressed = size
114
+ return int(approx_uncompressed / (len(sample) / float(lines)) / per_record_lines)
115
+
116
+
117
+ def describe(path, strict=False, base=None):
118
+ """A short description of a file or folder, safe to send to the AI."""
119
+ shown = paths.pretty(path) if base is None else os.path.relpath(path, base)
120
+ if not os.path.exists(path):
121
+ return "%s: there is no such file or folder." % shown
122
+ if os.path.isdir(path):
123
+ return _describe_dir(path, shown)
124
+ size = os.path.getsize(path)
125
+ head = _magic(path)
126
+ name = os.path.basename(path)
127
+ low = name.lower()
128
+ gz = head[:2] == b"\x1f\x8b"
129
+ comp = "BGZF" if _bgzf(head) else "gzip" if gz else ""
130
+ for ext_, what in INDEX_EXT.items():
131
+ if low.endswith(ext_):
132
+ return "%s: %s, %s." % (shown, what, human(size))
133
+ # binary formats
134
+ if low.endswith(".bam") or (gz and _bam_inside(path)):
135
+ return _describe_bam(path, shown, size, strict)
136
+ if head[:4] == b"CRAM":
137
+ return "%s: CRAM alignment file, %s. %s" % (shown, human(size), _samtools_header_summary(path, strict) or "")
138
+ if low.endswith(".bcf"):
139
+ return "%s: BCF (binary VCF), %s. Use bcftools to read it." % (shown, human(size))
140
+ for sig, kind in ((b"PK\x03\x04", "a zip archive (or an .xlsx/.docx file)"), (b"%PDF", "a PDF document"), (b"\x89PNG", "a PNG image"),
141
+ (b"\xff\xd8\xff", "a JPEG image"), (b"\x89HDF", "an HDF5 file (for example .h5ad or .h5)"), (b"PAR1", "a Parquet table"),
142
+ (b"SQLite format 3", "an SQLite database"), (b"BZh", "a bzip2-compressed file"), (b"\xfd7zXZ", "an xz-compressed file"),
143
+ (b"(\xb5/\xfd", "a zstd-compressed file"), (b"GIF8", "a GIF image")):
144
+ if head.startswith(sig):
145
+ extra = _zip_members(path) if sig == b"PK\x03\x04" else ""
146
+ return "%s: %s, %s.%s" % (shown, kind, human(size), extra)
147
+ sample = _read_sample(path, gz)
148
+ if sample is None:
149
+ return "%s: %s, %s; it could not be read (damaged or incomplete?)." % (shown, "compressed file" if gz else "file", human(size))
150
+ if b"\x00" in sample[:8192] and not gz:
151
+ return "%s: a binary file, %s." % (shown, human(size))
152
+ text = sample.decode("utf-8", "replace")
153
+ lines = text.split("\n")
154
+ if len(sample) >= SAMPLE_BYTES:
155
+ lines = lines[:-1] # the last line may be cut
156
+ stem = re.sub(r"\.(gz|bgz|bz2|xz|zst)$", "", low)
157
+ ext = os.path.splitext(stem)[1]
158
+ fmt = (" (%s)" % comp) if comp else ""
159
+ first = next((ln for ln in lines if ln.strip()), "")
160
+ if not first:
161
+ return "%s: an empty file%s, %s." % (shown, fmt, human(size))
162
+ if first.startswith("@") and len(lines) > 3 and lines[2].startswith("+"):
163
+ return _describe_fastq(path, shown, size, gz, sample, lines, fmt)
164
+ if first.startswith(">"):
165
+ return _describe_fasta(path, shown, size, gz, sample, lines, fmt, strict)
166
+ if first.startswith("##fileformat=VCF") or ext == ".vcf":
167
+ return _describe_vcf(path, shown, size, gz, sample, lines, fmt, strict)
168
+ if first.startswith("@HD") or first.startswith("@SQ") or ext == ".sam":
169
+ return "%s: SAM alignments%s, %s. %s" % (shown, fmt, human(size), _samtools_header_summary(path, strict) or "")
170
+ if ext in (".gff", ".gff3", ".gtf") or first.startswith("##gff-version"):
171
+ return _describe_gff(path, shown, size, gz, lines, fmt)
172
+ if ext in (".bed", ".bedgraph", ".narrowpeak", ".broadpeak"):
173
+ return _describe_bed(path, shown, size, gz, lines, fmt)
174
+ if ext == ".json" or (first.lstrip()[:1] in "{[" and ext not in CODE_EXT - {".json"}):
175
+ return _describe_json(path, shown, size, gz, text, fmt, strict)
176
+ if ext in CODE_EXT and ext not in (".txt", ".json") or stem in CODE_NAMES or name.lower() in CODE_NAMES:
177
+ n, exact = _count_lines(path, gz)
178
+ return "%s: a text file (%s)%s, %s, %s%d lines. It is code or writing, not data: you may read it." % (
179
+ shown, ext.lstrip(".") or name, fmt, human(size), "" if exact else "at least ", n)
180
+ return _describe_table_or_text(path, shown, size, gz, lines, fmt, strict, ext)
181
+
182
+
183
+ def _describe_dir(path, shown):
184
+ counts = {}
185
+ n_files = n_dirs = 0
186
+ total = 0
187
+ try:
188
+ for root, dirs, files in os.walk(path):
189
+ dirs[:] = [d for d in dirs if not d.startswith(".")]
190
+ n_dirs += len(dirs)
191
+ for fn in files:
192
+ if fn.startswith("."):
193
+ continue
194
+ n_files += 1
195
+ low = fn.lower()
196
+ m = re.search(r"(\.[a-z0-9]{1,8}(\.(gz|bz2|xz|zst))?)$", low)
197
+ counts[m.group(1) if m else "(no extension)"] = counts.get(m.group(1) if m else "(no extension)", 0) + 1
198
+ try:
199
+ total += os.path.getsize(os.path.join(root, fn))
200
+ except OSError:
201
+ pass
202
+ if n_files > 50000:
203
+ break
204
+ except OSError:
205
+ pass
206
+ kinds = ", ".join("%d %s" % (v, k) for k, v in sorted(counts.items(), key=lambda kv: -kv[1])[:12])
207
+ return "%s/: a folder with %d files (%s) in %d subfolders, %s in all." % (shown.rstrip("/"), n_files, kinds or "none", n_dirs, human(total))
208
+
209
+
210
+ def _zip_members(path):
211
+ try:
212
+ import zipfile
213
+
214
+ with zipfile.ZipFile(path) as z:
215
+ names = z.namelist()
216
+ if any(n.startswith("xl/") for n in names):
217
+ return " It is an Excel workbook (.xlsx)."
218
+ return " It holds %d files." % len(names)
219
+ except Exception:
220
+ return ""
221
+
222
+
223
+ def _bam_inside(path):
224
+ try:
225
+ with gzip.open(path, "rb") as f:
226
+ return f.read(4) == b"BAM\x01"
227
+ except Exception:
228
+ return False
229
+
230
+
231
+ def _samtools_header_summary(path, strict):
232
+ st = shutil.which("samtools")
233
+ if not st:
234
+ return ""
235
+ try:
236
+ p = subprocess.run([st, "view", "-H", path], capture_output=True, timeout=20)
237
+ except Exception:
238
+ return ""
239
+ hdr = p.stdout.decode("utf-8", "replace").splitlines()
240
+ sq = [ln for ln in hdr if ln.startswith("@SQ")]
241
+ rg = [ln for ln in hdr if ln.startswith("@RG")]
242
+ pg = []
243
+ for ln in hdr:
244
+ if ln.startswith("@PG"):
245
+ m = re.search(r"\tPN:([^\t]+)", ln) or re.search(r"\tID:([^\t]+)", ln)
246
+ if m and m.group(1) not in pg:
247
+ pg.append(m.group(1))
248
+ so = ""
249
+ for ln in hdr:
250
+ if ln.startswith("@HD"):
251
+ m = re.search(r"\tSO:(\S+)", ln)
252
+ so = m.group(1) if m else ""
253
+ names = []
254
+ for ln in sq[:30]:
255
+ m = re.search(r"\tSN:(\S+)\tLN:(\d+)", ln) or re.search(r"\tSN:(\S+)", ln)
256
+ if m:
257
+ names.append(m.group(1) if _REF_NAME.match(m.group(1)) else "(name withheld)")
258
+ parts = ["%d reference sequence%s in the header" % (len(sq), "" if len(sq) == 1 else "s")]
259
+ if names and not strict:
260
+ parts[-1] += " (%s%s)" % (", ".join(names[:10]), ", …" if len(sq) > 10 else "")
261
+ if so:
262
+ parts.append("sorted by %s" % so)
263
+ if rg:
264
+ parts.append("%d read group%s (sample names withheld)" % (len(rg), "" if len(rg) == 1 else "s"))
265
+ if pg and not strict:
266
+ parts.append("made with: %s" % ", ".join(pg[:6]))
267
+ return "; ".join(parts) + "."
268
+
269
+
270
+ def _describe_bam(path, shown, size, strict):
271
+ idx = any(os.path.exists(path + e) for e in (".bai", ".csi")) or os.path.exists(re.sub(r"\.bam$", ".bai", path))
272
+ out = "%s: BAM alignment file, %s; %s." % (shown, human(size), "indexed" if idx else "no index (.bai) next to it")
273
+ hs = _samtools_header_summary(path, strict)
274
+ if hs:
275
+ out += " " + hs
276
+ elif not shutil.which("samtools"):
277
+ out += " (samtools is not installed, so its header was not read.)"
278
+ if idx and shutil.which("samtools"):
279
+ try:
280
+ p = subprocess.run(["samtools", "idxstats", path], capture_output=True, timeout=30)
281
+ mapped = unmapped = 0
282
+ for ln in p.stdout.decode().splitlines():
283
+ f = ln.split("\t")
284
+ if len(f) == 4:
285
+ mapped += int(f[2])
286
+ unmapped += int(f[3])
287
+ out += " %s mapped and %s unmapped reads (from the index)." % (format(mapped, ","), format(unmapped, ","))
288
+ except Exception:
289
+ pass
290
+ return out
291
+
292
+
293
+ def _describe_fastq(path, shown, size, gz, sample, lines, fmt):
294
+ seqs, quals = [], []
295
+ for i in range(0, len(lines) - 3, 4):
296
+ if not lines[i].startswith("@"):
297
+ break
298
+ seqs.append(len(lines[i + 1].strip()))
299
+ quals.append(lines[i + 3].strip())
300
+ if gz or size > COUNT_LIMIT:
301
+ est = _estimate(path, gz, sample, 4)
302
+ count = "about %s reads (estimated)" % format(est, ",") if est else "reads"
303
+ if size <= COUNT_LIMIT // 4 and gz:
304
+ n, exact = _count_lines(path, gz)
305
+ if exact:
306
+ count = "%s reads" % format(n // 4, ",")
307
+ else:
308
+ n, exact = _count_lines(path, gz)
309
+ count = "%s reads" % format(n // 4, ",") if exact else "at least %s reads" % format(n // 4, ",")
310
+ mn = min(quals_ord(q) for q in quals if q) if quals else 64
311
+ enc = "Phred+33 (Sanger/Illumina 1.8+)" if mn < 59 else "possibly Phred+64 (old Illumina)" if mn >= 64 else "Phred+33"
312
+ hdr = lines[0]
313
+ paired = " Read names end in /1 or /2 (paired reads)." if re.search(r"/[12]\s*$", hdr.split()[0]) else (" The names look like Illumina CASAVA 1.8 (with a read number after the space)." if re.search(r"\s[12]:[YN]:", hdr) else "")
314
+ lens = "read length %d-%d (mean %.1f)" % (min(seqs), max(seqs), sum(seqs) / float(len(seqs))) if seqs else "read lengths unknown"
315
+ return "%s: FASTQ%s, %s; %s; %s; qualities look like %s.%s" % (shown, fmt, human(size), count, lens, enc, paired)
316
+
317
+
318
+ def quals_ord(q):
319
+ return min(ord(c) for c in q)
320
+
321
+
322
+ def _describe_fasta(path, shown, size, gz, sample, lines, fmt, strict):
323
+ names, lengths = [], []
324
+ cur = None
325
+ alphabet = set()
326
+ for ln in lines:
327
+ if ln.startswith(">"):
328
+ if cur is not None:
329
+ lengths.append(cur)
330
+ names.append(ln[1:].split()[0] if ln[1:].split() else "")
331
+ cur = 0
332
+ elif cur is not None:
333
+ s = ln.strip()
334
+ cur += len(s)
335
+ if len(alphabet) < 30:
336
+ alphabet.update(s.upper()[:200])
337
+ if cur is not None:
338
+ lengths.append(cur)
339
+ nuc = set("ACGTUNRYKMSWBDHV-*.")
340
+ kind = "DNA/RNA" if alphabet and alphabet <= nuc else "protein" if alphabet else "sequences"
341
+ whole = size <= COUNT_LIMIT and not (gz and size > COUNT_LIMIT // 4)
342
+ if whole:
343
+ n = 0
344
+ total_len = 0
345
+ try:
346
+ with _open_text(path, gz) as f:
347
+ for raw in f:
348
+ if raw.startswith(b">"):
349
+ n += 1
350
+ else:
351
+ total_len += len(raw.strip())
352
+ except (OSError, EOFError):
353
+ pass
354
+ count = "%s sequence%s, %s letters in all" % (format(n, ","), "" if n == 1 else "s", format(total_len, ","))
355
+ else:
356
+ count = "at least %d sequences (the file is large; not all were counted)" % len(names)
357
+ shown_names = ""
358
+ if not strict and names:
359
+ ok = [x for x in names[:12] if _REF_NAME.match(x)]
360
+ if ok and len(ok) == len(names[:12]):
361
+ shown_names = "; first names: %s%s" % (", ".join(ok[:8]), ", …" if len(names) > 8 else "")
362
+ else:
363
+ shown_names = "; sequence names withheld"
364
+ lens = ""
365
+ if lengths and len(sample) < SAMPLE_BYTES:
366
+ lens = "; lengths %s-%s" % (format(min(lengths), ","), format(max(lengths), ","))
367
+ idx = " An index (.fai) is next to it." if os.path.exists(path + ".fai") else ""
368
+ return "%s: FASTA (%s)%s, %s; %s%s%s.%s" % (shown, kind, fmt, human(size), count, lens, shown_names, idx)
369
+
370
+
371
+ def _describe_vcf(path, shown, size, gz, sample, lines, fmt, strict):
372
+ info, fmt_ids, contigs, samples = [], [], 0, 0
373
+ data_lines = 0
374
+ for ln in lines:
375
+ if ln.startswith("##INFO=<ID="):
376
+ info.append(ln[11:].split(",")[0])
377
+ elif ln.startswith("##FORMAT=<ID="):
378
+ fmt_ids.append(ln[13:].split(",")[0])
379
+ elif ln.startswith("##contig="):
380
+ contigs += 1
381
+ elif ln.startswith("#CHROM"):
382
+ samples = max(0, len(ln.split("\t")) - 9)
383
+ elif ln and not ln.startswith("#"):
384
+ data_lines += 1
385
+ if size <= COUNT_LIMIT and not (gz and size > COUNT_LIMIT // 4):
386
+ n = 0
387
+ try:
388
+ with _open_text(path, gz) as f:
389
+ for raw in f:
390
+ if not raw.startswith(b"#") and raw.strip():
391
+ n += 1
392
+ except (OSError, EOFError):
393
+ pass
394
+ count = "%s variant record%s" % (format(n, ","), "" if n == 1 else "s")
395
+ else:
396
+ count = "many variant records (not counted: the file is large)"
397
+ idx = " It has an index (%s)." % ", ".join(e for e in (".tbi", ".csi") if os.path.exists(path + e)) if any(os.path.exists(path + e) for e in (".tbi", ".csi")) else ""
398
+ parts = ["%s: VCF%s, %s; %s; %d sample%s (names withheld); %d contigs in the header" % (shown, fmt, human(size), count, samples, "" if samples == 1 else "s", contigs)]
399
+ if not strict:
400
+ if info:
401
+ parts.append("INFO fields: %s" % ", ".join(info[:25]))
402
+ if fmt_ids:
403
+ parts.append("FORMAT fields: %s" % ", ".join(fmt_ids[:25]))
404
+ if gz and fmt != " (BGZF)":
405
+ parts.append("it is gzip- but not bgzip-compressed, so it cannot be indexed with tabix as it is")
406
+ return "; ".join(parts) + "." + idx
407
+
408
+
409
+ def _describe_gff(path, shown, size, gz, lines, fmt):
410
+ types = {}
411
+ for ln in lines:
412
+ if ln.startswith("#") or not ln.strip():
413
+ continue
414
+ f = ln.split("\t")
415
+ if len(f) >= 9:
416
+ types[f[2]] = types.get(f[2], 0) + 1
417
+ n, exact = _count_lines(path, gz)
418
+ t = ", ".join("%s (%d)" % kv for kv in sorted(types.items(), key=lambda kv: -kv[1])[:10])
419
+ return "%s: GFF/GTF annotation%s, %s, %s%s lines; feature types in the first part: %s." % (shown, fmt, human(size), "" if exact else "at least ", format(n, ","), t or "none found")
420
+
421
+
422
+ def _describe_bed(path, shown, size, gz, lines, fmt):
423
+ cols = 0
424
+ for ln in lines:
425
+ if ln.strip() and not ln.startswith(("#", "track", "browser")):
426
+ cols = len(ln.split("\t"))
427
+ break
428
+ n, exact = _count_lines(path, gz)
429
+ return "%s: BED-like intervals%s, %s; %s%s lines; %d columns." % (shown, fmt, human(size), "" if exact else "at least ", format(n, ","), cols)
430
+
431
+
432
+ def _json_shape(obj, depth=0):
433
+ if depth > 2:
434
+ return "…"
435
+ if isinstance(obj, dict):
436
+ keys = list(obj)[:15]
437
+ inner = ", ".join("%s: %s" % (k, _json_shape(obj[k], depth + 1)) for k in keys)
438
+ return "{%s%s}" % (inner, ", …" if len(obj) > 15 else "")
439
+ if isinstance(obj, list):
440
+ return "[%d item%s%s]" % (len(obj), "" if len(obj) == 1 else "s", (" of " + _json_shape(obj[0], depth + 1)) if obj else "")
441
+ return type(obj).__name__.replace("str", "text").replace("float", "number").replace("int", "number")
442
+
443
+
444
+ def _describe_json(path, shown, size, gz, text, fmt, strict):
445
+ try:
446
+ if size <= COUNT_LIMIT // 4:
447
+ with _open_text(path, gz) as f:
448
+ obj = json.loads(f.read().decode("utf-8", "replace"))
449
+ else:
450
+ obj = json.loads(text)
451
+ except ValueError:
452
+ return "%s: JSON-like text%s, %s (it could not be read as JSON)." % (shown, fmt, human(size))
453
+ shape = _json_shape(obj) if not strict else type(obj).__name__
454
+ return "%s: JSON%s, %s; structure (keys and types, no values): %s" % (shown, fmt, human(size), shape)
455
+
456
+
457
+ def _describe_table_or_text(path, shown, size, gz, lines, fmt, strict, ext):
458
+ rows = [ln for ln in lines if ln.strip() and not ln.startswith("#")]
459
+ if not rows:
460
+ return "%s: a text file of comments only%s, %s." % (shown, fmt, human(size))
461
+ delim = None
462
+ for d in ("\t", ",", ";", "|"):
463
+ counts = [r.count(d) for r in rows[:50]]
464
+ if counts and min(counts) >= 1 and max(counts) == min(counts):
465
+ delim = d
466
+ break
467
+ if delim is None and ext in (".csv", ".tsv", ".tab"):
468
+ delim = "," if ext == ".csv" else "\t"
469
+ n, exact = _count_lines(path, gz)
470
+ total = "%s%s lines" % ("" if exact else "at least ", format(n, ","))
471
+ if delim is None:
472
+ words = sum(len(r.split()) for r in rows[:200]) / float(min(len(rows), 200))
473
+ return "%s: plain text%s, %s, %s (about %.0f words per line); not a table AskTim! recognises." % (shown, fmt, human(size), total, words)
474
+ name = {"\t": "tab-separated", ",": "comma-separated (CSV)", ";": "semicolon-separated", "|": "pipe-separated"}[delim]
475
+ try:
476
+ parsed = list(csv.reader(io.StringIO("\n".join(rows[:2000])), delimiter=delim))
477
+ except csv.Error:
478
+ parsed = [r.split(delim) for r in rows[:2000]]
479
+ if not parsed:
480
+ return "%s: %s table%s, %s, %s." % (shown, name, fmt, human(size), total)
481
+ ncol = max(len(r) for r in parsed[:50])
482
+ header = _looks_like_header(parsed)
483
+ body = parsed[1:] if header else parsed
484
+ kinds = []
485
+ for j in range(ncol):
486
+ vals = [r[j].strip() for r in body[:2000] if j < len(r)]
487
+ kinds.append(_column_kind(vals))
488
+ out = "%s: %s table%s, %s, %s; %d columns" % (shown, name, fmt, human(size), total, ncol)
489
+ if header and not strict:
490
+ cols = ["%s (%s)" % (_clip(h), k) for h, k in zip(parsed[0], kinds)]
491
+ out += "; the first line is a header. Columns: " + ", ".join(cols[:60]) + (", …" if ncol > 60 else "")
492
+ elif header:
493
+ out += "; the first line is a header (column names withheld in strict mode); kinds of values: " + ", ".join(kinds[:60])
494
+ else:
495
+ out += "; no header line was found; kinds of values by column: " + ", ".join("%d: %s" % (j + 1, k) for j, k in enumerate(kinds[:60]))
496
+ return out + "."
497
+
498
+
499
+ def _clip(s, n=40):
500
+ s = s.strip().strip('"')
501
+ return s if len(s) <= n else s[: n - 1] + "…"
502
+
503
+
504
+ def _is_number(v):
505
+ try:
506
+ float(v.replace(",", "")) if v.count(",") <= 3 else float(v)
507
+ return True
508
+ except ValueError:
509
+ return v.lower() in ("na", "nan", "inf", "-inf", "")
510
+
511
+
512
+ def _column_kind(vals):
513
+ vals = [v for v in vals if v != ""]
514
+ if not vals:
515
+ return "empty"
516
+ low = set(v.lower() for v in vals[:500])
517
+ if low <= {"true", "false", "t", "f", "yes", "no", "0", "1"} and len(low) <= 4 and not all(v in ("0", "1") for v in low):
518
+ return "true/false"
519
+ nums = sum(1 for v in vals if _is_number(v))
520
+ if nums == len(vals):
521
+ ints = all(re.fullmatch(r"-?\d+", v) for v in vals if v.lower() not in ("na", "nan"))
522
+ return "whole numbers" if ints else "numbers"
523
+ if nums >= 0.9 * len(vals):
524
+ return "numbers (some missing or text)"
525
+ distinct = len(set(vals))
526
+ if distinct <= 12 and len(vals) >= 20:
527
+ return "text, %d distinct values" % distinct
528
+ if all(re.fullmatch(r"\d{4}-\d\d-\d\d.*", v) for v in vals[:50]):
529
+ return "dates"
530
+ return "text"
531
+
532
+
533
+ def _looks_like_header(parsed):
534
+ if len(parsed) < 2:
535
+ return all(not _is_number(c) for c in parsed[0]) if parsed else False
536
+ first, rest = parsed[0], parsed[1:20]
537
+ if any(_is_number(c) and c.strip() for c in first):
538
+ return False
539
+ # a header if some column is numeric below it, or its cells are unlike the cells below
540
+ for j, c in enumerate(first):
541
+ below = [r[j] for r in rest if j < len(r)]
542
+ if below and all(_is_number(b) and b.strip() for b in below):
543
+ return True
544
+ try:
545
+ return csv.Sniffer().has_header("\n".join(",".join(r) for r in parsed[:20]))
546
+ except csv.Error:
547
+ return False
548
+
549
+
550
+ def is_code_file(path):
551
+ low = os.path.basename(path).lower()
552
+ stem = re.sub(r"\.(gz|bz2|xz)$", "", low)
553
+ ext = os.path.splitext(stem)[1]
554
+ return (ext in CODE_EXT and ext not in (".txt", ".json", ".ipynb", ".html")) or stem in CODE_NAMES
555
+
556
+
557
+ def listing(folder, max_entries=50, strict=False):
558
+ """Names and sizes of the files in a folder (one level, then one more for subfolders)."""
559
+ if strict:
560
+ try:
561
+ n = len([e for e in os.listdir(folder) if not e.startswith(".")])
562
+ except OSError:
563
+ n = 0
564
+ return "%d entries (names withheld in strict mode)" % n
565
+ out = []
566
+ more = 0
567
+
568
+ def walk(d, depth):
569
+ nonlocal more
570
+ try:
571
+ entries = sorted(os.scandir(d), key=lambda e: (not e.is_dir(), e.name.lower()))
572
+ except OSError:
573
+ return
574
+ for e in entries:
575
+ if e.name.startswith(".") or e.name in ("__pycache__", "node_modules"):
576
+ continue
577
+ if len(out) >= max_entries:
578
+ more += 1
579
+ continue
580
+ try:
581
+ if e.is_dir():
582
+ out.append(" " * depth + e.name + "/")
583
+ if depth == 0 and e.name not in ("asktim-runs",):
584
+ walk(e.path, depth + 1)
585
+ else:
586
+ out.append(" " * depth + "%s (%s)" % (e.name, human(e.stat().st_size)))
587
+ except OSError:
588
+ pass
589
+
590
+ walk(folder, 0)
591
+ if more:
592
+ out.append("… and %d more" % more)
593
+ return "\n".join(out) if out else "(empty)"