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/__init__.py +72 -0
- asktim/__main__.py +6 -0
- asktim/agent.py +490 -0
- asktim/api.py +41 -0
- asktim/chat.py +106 -0
- asktim/cli.py +577 -0
- asktim/config.py +316 -0
- asktim/context.py +156 -0
- asktim/fileinfo.py +593 -0
- asktim/history.py +214 -0
- asktim/inventory.py +379 -0
- asktim/logbook.py +159 -0
- asktim/net.py +151 -0
- asktim/notebook.py +1010 -0
- asktim/offline.py +110 -0
- asktim/paths.py +81 -0
- asktim/privacy.py +804 -0
- asktim/prompts.py +226 -0
- asktim/providers/__init__.py +173 -0
- asktim/providers/anthropic.py +227 -0
- asktim/providers/gemini.py +215 -0
- asktim/providers/openai.py +135 -0
- asktim/records.py +319 -0
- asktim/render.py +511 -0
- asktim/runner.py +308 -0
- asktim/safety.py +1495 -0
- asktim/shell_setup.py +183 -0
- asktim/ui.py +303 -0
- asktim/viewers.py +97 -0
- asktim-0.1.0.data/scripts/AskTim! +8 -0
- asktim-0.1.0.dist-info/METADATA +458 -0
- asktim-0.1.0.dist-info/RECORD +36 -0
- asktim-0.1.0.dist-info/WHEEL +5 -0
- asktim-0.1.0.dist-info/entry_points.txt +2 -0
- asktim-0.1.0.dist-info/licenses/LICENSE +21 -0
- asktim-0.1.0.dist-info/top_level.txt +1 -0
asktim/history.py
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
"""The student's recent shell commands (never their output).
|
|
2
|
+
|
|
3
|
+
Two sources, best first:
|
|
4
|
+
|
|
5
|
+
1. AskTim!'s shell hook (installed with `AskTim! setup-shell`): after every command the
|
|
6
|
+
shell appends one line - time, exit status, folder, command - to
|
|
7
|
+
~/.local/state/asktim/commands.tsv. It knows which command failed, and sees commands
|
|
8
|
+
as soon as they have run.
|
|
9
|
+
2. The shell's own history file (~/.bash_history, ~/.zsh_history, fish's history). Bash
|
|
10
|
+
writes it only when a terminal closes, so the latest commands may be missing; there is
|
|
11
|
+
no exit status.
|
|
12
|
+
|
|
13
|
+
AskTim!'s own commands are left out (they hold questions, and perhaps a key). Everything
|
|
14
|
+
returned here still goes through privacy.clean() before it is sent.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
import os
|
|
18
|
+
import re
|
|
19
|
+
import sys
|
|
20
|
+
import time
|
|
21
|
+
|
|
22
|
+
from . import paths
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class Command(object):
|
|
26
|
+
def __init__(self, line, status=None, cwd=None, when=None):
|
|
27
|
+
self.line = line
|
|
28
|
+
self.status = status # exit status, or None if not known
|
|
29
|
+
self.cwd = cwd
|
|
30
|
+
self.when = when
|
|
31
|
+
|
|
32
|
+
def __repr__(self):
|
|
33
|
+
return "Command(%r, status=%r)" % (self.line, self.status)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
_ASKTIM = re.compile(r"^\s*(?:command\s+|builtin\s+|\\)?(?:\S*/)?(?:AskTim!?|asktim!?)(?:\s|$)", re.I)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def is_asktim(line):
|
|
40
|
+
return bool(_ASKTIM.match(line or ""))
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def detect_shell():
|
|
44
|
+
"""bash, zsh, fish, sh, powershell ... - the shell that started us, else $SHELL."""
|
|
45
|
+
try:
|
|
46
|
+
ppid = os.getppid()
|
|
47
|
+
with open("/proc/%d/comm" % ppid) as f:
|
|
48
|
+
name = f.read().strip()
|
|
49
|
+
if name in ("bash", "zsh", "fish", "sh", "dash", "ksh", "tcsh", "csh"):
|
|
50
|
+
return name
|
|
51
|
+
except (OSError, AttributeError):
|
|
52
|
+
pass
|
|
53
|
+
if sys.platform.startswith("win"):
|
|
54
|
+
return "powershell"
|
|
55
|
+
return os.path.basename(os.environ.get("SHELL", "")) or "sh"
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _unmetafy(data):
|
|
59
|
+
"""zsh writes some bytes in its history as 0x83 followed by the byte XOR 32."""
|
|
60
|
+
out = bytearray()
|
|
61
|
+
it = iter(data)
|
|
62
|
+
for b in it:
|
|
63
|
+
if b == 0x83:
|
|
64
|
+
try:
|
|
65
|
+
out.append(next(it) ^ 32)
|
|
66
|
+
except StopIteration:
|
|
67
|
+
break
|
|
68
|
+
else:
|
|
69
|
+
out.append(b)
|
|
70
|
+
return bytes(out)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _tail_bytes(path, limit=400000):
|
|
74
|
+
try:
|
|
75
|
+
size = os.path.getsize(path)
|
|
76
|
+
with open(path, "rb") as f:
|
|
77
|
+
if size > limit:
|
|
78
|
+
f.seek(size - limit)
|
|
79
|
+
data = f.read()
|
|
80
|
+
if size > limit:
|
|
81
|
+
data = data.split(b"\n", 1)[-1]
|
|
82
|
+
return data
|
|
83
|
+
except OSError:
|
|
84
|
+
return b""
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def history_file(shell):
|
|
88
|
+
home = os.path.expanduser("~")
|
|
89
|
+
if os.environ.get("HISTFILE") and shell in ("bash", "zsh", "sh", "ksh"):
|
|
90
|
+
return os.environ["HISTFILE"]
|
|
91
|
+
if shell == "zsh":
|
|
92
|
+
return os.path.join(os.environ.get("ZDOTDIR", home), ".zsh_history")
|
|
93
|
+
if shell == "fish":
|
|
94
|
+
data = os.environ.get("XDG_DATA_HOME") or os.path.join(home, ".local", "share")
|
|
95
|
+
return os.path.join(data, "fish", "fish_history")
|
|
96
|
+
if shell == "powershell":
|
|
97
|
+
return os.path.join(os.environ.get("APPDATA", ""), "Microsoft", "Windows", "PowerShell", "PSReadLine", "ConsoleHost_history.txt")
|
|
98
|
+
return os.path.join(home, ".bash_history")
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def parse_bash(text):
|
|
102
|
+
cmds = []
|
|
103
|
+
for ln in text.splitlines():
|
|
104
|
+
if ln.startswith("#") and ln[1:].strip().isdigit():
|
|
105
|
+
continue # HISTTIMEFORMAT time stamps
|
|
106
|
+
if ln.strip():
|
|
107
|
+
cmds.append(Command(ln.rstrip()))
|
|
108
|
+
return cmds
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def parse_zsh(text):
|
|
112
|
+
cmds = []
|
|
113
|
+
buf = None
|
|
114
|
+
for ln in text.splitlines():
|
|
115
|
+
if buf is not None:
|
|
116
|
+
buf += "\n" + ln
|
|
117
|
+
else:
|
|
118
|
+
m = re.match(r"^: (\d+):\d+;(.*)$", ln)
|
|
119
|
+
if m:
|
|
120
|
+
buf = m.group(2)
|
|
121
|
+
when = int(m.group(1))
|
|
122
|
+
else:
|
|
123
|
+
buf = ln
|
|
124
|
+
when = None
|
|
125
|
+
if buf.endswith("\\"):
|
|
126
|
+
buf = buf[:-1]
|
|
127
|
+
continue
|
|
128
|
+
if buf.strip():
|
|
129
|
+
cmds.append(Command(buf, when=when))
|
|
130
|
+
buf = None
|
|
131
|
+
return cmds
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def parse_fish(text):
|
|
135
|
+
cmds = []
|
|
136
|
+
cur = None
|
|
137
|
+
for ln in text.splitlines():
|
|
138
|
+
if ln.startswith("- cmd: "):
|
|
139
|
+
if cur:
|
|
140
|
+
cmds.append(cur)
|
|
141
|
+
cmd = ln[len("- cmd: "):].replace("\\n", "\n").replace("\\\\", "\\")
|
|
142
|
+
cur = Command(cmd)
|
|
143
|
+
elif ln.startswith(" when: ") and cur is not None:
|
|
144
|
+
try:
|
|
145
|
+
cur.when = int(ln.split(":", 1)[1])
|
|
146
|
+
except ValueError:
|
|
147
|
+
pass
|
|
148
|
+
if cur:
|
|
149
|
+
cmds.append(cur)
|
|
150
|
+
return cmds
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def parse_hook_log(text):
|
|
154
|
+
cmds = []
|
|
155
|
+
for ln in text.splitlines():
|
|
156
|
+
parts = ln.split("\t", 3)
|
|
157
|
+
if len(parts) != 4:
|
|
158
|
+
continue
|
|
159
|
+
when, status, cwd, line = parts
|
|
160
|
+
try:
|
|
161
|
+
st = int(status)
|
|
162
|
+
except ValueError:
|
|
163
|
+
st = None
|
|
164
|
+
try:
|
|
165
|
+
w = int(float(when))
|
|
166
|
+
except ValueError:
|
|
167
|
+
w = None
|
|
168
|
+
cmds.append(Command(line.replace("\x1e", "\n"), status=st, cwd=cwd, when=w))
|
|
169
|
+
return cmds
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def hook_active(max_age_hours=12):
|
|
173
|
+
"""Is the shell hook writing its log (and recently)?"""
|
|
174
|
+
p = paths.commands_log()
|
|
175
|
+
try:
|
|
176
|
+
return time.time() - os.path.getmtime(p) < max_age_hours * 3600
|
|
177
|
+
except OSError:
|
|
178
|
+
return False
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def recent(n=20, shell=None):
|
|
182
|
+
"""(commands, source): the last n commands, oldest first, without AskTim!'s own."""
|
|
183
|
+
shell = shell or detect_shell()
|
|
184
|
+
source = None
|
|
185
|
+
cmds = []
|
|
186
|
+
if hook_active():
|
|
187
|
+
cmds = parse_hook_log(_tail_bytes(paths.commands_log()).decode("utf-8", "replace"))
|
|
188
|
+
source = "the AskTim! shell hook"
|
|
189
|
+
if not cmds:
|
|
190
|
+
f = history_file(shell)
|
|
191
|
+
raw = _tail_bytes(f)
|
|
192
|
+
if raw:
|
|
193
|
+
if shell == "zsh":
|
|
194
|
+
cmds = parse_zsh(_unmetafy(raw).decode("utf-8", "replace"))
|
|
195
|
+
elif shell == "fish":
|
|
196
|
+
cmds = parse_fish(raw.decode("utf-8", "replace"))
|
|
197
|
+
else:
|
|
198
|
+
cmds = parse_bash(raw.decode("utf-8", "replace"))
|
|
199
|
+
source = paths.pretty(f)
|
|
200
|
+
out = []
|
|
201
|
+
for c in cmds:
|
|
202
|
+
if is_asktim(c.line) or c.line.startswith(" "):
|
|
203
|
+
continue
|
|
204
|
+
if out and out[-1].line == c.line and out[-1].status == c.status:
|
|
205
|
+
continue
|
|
206
|
+
out.append(c)
|
|
207
|
+
return out[-n:] if n else out, source
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def last_failed(cmds):
|
|
211
|
+
for c in reversed(cmds):
|
|
212
|
+
if c.status not in (None, 0):
|
|
213
|
+
return c
|
|
214
|
+
return None
|
asktim/inventory.py
ADDED
|
@@ -0,0 +1,379 @@
|
|
|
1
|
+
"""What is installed on this computer: programs (with versions), Python and R packages.
|
|
2
|
+
|
|
3
|
+
The AI is told this list so that it suggests - and, as an agent, uses - only what is there.
|
|
4
|
+
Finding versions takes a second or two, so the result is kept in ~/.cache/asktim for 12
|
|
5
|
+
hours, or until PATH or the conda environment changes. `AskTim! tools` shows it and
|
|
6
|
+
looks again.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import concurrent.futures
|
|
10
|
+
import hashlib
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import platform
|
|
14
|
+
import re
|
|
15
|
+
import shutil
|
|
16
|
+
import subprocess
|
|
17
|
+
import sys
|
|
18
|
+
import time
|
|
19
|
+
|
|
20
|
+
from . import paths
|
|
21
|
+
|
|
22
|
+
# (command, category, how to ask for the version). The version command is run with a short
|
|
23
|
+
# timeout; its first line that holds a version number is used.
|
|
24
|
+
TOOLS = [
|
|
25
|
+
# quality control and trimming
|
|
26
|
+
("fastqc", "QC", ["--version"]), ("multiqc", "QC", ["--version"]), ("fastp", "QC", ["--version"]),
|
|
27
|
+
("cutadapt", "QC", ["--version"]), ("trimmomatic", "QC", ["-version"]), ("trim_galore", "QC", ["--version"]),
|
|
28
|
+
("seqkit", "QC", ["version"]), ("seqtk", "QC", []), ("NanoPlot", "QC", ["--version"]), ("nanoq", "QC", ["--version"]),
|
|
29
|
+
("porechop", "QC", ["--version"]), ("filtlong", "QC", ["--version"]), ("chopper", "QC", ["--version"]),
|
|
30
|
+
("bbduk.sh", "QC", ["--version"]), ("qualimap", "QC", ["--version"]),
|
|
31
|
+
# alignment and mapping
|
|
32
|
+
("bwa", "mapping", []), ("bwa-mem2", "mapping", ["version"]), ("bowtie2", "mapping", ["--version"]),
|
|
33
|
+
("bowtie", "mapping", ["--version"]), ("minimap2", "mapping", ["--version"]), ("hisat2", "mapping", ["--version"]),
|
|
34
|
+
("STAR", "mapping", ["--version"]), ("subread-align", "mapping", ["-v"]), ("blat", "mapping", []),
|
|
35
|
+
("nucmer", "mapping", ["--version"]), ("lastz", "mapping", ["--version"]),
|
|
36
|
+
# RNA-seq quantification
|
|
37
|
+
("salmon", "RNA-seq", ["--version"]), ("kallisto", "RNA-seq", ["version"]), ("featureCounts", "RNA-seq", ["-v"]),
|
|
38
|
+
("htseq-count", "RNA-seq", ["--version"]), ("stringtie", "RNA-seq", ["--version"]), ("rsem-calculate-expression", "RNA-seq", ["--version"]),
|
|
39
|
+
("umi_tools", "RNA-seq", ["--version"]), ("cellranger", "single-cell", ["--version"]), ("kb", "single-cell", ["--version"]),
|
|
40
|
+
("bustools", "single-cell", ["version"]), ("velocyto", "single-cell", ["--version"]),
|
|
41
|
+
# SAM/BAM/VCF and intervals
|
|
42
|
+
("samtools", "SAM/BAM/VCF", ["--version"]), ("bcftools", "SAM/BAM/VCF", ["--version"]), ("htsfile", "SAM/BAM/VCF", ["--version"]),
|
|
43
|
+
("bgzip", "SAM/BAM/VCF", ["--version"]), ("tabix", "SAM/BAM/VCF", ["--version"]), ("sambamba", "SAM/BAM/VCF", ["--version"]),
|
|
44
|
+
("picard", "SAM/BAM/VCF", ["SortSam", "--version"]), ("gatk", "variant calling", ["--version"]),
|
|
45
|
+
("freebayes", "variant calling", ["--version"]), ("lofreq", "variant calling", ["version"]), ("varscan", "variant calling", []),
|
|
46
|
+
("delly", "variant calling", ["--version"]), ("vcftools", "SAM/BAM/VCF", ["--version"]), ("snpEff", "annotation", ["-version"]),
|
|
47
|
+
("vep", "annotation", ["--help"]), ("mosdepth", "SAM/BAM/VCF", ["--version"]), ("bedtools", "intervals", ["--version"]),
|
|
48
|
+
("bedops", "intervals", ["--version"]), ("bamCoverage", "intervals", ["--version"]), ("computeMatrix", "intervals", ["--version"]),
|
|
49
|
+
("plotHeatmap", "intervals", ["--version"]), ("macs2", "ChIP/ATAC", ["--version"]), ("macs3", "ChIP/ATAC", ["--version"]),
|
|
50
|
+
("findMotifsGenome.pl", "ChIP/ATAC", []), ("meme", "motifs", ["-version"]), ("fimo", "motifs", ["--version"]),
|
|
51
|
+
("bismark", "methylation", ["--version"]), ("MethylDackel", "methylation", ["--version"]),
|
|
52
|
+
("plink", "genetics", ["--version"]), ("plink2", "genetics", ["--version"]), ("gffread", "annotation", ["--version"]),
|
|
53
|
+
("gffcompare", "annotation", ["--version"]), ("agat_convert_sp_gxf2gxf.pl", "annotation", ["--help"]),
|
|
54
|
+
# sequence search, alignment, phylogeny
|
|
55
|
+
("blastn", "search", ["-version"]), ("blastp", "search", ["-version"]), ("blastx", "search", ["-version"]),
|
|
56
|
+
("tblastn", "search", ["-version"]), ("makeblastdb", "search", ["-version"]), ("diamond", "search", ["version"]),
|
|
57
|
+
("mmseqs", "search", ["version"]), ("hmmsearch", "search", ["-h"]), ("hmmscan", "search", ["-h"]),
|
|
58
|
+
("hmmbuild", "search", ["-h"]), ("jackhmmer", "search", ["-h"]), ("nhmmer", "search", ["-h"]), ("cmsearch", "search", ["-h"]),
|
|
59
|
+
("mafft", "alignment", ["--version"]), ("muscle", "alignment", ["-version"]), ("clustalo", "alignment", ["--version"]),
|
|
60
|
+
("kalign", "alignment", ["--version"]), ("t_coffee", "alignment", ["-version"]), ("trimal", "alignment", ["--version"]),
|
|
61
|
+
("iqtree2", "phylogenetics", ["--version"]), ("iqtree", "phylogenetics", ["--version"]), ("raxml-ng", "phylogenetics", ["--version"]),
|
|
62
|
+
("FastTree", "phylogenetics", []), ("fasttree", "phylogenetics", []), ("mb", "phylogenetics", ["-v"]),
|
|
63
|
+
("treetime", "phylogenetics", ["--version"]), ("augur", "phylogenetics", ["--version"]), ("nextclade", "phylogenetics", ["--version"]),
|
|
64
|
+
# assembly, metagenomics, microbial genomics
|
|
65
|
+
("spades.py", "assembly", ["--version"]), ("megahit", "assembly", ["--version"]), ("flye", "assembly", ["--version"]),
|
|
66
|
+
("canu", "assembly", ["-version"]), ("velveth", "assembly", []), ("unicycler", "assembly", ["--version"]),
|
|
67
|
+
("hifiasm", "assembly", ["--version"]), ("Trinity", "assembly", ["--version"]), ("quast.py", "assembly", ["--version"]),
|
|
68
|
+
("busco", "assembly", ["--version"]), ("racon", "assembly", ["--version"]), ("medaka_consensus", "assembly", ["-h"]),
|
|
69
|
+
("pilon", "assembly", ["--version"]), ("prokka", "annotation", ["--version"]), ("bakta", "annotation", ["--version"]),
|
|
70
|
+
("prodigal", "annotation", ["-v"]), ("abricate", "microbial", ["--version"]), ("mlst", "microbial", ["--version"]),
|
|
71
|
+
("kraken2", "metagenomics", ["--version"]), ("bracken", "metagenomics", ["-v"]), ("metaphlan", "metagenomics", ["--version"]),
|
|
72
|
+
("humann", "metagenomics", ["--version"]), ("checkm", "metagenomics", []), ("gtdbtk", "metagenomics", ["--version"]),
|
|
73
|
+
# public data (these need the internet)
|
|
74
|
+
("prefetch", "public data", ["--version"]), ("fasterq-dump", "public data", ["--version"]), ("fastq-dump", "public data", ["--version"]),
|
|
75
|
+
("esearch", "public data", ["-version"]), ("efetch", "public data", ["-version"]), ("datasets", "public data", ["--version"]),
|
|
76
|
+
# workflows
|
|
77
|
+
("snakemake", "workflow", ["--version"]), ("nextflow", "workflow", ["-version"]), ("cwltool", "workflow", ["--version"]),
|
|
78
|
+
("make", "workflow", ["--version"]), ("parallel", "workflow", ["--version"]),
|
|
79
|
+
# languages and environments
|
|
80
|
+
("python3", "language", ["--version"]), ("python", "language", ["--version"]), ("R", "language", ["--version"]),
|
|
81
|
+
("Rscript", "language", ["--version"]), ("perl", "language", ["-v"]), ("java", "language", ["-version"]),
|
|
82
|
+
("julia", "language", ["--version"]), ("node", "language", ["--version"]), ("ruby", "language", ["--version"]),
|
|
83
|
+
("gcc", "language", ["--version"]), ("jupyter", "language", ["--version"]), ("ipython", "language", ["--version"]),
|
|
84
|
+
("conda", "environment", ["--version"]), ("mamba", "environment", ["--version"]), ("micromamba", "environment", ["--version"]),
|
|
85
|
+
("pip", "environment", ["--version"]), ("singularity", "environment", ["--version"]), ("apptainer", "environment", ["--version"]),
|
|
86
|
+
("docker", "environment", ["--version"]), ("sbatch", "cluster", ["--version"]), ("qsub", "cluster", ["--version"]),
|
|
87
|
+
# general tools
|
|
88
|
+
("git", "general", ["--version"]), ("curl", "general", ["--version"]), ("wget", "general", ["--version"]),
|
|
89
|
+
("jq", "general", ["--version"]), ("yq", "general", ["--version"]), ("awk", "general", ["--version"]), ("gawk", "general", ["--version"]),
|
|
90
|
+
("sed", "general", ["--version"]), ("grep", "general", ["--version"]), ("sort", "general", ["--version"]),
|
|
91
|
+
("datamash", "general", ["--version"]), ("mlr", "general", ["--version"]), ("csvlook", "general", ["--version"]),
|
|
92
|
+
("sqlite3", "general", ["--version"]), ("duckdb", "general", ["--version"]), ("pigz", "general", ["--version"]),
|
|
93
|
+
("zstd", "general", ["--version"]), ("xz", "general", ["--version"]), ("bzip2", "general", ["--help"]),
|
|
94
|
+
("gzip", "general", ["--version"]), ("unzip", "general", ["-v"]), ("tar", "general", ["--version"]),
|
|
95
|
+
("rsync", "general", ["--version"]), ("tree", "general", ["--version"]), ("column", "general", ["--version"]),
|
|
96
|
+
("tmux", "general", ["-V"]), ("screen", "general", ["--version"]), ("nano", "general", ["--version"]), ("vim", "general", ["--version"]),
|
|
97
|
+
# programs with windows
|
|
98
|
+
("igv", "viewer", []), ("igv.sh", "viewer", []), ("rstudio", "viewer", []), ("code", "viewer", ["--version"]),
|
|
99
|
+
("xdg-open", "viewer", ["--version"]), ("open", "viewer", []), ("firefox", "viewer", ["--version"]),
|
|
100
|
+
]
|
|
101
|
+
|
|
102
|
+
# looked for but worth naming when missing (the AI can say "X is not installed here")
|
|
103
|
+
COMMONLY_EXPECTED = [
|
|
104
|
+
"fastqc", "multiqc", "fastp", "cutadapt", "trimmomatic", "bwa", "bowtie2", "minimap2", "hisat2", "STAR",
|
|
105
|
+
"salmon", "kallisto", "featureCounts", "samtools", "bcftools", "bedtools", "gatk", "picard", "freebayes",
|
|
106
|
+
"blastn", "diamond", "mafft", "iqtree2", "spades.py", "kraken2", "snakemake", "nextflow", "R", "conda",
|
|
107
|
+
]
|
|
108
|
+
|
|
109
|
+
PY_PACKAGES = [
|
|
110
|
+
"numpy", "pandas", "scipy", "matplotlib", "seaborn", "plotly", "scikit-learn", "statsmodels", "biopython",
|
|
111
|
+
"pysam", "pybedtools", "pyranges", "cyvcf2", "pyvcf", "scanpy", "anndata", "scvi-tools", "squidpy", "muon",
|
|
112
|
+
"gseapy", "pydeseq2", "networkx", "umap-learn", "ete3", "dendropy", "polars", "pyarrow", "h5py", "tables",
|
|
113
|
+
"jupyterlab", "notebook", "ipywidgets", "torch", "tensorflow", "esm", "fair-esm", "transformers", "openpyxl",
|
|
114
|
+
"snakemake", "multiqc", "pybiomart", "mygene", "requests", "tqdm", "numba", "xarray", "zarr", "dask",
|
|
115
|
+
]
|
|
116
|
+
|
|
117
|
+
R_PACKAGES = [
|
|
118
|
+
"tidyverse", "ggplot2", "dplyr", "tidyr", "readr", "data.table", "DESeq2", "edgeR", "limma", "Seurat",
|
|
119
|
+
"SingleCellExperiment", "scran", "scater", "Biostrings", "GenomicRanges", "GenomicFeatures", "rtracklayer",
|
|
120
|
+
"Rsamtools", "VariantAnnotation", "vcfR", "clusterProfiler", "org.Hs.eg.db", "biomaRt", "ComplexHeatmap",
|
|
121
|
+
"pheatmap", "ape", "phangorn", "ggtree", "vegan", "phyloseq", "dada2", "tximport", "apeglm", "sva",
|
|
122
|
+
"WGCNA", "rmarkdown", "knitr", "shiny", "BiocManager", "lme4", "survival",
|
|
123
|
+
]
|
|
124
|
+
|
|
125
|
+
_VERSION_RE = re.compile(r"(?<![\w.])v?(\d+(?:\.\d+)+[a-z]?(?:[-+._][\w.]+)?|\d+[a-z]\d*)(?![\w])", re.I)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _cache_file():
|
|
129
|
+
return os.path.join(paths.cache_dir(), "inventory.json")
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _fingerprint():
|
|
133
|
+
h = hashlib.sha1()
|
|
134
|
+
for k in ("PATH", "CONDA_PREFIX", "VIRTUAL_ENV", "LOADEDMODULES"):
|
|
135
|
+
h.update((os.environ.get(k, "") + "\0").encode("utf-8", "replace"))
|
|
136
|
+
return h.hexdigest()
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _env():
|
|
140
|
+
env = dict(os.environ)
|
|
141
|
+
for k in list(env):
|
|
142
|
+
if re.search(r"KEY|TOKEN|SECRET|PASSWORD", k, re.I):
|
|
143
|
+
env.pop(k)
|
|
144
|
+
env.update({"PAGER": "cat", "NO_COLOR": "1", "TERM": "dumb", "MPLBACKEND": "Agg", "JAVA_TOOL_OPTIONS": ""})
|
|
145
|
+
return env
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _version_of(path, name, args, timeout):
|
|
149
|
+
try:
|
|
150
|
+
p = subprocess.run([path] + list(args), stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=timeout, env=_env())
|
|
151
|
+
out = p.stdout.decode("utf-8", "replace")
|
|
152
|
+
except (subprocess.TimeoutExpired, OSError):
|
|
153
|
+
return ""
|
|
154
|
+
return parse_version(out, name)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def parse_version(out, name=""):
|
|
158
|
+
"""The version in what a program printed about itself, or ''."""
|
|
159
|
+
lines = [ln.strip() for ln in out.splitlines() if ln.strip()]
|
|
160
|
+
low = name.lower().replace(".py", "").replace(".sh", "").replace(".pl", "")
|
|
161
|
+
# prefer a line that names the program or says "version"
|
|
162
|
+
ranked = sorted(lines[:40], key=lambda ln: (0 if low and low in ln.lower() else 1, 0 if "version" in ln.lower() else 1))
|
|
163
|
+
for ln in ranked:
|
|
164
|
+
if re.search(r"copyright|\(c\)|usage:|warning|license", ln, re.I) and not re.search(r"version", ln, re.I):
|
|
165
|
+
continue
|
|
166
|
+
ln2 = re.sub(r"\b(?:19|20)\d\d[-/]\d\d[-/]\d\d\b", " ", ln) # dates are not versions
|
|
167
|
+
m = _VERSION_RE.search(ln2)
|
|
168
|
+
if m:
|
|
169
|
+
v = m.group(1)
|
|
170
|
+
if re.fullmatch(r"\d{4}", v):
|
|
171
|
+
continue
|
|
172
|
+
return v[:40]
|
|
173
|
+
return ""
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _scan_tools(timeout=6.0):
|
|
177
|
+
found = {}
|
|
178
|
+
for name, cat, args in TOOLS:
|
|
179
|
+
p = shutil.which(name)
|
|
180
|
+
if p and name not in found:
|
|
181
|
+
found[name] = {"path": p, "category": cat, "args": args}
|
|
182
|
+
# some names are the same program twice
|
|
183
|
+
for a, b in (("python", "python3"), ("fasttree", "FastTree"), ("iqtree", "iqtree2"), ("gawk", "awk")):
|
|
184
|
+
if a in found and b in found and os.path.realpath(found[a]["path"]) == os.path.realpath(found[b]["path"]):
|
|
185
|
+
found.pop(a)
|
|
186
|
+
names = list(found)
|
|
187
|
+
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as ex:
|
|
188
|
+
futs = {ex.submit(_version_of, found[n]["path"], n, found[n]["args"], timeout if found[n]["args"] else 3.0): n for n in names}
|
|
189
|
+
for f in concurrent.futures.as_completed(futs):
|
|
190
|
+
n = futs[f]
|
|
191
|
+
try:
|
|
192
|
+
found[n]["version"] = f.result()
|
|
193
|
+
except Exception:
|
|
194
|
+
found[n]["version"] = ""
|
|
195
|
+
for v in found.values():
|
|
196
|
+
v.pop("args", None)
|
|
197
|
+
return found
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def _python_packages(python=None):
|
|
201
|
+
"""Packages of the Python that the student uses (the first python3 on PATH, or this one)."""
|
|
202
|
+
code = (
|
|
203
|
+
"import json,sys\n"
|
|
204
|
+
"try:\n import importlib.metadata as m\nexcept ImportError:\n import importlib_metadata as m\n"
|
|
205
|
+
"d={}\n"
|
|
206
|
+
"for x in m.distributions():\n"
|
|
207
|
+
" try:\n d[x.metadata['Name'].lower()]=x.version\n except Exception: pass\n"
|
|
208
|
+
"print(json.dumps({'python':sys.version.split()[0],'executable':sys.executable,'packages':d}))\n"
|
|
209
|
+
)
|
|
210
|
+
exe = python or shutil.which("python3") or shutil.which("python") or sys.executable
|
|
211
|
+
try:
|
|
212
|
+
p = subprocess.run([exe, "-c", code], stdin=subprocess.DEVNULL, capture_output=True, timeout=15, env=_env())
|
|
213
|
+
data = json.loads(p.stdout.decode("utf-8", "replace") or "{}")
|
|
214
|
+
except Exception:
|
|
215
|
+
return {}
|
|
216
|
+
pk = data.get("packages") or {}
|
|
217
|
+
wanted = {}
|
|
218
|
+
for name in PY_PACKAGES:
|
|
219
|
+
v = pk.get(name.lower())
|
|
220
|
+
if v:
|
|
221
|
+
wanted[name] = v
|
|
222
|
+
return {"python": data.get("python"), "executable": paths.pretty(data.get("executable") or exe), "packages": wanted, "count": len(pk)}
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _r_packages():
|
|
226
|
+
rs = shutil.which("Rscript")
|
|
227
|
+
if not rs:
|
|
228
|
+
return {}
|
|
229
|
+
code = 'ip <- installed.packages()[, c("Package", "Version")]; cat(paste(ip[,1], ip[,2]), sep="\\n")'
|
|
230
|
+
try:
|
|
231
|
+
p = subprocess.run([rs, "--vanilla", "-e", code], stdin=subprocess.DEVNULL, capture_output=True, timeout=30, env=_env())
|
|
232
|
+
except Exception:
|
|
233
|
+
return {}
|
|
234
|
+
allp = {}
|
|
235
|
+
for ln in p.stdout.decode("utf-8", "replace").splitlines():
|
|
236
|
+
parts = ln.split()
|
|
237
|
+
if len(parts) == 2:
|
|
238
|
+
allp[parts[0]] = parts[1]
|
|
239
|
+
return {"packages": {n: allp[n] for n in R_PACKAGES if n in allp}, "count": len(allp)}
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def _system():
|
|
243
|
+
info = {
|
|
244
|
+
"os": platform.system(),
|
|
245
|
+
"os_release": "",
|
|
246
|
+
"machine": platform.machine(),
|
|
247
|
+
"cpus": os.cpu_count() or 0,
|
|
248
|
+
"memory_gb": None,
|
|
249
|
+
"shell": os.path.basename(os.environ.get("SHELL", "")),
|
|
250
|
+
"conda_env": os.environ.get("CONDA_DEFAULT_ENV") or "",
|
|
251
|
+
"virtualenv": os.path.basename(os.environ.get("VIRTUAL_ENV", "")) if os.environ.get("VIRTUAL_ENV") else "",
|
|
252
|
+
"modules": "",
|
|
253
|
+
"colab": "COLAB_RELEASE_TAG" in os.environ or os.path.exists("/content") and "COLAB_GPU" in os.environ,
|
|
254
|
+
"gpu": bool(shutil.which("nvidia-smi")),
|
|
255
|
+
"scheduler": "slurm" if shutil.which("sbatch") else "pbs/sge" if shutil.which("qsub") else "",
|
|
256
|
+
}
|
|
257
|
+
if info["os"] == "Linux":
|
|
258
|
+
try:
|
|
259
|
+
with open("/etc/os-release") as f:
|
|
260
|
+
for ln in f:
|
|
261
|
+
if ln.startswith("PRETTY_NAME="):
|
|
262
|
+
info["os_release"] = ln.split("=", 1)[1].strip().strip('"')
|
|
263
|
+
except OSError:
|
|
264
|
+
pass
|
|
265
|
+
try:
|
|
266
|
+
with open("/proc/meminfo") as f:
|
|
267
|
+
for ln in f:
|
|
268
|
+
if ln.startswith("MemTotal:"):
|
|
269
|
+
info["memory_gb"] = round(int(ln.split()[1]) / 1048576.0, 1)
|
|
270
|
+
except (OSError, ValueError):
|
|
271
|
+
pass
|
|
272
|
+
if os.path.exists("/.dockerenv") or os.path.exists("/run/.containerenv"):
|
|
273
|
+
info["container"] = True
|
|
274
|
+
elif info["os"] == "Darwin":
|
|
275
|
+
info["os_release"] = "macOS " + platform.mac_ver()[0]
|
|
276
|
+
try:
|
|
277
|
+
out = subprocess.run(["sysctl", "-n", "hw.memsize"], capture_output=True, timeout=3).stdout
|
|
278
|
+
info["memory_gb"] = round(int(out) / 1073741824.0, 1)
|
|
279
|
+
except Exception:
|
|
280
|
+
pass
|
|
281
|
+
elif info["os"] == "Windows":
|
|
282
|
+
info["os_release"] = "Windows " + platform.release()
|
|
283
|
+
if os.environ.get("MODULESHOME") or os.environ.get("LMOD_CMD"):
|
|
284
|
+
info["modules"] = os.environ.get("LOADEDMODULES", "").replace(":", ", ") or "(none loaded)"
|
|
285
|
+
if "WSL_DISTRO_NAME" in os.environ:
|
|
286
|
+
info["wsl"] = os.environ["WSL_DISTRO_NAME"]
|
|
287
|
+
return info
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def gather(refresh=False, max_age=12 * 3600):
|
|
291
|
+
"""The inventory, from the cache if it is recent and nothing has changed."""
|
|
292
|
+
fp = _fingerprint()
|
|
293
|
+
cf = _cache_file()
|
|
294
|
+
if not refresh:
|
|
295
|
+
try:
|
|
296
|
+
with open(cf, encoding="utf-8") as f:
|
|
297
|
+
data = json.load(f)
|
|
298
|
+
if data.get("fingerprint") == fp and time.time() - data.get("time", 0) < max_age and data.get("version") == 2:
|
|
299
|
+
return data
|
|
300
|
+
except (OSError, ValueError):
|
|
301
|
+
pass
|
|
302
|
+
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as ex:
|
|
303
|
+
ft = ex.submit(_scan_tools)
|
|
304
|
+
fpy = ex.submit(_python_packages)
|
|
305
|
+
fr = ex.submit(_r_packages)
|
|
306
|
+
tools, py, r = ft.result(), fpy.result(), fr.result()
|
|
307
|
+
data = {"version": 2, "time": time.time(), "fingerprint": fp, "system": _system(), "tools": tools, "python": py, "r": r}
|
|
308
|
+
try:
|
|
309
|
+
paths.ensure(paths.cache_dir(), private=True)
|
|
310
|
+
tmp = cf + ".tmp"
|
|
311
|
+
with open(tmp, "w", encoding="utf-8") as f:
|
|
312
|
+
json.dump(data, f)
|
|
313
|
+
os.replace(tmp, cf)
|
|
314
|
+
except OSError:
|
|
315
|
+
pass
|
|
316
|
+
return data
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def is_installed(name):
|
|
320
|
+
return shutil.which(name) is not None
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def describe(inv, notebook_packages=None):
|
|
324
|
+
"""The inventory as lines for the AI."""
|
|
325
|
+
s = inv.get("system", {})
|
|
326
|
+
lines = []
|
|
327
|
+
osdesc = s.get("os_release") or s.get("os") or "unknown system"
|
|
328
|
+
extra = []
|
|
329
|
+
if s.get("cpus"):
|
|
330
|
+
extra.append("%d CPUs" % s["cpus"])
|
|
331
|
+
if s.get("memory_gb"):
|
|
332
|
+
extra.append("%s GB memory" % s["memory_gb"])
|
|
333
|
+
if s.get("gpu"):
|
|
334
|
+
extra.append("an NVIDIA GPU")
|
|
335
|
+
lines.append("System: %s (%s)%s." % (osdesc, s.get("machine", ""), (", " + ", ".join(extra)) if extra else ""))
|
|
336
|
+
if s.get("colab"):
|
|
337
|
+
lines.append("This is a Google Colab runtime (a temporary Linux machine; files outside Google Drive disappear when it stops).")
|
|
338
|
+
if s.get("wsl"):
|
|
339
|
+
lines.append("Windows Subsystem for Linux (%s)." % s["wsl"])
|
|
340
|
+
env = []
|
|
341
|
+
if s.get("shell"):
|
|
342
|
+
env.append("shell: " + s["shell"])
|
|
343
|
+
if s.get("conda_env"):
|
|
344
|
+
env.append("conda environment: " + s["conda_env"])
|
|
345
|
+
if s.get("virtualenv"):
|
|
346
|
+
env.append("virtualenv: " + s["virtualenv"])
|
|
347
|
+
if s.get("modules"):
|
|
348
|
+
env.append("environment modules (module load ...); loaded: " + s["modules"])
|
|
349
|
+
if s.get("scheduler"):
|
|
350
|
+
env.append("a job scheduler (%s)" % s["scheduler"])
|
|
351
|
+
if env:
|
|
352
|
+
lines.append("Environment: " + "; ".join(env) + ".")
|
|
353
|
+
tools = inv.get("tools", {})
|
|
354
|
+
by_cat = {}
|
|
355
|
+
for name in sorted(tools, key=str.lower):
|
|
356
|
+
t = tools[name]
|
|
357
|
+
by_cat.setdefault(t.get("category", "other"), []).append(name + (" " + t["version"] if t.get("version") else ""))
|
|
358
|
+
if tools:
|
|
359
|
+
lines.append("Installed programs (on PATH, with versions where they report one):")
|
|
360
|
+
order = ["QC", "mapping", "RNA-seq", "single-cell", "SAM/BAM/VCF", "variant calling", "intervals", "annotation", "ChIP/ATAC", "motifs", "methylation", "genetics", "search", "alignment", "phylogenetics", "assembly", "microbial", "metagenomics", "public data", "workflow", "cluster", "language", "environment", "general", "viewer"]
|
|
361
|
+
for cat in order + sorted(set(by_cat) - set(order)):
|
|
362
|
+
if cat in by_cat:
|
|
363
|
+
lines.append(" - %s: %s" % (cat, ", ".join(by_cat[cat])))
|
|
364
|
+
missing = [n for n in COMMONLY_EXPECTED if n not in tools]
|
|
365
|
+
if missing:
|
|
366
|
+
lines.append("Not installed (often used, but not on this computer): %s." % ", ".join(missing))
|
|
367
|
+
py = notebook_packages or inv.get("python") or {}
|
|
368
|
+
if py.get("python"):
|
|
369
|
+
pk = py.get("packages") or {}
|
|
370
|
+
lines.append("Python %s%s; packages: %s%s." % (
|
|
371
|
+
py["python"],
|
|
372
|
+
"" if notebook_packages else " (%s)" % py.get("executable", "python3"),
|
|
373
|
+
", ".join("%s %s" % (k, v) for k, v in sorted(pk.items(), key=lambda kv: kv[0].lower())) or "(none of the usual data-science packages)",
|
|
374
|
+
("; %d packages in all" % py["count"]) if py.get("count") else "",
|
|
375
|
+
))
|
|
376
|
+
r = inv.get("r") or {}
|
|
377
|
+
if r.get("count"):
|
|
378
|
+
lines.append("R packages: %s; %d packages in all." % (", ".join("%s %s" % kv for kv in sorted(r.get("packages", {}).items())) or "none of the usual Bioconductor/tidyverse packages", r["count"]))
|
|
379
|
+
return lines
|