aimancli 0.2.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.
- aiman/__init__.py +0 -0
- aiman/cli.py +53 -0
- aiman/core/__init__.py +1 -0
- aiman/core/classifiers.py +38 -0
- aiman/core/pipeline.py +129 -0
- aiman/core/registry.py +15 -0
- aiman/core/safety.py +63 -0
- aiman/core/tagger.py +70 -0
- aiman/core/tool.py +61 -0
- aiman/tools/__init__.py +0 -0
- aiman/tools/find/__init__.py +63 -0
- aiman/tools/find/fixture.py +63 -0
- aiman/tools/find/rules.py +208 -0
- aiman/tools/find/schema.json +98 -0
- aiman/tools/find/slots.py +224 -0
- aiman/tools/find/templates.py +690 -0
- aiman/tools/ls/__init__.py +42 -0
- aiman/tools/ls/fixture.py +88 -0
- aiman/tools/ls/rules.py +109 -0
- aiman/tools/ls/schema.json +28 -0
- aiman/tools/ls/slots.py +245 -0
- aiman/tools/ls/templates.py +422 -0
- aimancli-0.2.0.dist-info/METADATA +99 -0
- aimancli-0.2.0.dist-info/RECORD +28 -0
- aimancli-0.2.0.dist-info/WHEEL +5 -0
- aimancli-0.2.0.dist-info/entry_points.txt +2 -0
- aimancli-0.2.0.dist-info/licenses/LICENSE +674 -0
- aimancli-0.2.0.dist-info/top_level.txt +1 -0
aiman/__init__.py
ADDED
|
File without changes
|
aiman/cli.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""aiman command line.
|
|
2
|
+
|
|
3
|
+
aiman find "delete .tmp files older than 7 days in /tmp" # show, confirm, run
|
|
4
|
+
aiman find -n "..." # print only
|
|
5
|
+
aiman build <tool> | train <tool> | eval <tool> | all <tool>
|
|
6
|
+
aiman list
|
|
7
|
+
"""
|
|
8
|
+
import json
|
|
9
|
+
import sys
|
|
10
|
+
|
|
11
|
+
from aiman.core import pipeline, registry, safety
|
|
12
|
+
|
|
13
|
+
ADMIN = ("build", "train", "eval", "all", "list")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def main(argv=None):
|
|
17
|
+
argv = list(sys.argv[1:] if argv is None else argv)
|
|
18
|
+
if not argv or argv[0] in ("-h", "--help"):
|
|
19
|
+
print(__doc__.strip())
|
|
20
|
+
return 0
|
|
21
|
+
cmd = argv.pop(0)
|
|
22
|
+
|
|
23
|
+
if cmd == "list":
|
|
24
|
+
print("\n".join(registry.available()))
|
|
25
|
+
return 0
|
|
26
|
+
if cmd in ADMIN:
|
|
27
|
+
if not argv:
|
|
28
|
+
print(f"usage: aiman {cmd} <tool>")
|
|
29
|
+
return 2
|
|
30
|
+
tool = registry.load(argv[0])
|
|
31
|
+
if cmd in ("build", "all"):
|
|
32
|
+
print("dataset:", json.dumps(pipeline.build_dataset(tool)))
|
|
33
|
+
if cmd in ("train", "all"):
|
|
34
|
+
print("train: ", json.dumps(pipeline.train(tool)))
|
|
35
|
+
if cmd in ("eval", "all"):
|
|
36
|
+
print("eval: ", json.dumps(pipeline.evaluate(tool, show=5 if cmd == "eval" else 0), indent=1))
|
|
37
|
+
return 0
|
|
38
|
+
|
|
39
|
+
tool = registry.load(cmd)
|
|
40
|
+
dry = yes = False
|
|
41
|
+
while argv and argv[0] in ("-n", "--dry-run", "-y", "--yes"):
|
|
42
|
+
flag = argv.pop(0)
|
|
43
|
+
dry |= flag in ("-n", "--dry-run")
|
|
44
|
+
yes |= flag in ("-y", "--yes")
|
|
45
|
+
intent = " ".join(argv).strip()
|
|
46
|
+
if not intent:
|
|
47
|
+
print(f'usage: aiman {cmd} [-n|-y] "<intent>"')
|
|
48
|
+
return 2
|
|
49
|
+
return safety.run(pipeline.Predictor(tool), intent, dry=dry, yes=yes)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
if __name__ == "__main__":
|
|
53
|
+
sys.exit(main())
|
aiman/core/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Shared machinery: tagger, classifiers, pipeline, safety, plugin contract."""
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""Tool-agnostic sentence classifiers: one model per categorical slot.
|
|
2
|
+
|
|
3
|
+
TF-IDF word 1-2grams + char 2-4grams -> logistic regression.
|
|
4
|
+
"""
|
|
5
|
+
from sklearn.feature_extraction.text import TfidfVectorizer
|
|
6
|
+
from sklearn.linear_model import LogisticRegression
|
|
7
|
+
from sklearn.pipeline import make_pipeline, make_union
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _make():
|
|
11
|
+
feats = make_union(TfidfVectorizer(ngram_range=(1, 2), sublinear_tf=True),
|
|
12
|
+
TfidfVectorizer(analyzer="char_wb", ngram_range=(2, 4), sublinear_tf=True))
|
|
13
|
+
return make_pipeline(feats, LogisticRegression(max_iter=3000, C=10))
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def train(texts, labels):
|
|
17
|
+
"""texts: list[str]; labels: list[dict name->label]. Returns {name: model}."""
|
|
18
|
+
models = {}
|
|
19
|
+
for k in labels[0]:
|
|
20
|
+
y = [d[k] for d in labels]
|
|
21
|
+
if len(set(y)) < 2:
|
|
22
|
+
continue
|
|
23
|
+
models[k] = _make().fit(texts, y)
|
|
24
|
+
return models
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def predict(models, text):
|
|
28
|
+
return {k: m.predict([text])[0] for k, m in models.items()}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def confidence(models, text):
|
|
32
|
+
"""Lowest top-class probability across classifiers -> (prob, classifier name)."""
|
|
33
|
+
worst, which = 1.0, None
|
|
34
|
+
for k, m in models.items():
|
|
35
|
+
p = max(m.predict_proba([text])[0])
|
|
36
|
+
if p < worst:
|
|
37
|
+
worst, which = p, k
|
|
38
|
+
return worst, which
|
aiman/core/pipeline.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
"""Tool-agnostic pipeline: dataset -> slot labels -> train -> evaluate -> predict.
|
|
2
|
+
|
|
3
|
+
Files live under $AIMAN_HOME. Default: the repo root when run from a source checkout,
|
|
4
|
+
otherwise $XDG_DATA_HOME/aiman (usually ~/.local/share/aiman) for pip installs.
|
|
5
|
+
data/<tool>/{train,val}.jsonl models/<tool>/{tagger,classifiers}.joblib
|
|
6
|
+
"""
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
import random
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
import joblib
|
|
13
|
+
|
|
14
|
+
from aiman.core import classifiers, tagger
|
|
15
|
+
|
|
16
|
+
def _default_home():
|
|
17
|
+
repo = Path(__file__).resolve().parents[2]
|
|
18
|
+
if (repo / "pyproject.toml").exists(): # running from a source checkout
|
|
19
|
+
return repo
|
|
20
|
+
xdg = os.environ.get("XDG_DATA_HOME") or Path.home() / ".local" / "share"
|
|
21
|
+
return Path(xdg) / "aiman"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
HOME = Path(os.environ.get("AIMAN_HOME") or _default_home())
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def data_dir(tool):
|
|
28
|
+
return HOME / "data" / tool.name
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def model_dir(tool):
|
|
32
|
+
return HOME / "models" / tool.name
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _write(path, rows):
|
|
36
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
37
|
+
with open(path, "w") as f:
|
|
38
|
+
for r in rows:
|
|
39
|
+
f.write(json.dumps(r) + "\n")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _read(path):
|
|
43
|
+
return [json.loads(l) for l in open(path)]
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
# ---------------------------------------------------------------- 1. dataset
|
|
47
|
+
def build_dataset(tool, seed=42, val_frac=0.05):
|
|
48
|
+
pairs = tool.generate(seed)
|
|
49
|
+
rows, bad = [], []
|
|
50
|
+
for intent, cmd in pairs:
|
|
51
|
+
ok, err = tool.validate(cmd)
|
|
52
|
+
(rows if ok else bad).append({"instruction": intent, "output": cmd, **({} if ok else {"error": err})})
|
|
53
|
+
rows = [label(tool, r) for r in rows]
|
|
54
|
+
random.Random(seed).shuffle(rows)
|
|
55
|
+
n_val = max(1, int(len(rows) * val_frac))
|
|
56
|
+
_write(data_dir(tool) / "val.jsonl", rows[:n_val])
|
|
57
|
+
_write(data_dir(tool) / "train.jsonl", rows[n_val:])
|
|
58
|
+
in_schema = sum(1 for r in rows if r["slots"])
|
|
59
|
+
stats = {"pairs": len(pairs), "valid": len(rows), "invalid": len(bad), "in_schema": in_schema,
|
|
60
|
+
"train": len(rows) - n_val, "val": n_val}
|
|
61
|
+
if bad:
|
|
62
|
+
stats["first_invalid"] = bad[0]
|
|
63
|
+
return stats
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def label(tool, row):
|
|
67
|
+
"""Attach slots + BIO tags; rows whose rebuild isn't equivalent are left unlabelled."""
|
|
68
|
+
s = tool.parse(row["output"])
|
|
69
|
+
if s is not None and not tool.equivalent(tool.build(s), row["output"]):
|
|
70
|
+
s = None
|
|
71
|
+
toks, tags = tool.tag(row["instruction"], s) if s else (row["instruction"].split(), None)
|
|
72
|
+
return {**row, "slots": s, "tokens": toks, "tags": tags}
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
# ---------------------------------------------------------------- 2. train
|
|
76
|
+
def train(tool):
|
|
77
|
+
if not (data_dir(tool) / "train.jsonl").exists():
|
|
78
|
+
build_dataset(tool)
|
|
79
|
+
rows = [r for r in _read(data_dir(tool) / "train.jsonl") if r["slots"]]
|
|
80
|
+
tg = tagger.train(rows)
|
|
81
|
+
clf = classifiers.train([r["instruction"] for r in rows],
|
|
82
|
+
[tool.targets(r["slots"], r["instruction"]) for r in rows])
|
|
83
|
+
md = model_dir(tool)
|
|
84
|
+
md.mkdir(parents=True, exist_ok=True)
|
|
85
|
+
joblib.dump(tg, md / "tagger.joblib", compress=3)
|
|
86
|
+
joblib.dump(clf, md / "classifiers.joblib", compress=3)
|
|
87
|
+
size = sum(p.stat().st_size for p in md.glob("*.joblib"))
|
|
88
|
+
return {"rows": len(rows), "classifiers": len(clf), "model_mb": round(size / 1e6, 2)}
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
# ---------------------------------------------------------------- 3. predict
|
|
92
|
+
class Predictor:
|
|
93
|
+
def __init__(self, tool):
|
|
94
|
+
md = model_dir(tool)
|
|
95
|
+
if not (md / "tagger.joblib").exists():
|
|
96
|
+
raise SystemExit(f"aiman: no models for '{tool.name}'. Run: aiman all {tool.name}")
|
|
97
|
+
self.tool = tool
|
|
98
|
+
self.tagger = joblib.load(md / "tagger.joblib")
|
|
99
|
+
self.clf = joblib.load(md / "classifiers.joblib")
|
|
100
|
+
|
|
101
|
+
def slots(self, text):
|
|
102
|
+
return self.tool.assemble(text, tagger.spans(self.tagger, text), classifiers.predict(self.clf, text))
|
|
103
|
+
|
|
104
|
+
def command(self, text):
|
|
105
|
+
s, err = self.slots(text)
|
|
106
|
+
return (None, err) if err else (self.tool.build(s), None)
|
|
107
|
+
|
|
108
|
+
def confidence(self, text):
|
|
109
|
+
return classifiers.confidence(self.clf, text)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
# ---------------------------------------------------------------- 4. evaluate
|
|
113
|
+
def evaluate(tool, split="val", show=0):
|
|
114
|
+
rows = _read(data_dir(tool) / f"{split}.jsonl")
|
|
115
|
+
p = Predictor(tool)
|
|
116
|
+
in_schema = [r for r in rows if r["slots"]]
|
|
117
|
+
ok, misses = 0, []
|
|
118
|
+
for r in in_schema:
|
|
119
|
+
cmd, err = p.command(r["instruction"])
|
|
120
|
+
if cmd and (cmd == r["output"] or tool.equivalent(cmd, r["output"])):
|
|
121
|
+
ok += 1
|
|
122
|
+
else:
|
|
123
|
+
misses.append({"intent": r["instruction"], "gold": r["output"], "pred": cmd or err})
|
|
124
|
+
res = {"split": split, "in_schema": len(in_schema), "correct": ok,
|
|
125
|
+
"acc_in_schema": round(ok / max(1, len(in_schema)), 4),
|
|
126
|
+
"acc_all": round(ok / max(1, len(rows)), 4)}
|
|
127
|
+
if show:
|
|
128
|
+
res["misses"] = misses[:show]
|
|
129
|
+
return res
|
aiman/core/registry.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""Find tools: each package aiman/tools/<cmd>/ exposes TOOL = <Tool instance>."""
|
|
2
|
+
import importlib
|
|
3
|
+
import pkgutil
|
|
4
|
+
|
|
5
|
+
import aiman.tools
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def available():
|
|
9
|
+
return sorted(m.name for m in pkgutil.iter_modules(aiman.tools.__path__) if m.ispkg)
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def load(name):
|
|
13
|
+
if name not in available():
|
|
14
|
+
raise SystemExit(f"aiman: no tool '{name}'. Available: {', '.join(available()) or 'none'}")
|
|
15
|
+
return importlib.import_module(f"aiman.tools.{name}").TOOL
|
aiman/core/safety.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""Show, preview, confirm, run -- shared by every tool."""
|
|
2
|
+
import subprocess
|
|
3
|
+
import sys
|
|
4
|
+
|
|
5
|
+
CONF_MIN = 0.55
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def _c():
|
|
9
|
+
if sys.stdout.isatty():
|
|
10
|
+
return {"y": "\033[33m", "r": "\033[31m", "b": "\033[1m", "0": "\033[0m"}
|
|
11
|
+
return {"y": "", "r": "", "b": "", "0": ""}
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _ask(prompt):
|
|
15
|
+
try:
|
|
16
|
+
return input(prompt).strip().lower()
|
|
17
|
+
except EOFError:
|
|
18
|
+
return ""
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def run(predictor, intent, dry=False, yes=False):
|
|
22
|
+
C, tool = _c(), predictor.tool
|
|
23
|
+
cmd, err = predictor.command(intent)
|
|
24
|
+
if not cmd:
|
|
25
|
+
print(f"{C['r']}aiman: can't map that intent ({err}). Try rephrasing or see `man {tool.name}`.{C['0']}")
|
|
26
|
+
return 1
|
|
27
|
+
conf, weak = predictor.confidence(intent)
|
|
28
|
+
print(f"{C['b']}{cmd}{C['0']}")
|
|
29
|
+
if conf < CONF_MIN:
|
|
30
|
+
print(f"{C['y']}! low confidence ({conf:.2f}) on '{weak}' -- check the command{C['0']}")
|
|
31
|
+
if dry:
|
|
32
|
+
return 0
|
|
33
|
+
|
|
34
|
+
if tool.is_destructive(cmd):
|
|
35
|
+
reason = tool.refuse(cmd)
|
|
36
|
+
if reason:
|
|
37
|
+
print(f"{C['r']}refused: {reason}. Edit and run it yourself.{C['0']}")
|
|
38
|
+
return 3
|
|
39
|
+
pv = tool.preview(cmd)
|
|
40
|
+
if pv:
|
|
41
|
+
out = subprocess.run(["bash", "-c", pv], capture_output=True, text=True).stdout
|
|
42
|
+
items = [l for l in out.splitlines() if l]
|
|
43
|
+
print(f"{C['y']}destructive -- would affect {len(items)} item(s):{C['0']}")
|
|
44
|
+
for i in items[:10]:
|
|
45
|
+
print(" ", i)
|
|
46
|
+
if len(items) > 10:
|
|
47
|
+
print(f" ... and {len(items) - 10} more")
|
|
48
|
+
if not items:
|
|
49
|
+
print("nothing matched; not running.")
|
|
50
|
+
return 0
|
|
51
|
+
if yes:
|
|
52
|
+
print(f"{C['r']}-y ignored for destructive commands.{C['0']}")
|
|
53
|
+
ok = _ask("type 'yes' to run: ") == "yes"
|
|
54
|
+
elif yes:
|
|
55
|
+
ok = True
|
|
56
|
+
else:
|
|
57
|
+
a = _ask("run it? [Y/n] " if conf >= CONF_MIN else "run it? [y/N] ")
|
|
58
|
+
ok = a in ("y", "yes") or (a == "" and conf >= CONF_MIN)
|
|
59
|
+
|
|
60
|
+
if not ok:
|
|
61
|
+
print("cancelled.")
|
|
62
|
+
return 0
|
|
63
|
+
return subprocess.call(["bash", "-c", cmd])
|
aiman/core/tagger.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""Tool-agnostic span tagger: token -> B-SLOT / O.
|
|
2
|
+
|
|
3
|
+
Windowed lexical features + logistic regression. Small, CPU-only, fast.
|
|
4
|
+
"""
|
|
5
|
+
import re
|
|
6
|
+
|
|
7
|
+
from sklearn.feature_extraction import DictVectorizer
|
|
8
|
+
from sklearn.linear_model import LogisticRegression
|
|
9
|
+
from sklearn.pipeline import make_pipeline
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _norm(w):
|
|
13
|
+
return w.lower().strip("?,\"")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _shape(w):
|
|
17
|
+
s = re.sub(r"[A-Z]", "A", w)
|
|
18
|
+
s = re.sub(r"[a-z]", "a", s)
|
|
19
|
+
s = re.sub(r"\d", "9", s)
|
|
20
|
+
return re.sub(r"(.)\1+", r"\1\1", s)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def features(toks, i):
|
|
24
|
+
w = toks[i]
|
|
25
|
+
lw = _norm(w)
|
|
26
|
+
f = {
|
|
27
|
+
"w": lw, "shape": _shape(w), "pre3": lw[:3], "suf3": lw[-3:], "suf2": lw[-2:],
|
|
28
|
+
"is_digit": lw.isdigit(), "has_digit": any(c.isdigit() for c in lw),
|
|
29
|
+
"starts_slash": lw.startswith("/") or lw.startswith("~"), "has_slash": "/" in lw,
|
|
30
|
+
"starts_dot": lw.startswith("."), "has_dot": "." in lw[1:],
|
|
31
|
+
"unit": bool(re.search(r"\d*(k|kb|m|mb|meg|megs|g|gb|gigabytes?|megabytes?|kilobytes?)$", lw)),
|
|
32
|
+
"num_unit": bool(re.match(r"^\d+(k|kb|m|mb|g|gb)$", lw)),
|
|
33
|
+
"pos": min(i, 5), "is_last": i == len(toks) - 1,
|
|
34
|
+
}
|
|
35
|
+
for d in (-3, -2, -1, 1, 2):
|
|
36
|
+
j = i + d
|
|
37
|
+
f[f"w{d}"] = _norm(toks[j]) if 0 <= j < len(toks) else ("<s>" if j < 0 else "</s>")
|
|
38
|
+
f["bigram-1"] = f["w-1"] + "|" + lw
|
|
39
|
+
f["bigram+1"] = lw + "|" + f["w1"]
|
|
40
|
+
f["trigram-2"] = f["w-2"] + "|" + f["w-1"]
|
|
41
|
+
return f
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def train(rows):
|
|
45
|
+
"""rows: dicts with 'tokens' and 'tags' (rows without tags are skipped)."""
|
|
46
|
+
X, y = [], []
|
|
47
|
+
for r in rows:
|
|
48
|
+
if not r.get("tags"):
|
|
49
|
+
continue
|
|
50
|
+
for i in range(len(r["tokens"])):
|
|
51
|
+
X.append(features(r["tokens"], i))
|
|
52
|
+
y.append(r["tags"][i])
|
|
53
|
+
model = make_pipeline(DictVectorizer(sparse=True),
|
|
54
|
+
LogisticRegression(max_iter=2000, C=5.0, class_weight="balanced"))
|
|
55
|
+
model.fit(X, y)
|
|
56
|
+
return model
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def predict_tags(model, toks):
|
|
60
|
+
return list(model.predict([features(toks, i) for i in range(len(toks))])) if toks else []
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def spans(model, text):
|
|
64
|
+
"""text -> {SLOT: [words...]}"""
|
|
65
|
+
toks = text.split()
|
|
66
|
+
out = {}
|
|
67
|
+
for w, t in zip(toks, predict_tags(model, toks)):
|
|
68
|
+
if t != "O":
|
|
69
|
+
out.setdefault(t[2:], []).append(w.strip("?,\""))
|
|
70
|
+
return out
|
aiman/core/tool.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""The plugin contract every command in aiman/tools/<cmd>/ implements.
|
|
2
|
+
|
|
3
|
+
A tool supplies the command-specific parts; core supplies training, inference,
|
|
4
|
+
evaluation and the safety prompt. Add a command by subclassing Tool.
|
|
5
|
+
"""
|
|
6
|
+
from abc import ABC, abstractmethod
|
|
7
|
+
from typing import Dict, List, Optional, Tuple
|
|
8
|
+
|
|
9
|
+
Slots = dict
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Tool(ABC):
|
|
13
|
+
name: str = "" # e.g. "find"; also the CLI word: aiman find "..."
|
|
14
|
+
destructive_pattern = None # compiled regex; matches commands that change or remove things
|
|
15
|
+
|
|
16
|
+
# ---- dataset
|
|
17
|
+
@abstractmethod
|
|
18
|
+
def generate(self, seed: int = 42) -> List[Tuple[str, str]]:
|
|
19
|
+
"""Return unique (intent, command) pairs."""
|
|
20
|
+
|
|
21
|
+
@abstractmethod
|
|
22
|
+
def validate(self, cmd: str) -> Tuple[bool, str]:
|
|
23
|
+
"""Syntax-check a command safely (sandbox). Returns (ok, error)."""
|
|
24
|
+
|
|
25
|
+
# ---- slots
|
|
26
|
+
@abstractmethod
|
|
27
|
+
def parse(self, cmd: str) -> Optional[Slots]:
|
|
28
|
+
"""Command -> slots, or None if outside the schema."""
|
|
29
|
+
|
|
30
|
+
@abstractmethod
|
|
31
|
+
def build(self, slots: Slots) -> str:
|
|
32
|
+
"""Slots -> canonical command (the rule engine)."""
|
|
33
|
+
|
|
34
|
+
@abstractmethod
|
|
35
|
+
def tag(self, intent: str, slots: Slots) -> Tuple[List[str], List[str]]:
|
|
36
|
+
"""Intent + gold slots -> (tokens, BIO tags) for the span tagger."""
|
|
37
|
+
|
|
38
|
+
@abstractmethod
|
|
39
|
+
def targets(self, slots: Slots, intent: str) -> Dict[str, str]:
|
|
40
|
+
"""Gold slots -> {classifier name: label} for the sentence classifiers."""
|
|
41
|
+
|
|
42
|
+
@abstractmethod
|
|
43
|
+
def assemble(self, intent: str, spans: Dict[str, List[str]],
|
|
44
|
+
classes: Dict[str, str]) -> Tuple[Slots, Optional[str]]:
|
|
45
|
+
"""Predicted spans + classes -> slots (or an error message)."""
|
|
46
|
+
|
|
47
|
+
# ---- evaluation / safety
|
|
48
|
+
def equivalent(self, a: str, b: str) -> bool:
|
|
49
|
+
"""True if two commands do the same thing. Default: identical strings."""
|
|
50
|
+
return a == b
|
|
51
|
+
|
|
52
|
+
def preview(self, cmd: str) -> Optional[str]:
|
|
53
|
+
"""A read-only command listing what a destructive cmd would touch."""
|
|
54
|
+
return None
|
|
55
|
+
|
|
56
|
+
def refuse(self, cmd: str) -> Optional[str]:
|
|
57
|
+
"""Reason to refuse running cmd at all, or None."""
|
|
58
|
+
return None
|
|
59
|
+
|
|
60
|
+
def is_destructive(self, cmd: str) -> bool:
|
|
61
|
+
return bool(self.destructive_pattern and self.destructive_pattern.search(cmd))
|
aiman/tools/__init__.py
ADDED
|
File without changes
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""aiman plugin for GNU find."""
|
|
2
|
+
import re
|
|
3
|
+
|
|
4
|
+
from aiman.core.tool import Tool
|
|
5
|
+
|
|
6
|
+
from . import fixture, rules, slots, templates
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class FindTool(Tool):
|
|
10
|
+
name = "find"
|
|
11
|
+
destructive_pattern = re.compile(
|
|
12
|
+
r"(-delete\b|-exec(dir)? (rm|mv|chmod|chown|gzip)\b|xargs -0 (/bin/)?rm\b|-ok rm\b)")
|
|
13
|
+
_FILTERS = re.compile(r" -(name|iname|size|mtime|mmin|atime|amin|ctime|cmin|empty|perm|user|"
|
|
14
|
+
r"group|newer|path|regex)\b")
|
|
15
|
+
|
|
16
|
+
def generate(self, seed=42):
|
|
17
|
+
return templates.generate(seed)
|
|
18
|
+
|
|
19
|
+
def validate(self, cmd):
|
|
20
|
+
return fixture.validate(cmd)
|
|
21
|
+
|
|
22
|
+
def parse(self, cmd):
|
|
23
|
+
return slots.parse(cmd)
|
|
24
|
+
|
|
25
|
+
def build(self, s):
|
|
26
|
+
return slots.build(s)
|
|
27
|
+
|
|
28
|
+
def tag(self, intent, s):
|
|
29
|
+
return slots.tag(intent, s)
|
|
30
|
+
|
|
31
|
+
def targets(self, s, intent):
|
|
32
|
+
return slots.targets(s, intent)
|
|
33
|
+
|
|
34
|
+
def assemble(self, intent, spans, classes):
|
|
35
|
+
return rules.assemble(intent, spans, classes)
|
|
36
|
+
|
|
37
|
+
def equivalent(self, a, b):
|
|
38
|
+
"""Same slots, or same tokens in another order with the same output on the fixture."""
|
|
39
|
+
if a == b:
|
|
40
|
+
return True
|
|
41
|
+
pa, pb = slots.parse(a), slots.parse(b)
|
|
42
|
+
if pa is not None and pa == pb:
|
|
43
|
+
return True
|
|
44
|
+
bag = lambda c: sorted(c.replace("'", "").split()) # noqa: E731
|
|
45
|
+
return bag(a) == bag(b) and fixture.run(a) == fixture.run(b)
|
|
46
|
+
|
|
47
|
+
def preview(self, cmd):
|
|
48
|
+
base = cmd.split(" | ")[0]
|
|
49
|
+
base = re.sub(r" -delete\b", " -print", base)
|
|
50
|
+
base = re.sub(r" -(exec|execdir|ok) .*$", " -print", base)
|
|
51
|
+
return re.sub(r" -print0$", " -print", base)
|
|
52
|
+
|
|
53
|
+
def refuse(self, cmd):
|
|
54
|
+
parts = cmd.split()
|
|
55
|
+
start = parts[2] if parts[1] == "-L" else parts[1]
|
|
56
|
+
if start == "/":
|
|
57
|
+
return "destructive command starting at '/'"
|
|
58
|
+
if not self._FILTERS.search(cmd):
|
|
59
|
+
return "destructive command with no filters"
|
|
60
|
+
return None
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
TOOL = FindTool()
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""Sandbox for find commands: a throwaway directory tree + a rewriter that points
|
|
2
|
+
commands at it and neutralises anything destructive.
|
|
3
|
+
|
|
4
|
+
validate(cmd) -> (ok, err) syntax check (find parse errors in stderr)
|
|
5
|
+
run(cmd) -> sorted output lines, used to decide if two commands are equivalent
|
|
6
|
+
"""
|
|
7
|
+
import os
|
|
8
|
+
import re
|
|
9
|
+
import subprocess
|
|
10
|
+
import tempfile
|
|
11
|
+
|
|
12
|
+
_FX = None
|
|
13
|
+
_ERR = re.compile(r"find: (unknown predicate|invalid|paths must precede|missing argument|"
|
|
14
|
+
r"expected an expression|unexpected extra|arguments to option|you have too many)", re.I)
|
|
15
|
+
_REFS = ["main.c", "build.stamp", "last_backup", "config.yaml", "data.bin", "report.pdf"]
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def fixture():
|
|
19
|
+
global _FX
|
|
20
|
+
if _FX is None:
|
|
21
|
+
fx = tempfile.mkdtemp(prefix="aiman_find_fx_")
|
|
22
|
+
for d in ["node_modules/x", ".git/o", "venv", "build", "tests", "logs", "a/b/c", "emptydir", "src"]:
|
|
23
|
+
os.makedirs(os.path.join(fx, d), exist_ok=True)
|
|
24
|
+
files = [("a.py", 10), ("big.log", 200000), ("node_modules/x/m.js", 5), ("a/b/c/d.txt", 3),
|
|
25
|
+
("tests/t.py", 7), ("README.md", 40), ("empty.txt", 0), ("img.jpg", 12000),
|
|
26
|
+
("logs/x.log", 4), ("main.c", 2), ("build.stamp", 1), ("last_backup", 1),
|
|
27
|
+
("config.yaml", 9), ("data.bin", 3), ("report.pdf", 6)]
|
|
28
|
+
for f, n in files:
|
|
29
|
+
with open(os.path.join(fx, f), "w") as h:
|
|
30
|
+
h.write("x" * n)
|
|
31
|
+
_FX = fx
|
|
32
|
+
return _FX
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def sandbox(cmd):
|
|
36
|
+
fx = fixture()
|
|
37
|
+
c = re.sub(r"^find (-L )?(\S+(?: /usr/sbin)?)", lambda m: f"find {m.group(1) or ''}{fx}", cmd)
|
|
38
|
+
c = c.replace("/etc/passwd", f"{fx}/main.c").replace("/etc/hosts", f"{fx}/main.c")
|
|
39
|
+
for ref in _REFS:
|
|
40
|
+
c = re.sub(rf"(-newer|-samefile) {ref}\b", rf"\1 {fx}/{ref}", c)
|
|
41
|
+
c = c.replace(" -delete", " -print")
|
|
42
|
+
c = re.sub(r"-fprintf \S+ ('[^']*')", r"-printf \1", c)
|
|
43
|
+
c = re.sub(r"-fprint \S+", "-print", c)
|
|
44
|
+
for tool in ["rm", "/bin/rm", "mv", "cp", "chmod", "chown", "gzip"]:
|
|
45
|
+
c = re.sub(rf"(-exec|-ok|xargs -0|-execdir) {re.escape(tool)}\b", rf"\1 echo {tool}", c)
|
|
46
|
+
c = c.replace("-ok echo", "-exec echo")
|
|
47
|
+
c = c.replace("tar --null -czf archive.tar.gz -T -", "cat")
|
|
48
|
+
return c
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _exec(cmd):
|
|
52
|
+
return subprocess.run(["bash", "-c", sandbox(cmd)], capture_output=True, text=True,
|
|
53
|
+
timeout=10, cwd=fixture())
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def validate(cmd):
|
|
57
|
+
r = _exec(cmd)
|
|
58
|
+
m = _ERR.search(r.stderr)
|
|
59
|
+
return (False, r.stderr.strip().splitlines()[0]) if m else (True, "")
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def run(cmd):
|
|
63
|
+
return sorted(_exec(cmd).stdout.splitlines())
|