boyan 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.
- boyan/__init__.py +3 -0
- boyan/cli.py +222 -0
- boyan/corpus.py +147 -0
- boyan/detail.py +231 -0
- boyan/gaps.py +191 -0
- boyan/index.py +180 -0
- boyan/masks.py +157 -0
- boyan/neighbours.py +63 -0
- boyan/netguard.py +566 -0
- boyan/progress.py +94 -0
- boyan/search.py +303 -0
- boyan/server.py +232 -0
- boyan/text.py +50 -0
- boyan/transfer.py +290 -0
- boyan/vocab.py +169 -0
- boyan/webui/app.js +224 -0
- boyan/webui/bubbles.js +346 -0
- boyan/webui/i18n.js +35 -0
- boyan/webui/index.html +99 -0
- boyan/webui/lang/de.js +82 -0
- boyan/webui/lang/en.js +82 -0
- boyan/webui/lang/es.js +82 -0
- boyan/webui/lang/fr.js +82 -0
- boyan/webui/lang/pt.js +82 -0
- boyan/webui/lang/uk.js +82 -0
- boyan/webui/style.css +145 -0
- boyan/webui/themes/beach.css +19 -0
- boyan/webui/themes/dark.css +19 -0
- boyan/webui/themes/light.css +19 -0
- boyan/webui/themes/mono-dark.css +19 -0
- boyan/webui/themes/mono-light.css +19 -0
- boyan/webui/themes/ocean.css +19 -0
- boyan/webui/themes/soft.css +19 -0
- boyan/webui/themes/summer.css +19 -0
- boyan-0.1.0.dist-info/METADATA +247 -0
- boyan-0.1.0.dist-info/RECORD +40 -0
- boyan-0.1.0.dist-info/WHEEL +5 -0
- boyan-0.1.0.dist-info/entry_points.txt +2 -0
- boyan-0.1.0.dist-info/licenses/LICENSE +21 -0
- boyan-0.1.0.dist-info/top_level.txt +1 -0
boyan/__init__.py
ADDED
boyan/cli.py
ADDED
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
"""boyan index | search | expand | terms | detail | gaps | names | list | ui"""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import sys
|
|
8
|
+
import time
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
STEPS = {"search": 4, "terms": 5, "detail": 4, "expand": 3} # with a D-masks model; fewer without one
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _log(*a):
|
|
15
|
+
print(time.strftime("%H:%M:%S"), *a, flush=True)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _end():
|
|
19
|
+
from . import progress
|
|
20
|
+
progress.done() # the steps end before the answer is printed
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _index(a):
|
|
24
|
+
from . import progress
|
|
25
|
+
from .index import find
|
|
26
|
+
progress.start(STEPS.get(a.cmd), flag=getattr(a, "progress", None))
|
|
27
|
+
progress.step("loading the index")
|
|
28
|
+
d = find(a.root, a.project)
|
|
29
|
+
if d is None:
|
|
30
|
+
sys.exit("boyan: no index here (.boyan/<project>) - build one: boyan index <repo> --db <mokosh db>")
|
|
31
|
+
from .search import open_index
|
|
32
|
+
return open_index(d)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def cmd_index(a):
|
|
36
|
+
from .index import build
|
|
37
|
+
store, project = a.simargl, None
|
|
38
|
+
if store and os.path.isfile(os.path.join(store, "meta.json")): # <store>/<index> given
|
|
39
|
+
store, project = os.path.dirname(os.path.abspath(store)), os.path.basename(os.path.abspath(store))
|
|
40
|
+
try:
|
|
41
|
+
build(a.repo, a.db, a.project, a.map, store, project, a.no_masks, log=_log)
|
|
42
|
+
except (ValueError, RuntimeError) as e:
|
|
43
|
+
sys.exit(f"boyan: {e}")
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def cmd_search(a):
|
|
47
|
+
ix = _index(a)
|
|
48
|
+
r = ix.search(a.query, k=max(a.top, 1), with_words=not a.no_words, words_mode=a.words_mode,
|
|
49
|
+
top_words=a.n_words)
|
|
50
|
+
_end()
|
|
51
|
+
if a.format == "json":
|
|
52
|
+
print(json.dumps(r, ensure_ascii=False, indent=1))
|
|
53
|
+
return
|
|
54
|
+
if a.format == "paths":
|
|
55
|
+
print("\n".join(x["file"] for x in r["files"][:a.top]))
|
|
56
|
+
return
|
|
57
|
+
print("names: " + (", ".join(f"{n['name']} ({n['files']} files)" for n in r["names"]) or "none"))
|
|
58
|
+
if r.get("groups"):
|
|
59
|
+
print("groups: " + ", ".join(f"{g['name']} ({g['files']} files, {g['names']} names)" for g in r["groups"]))
|
|
60
|
+
if r["words"]:
|
|
61
|
+
print("words: " + ", ".join(r["words"]))
|
|
62
|
+
elif not r["masks"]:
|
|
63
|
+
print("words: - (no D-masks model in this index)")
|
|
64
|
+
for i, x in enumerate(r["files"][:a.top], 1):
|
|
65
|
+
print(f"{i:3}. {x['file']} [{x['why']}]")
|
|
66
|
+
print(f"(neighbours: {r['neighbours']})")
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def cmd_expand(a):
|
|
70
|
+
ix = _index(a)
|
|
71
|
+
if not ix.meta.get("masks") and a.words_mode == "masks":
|
|
72
|
+
sys.exit("boyan: this index has no D-masks model (gensim missing when it was built)")
|
|
73
|
+
w = ix.expand(a.query, a.n_words or a.top, a.words_mode)
|
|
74
|
+
_end()
|
|
75
|
+
print(" ".join(w))
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def cmd_terms(a):
|
|
79
|
+
from .detail import terms
|
|
80
|
+
r = terms(_index(a), a.query, a.names, a.words)
|
|
81
|
+
_end()
|
|
82
|
+
if a.format == "json":
|
|
83
|
+
print(json.dumps(r, ensure_ascii=False, indent=1))
|
|
84
|
+
return
|
|
85
|
+
print("TERMS: " + (" ".join(r["terms"]) or "none"))
|
|
86
|
+
if r["groups"]:
|
|
87
|
+
print("GROUPS: " + " ".join(r["groups"]))
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def cmd_gaps(a):
|
|
91
|
+
"""Only the GAP rules again (gaps.json); the rest of the index as it is."""
|
|
92
|
+
from . import corpus, gaps
|
|
93
|
+
ix = _index(a)
|
|
94
|
+
root, db = ix.meta.get("root") or "", ix.meta.get("db") or ""
|
|
95
|
+
try:
|
|
96
|
+
now = corpus.renames(root) if os.path.exists(os.path.join(root, ".git")) else (lambda p: p)
|
|
97
|
+
g = gaps.learn(db, now, root)
|
|
98
|
+
gaps.save(str(ix.dir / "gaps.json"), g)
|
|
99
|
+
info = gaps.summary(g)
|
|
100
|
+
except Exception as e:
|
|
101
|
+
info = {"error": str(e)[:300]}
|
|
102
|
+
meta = dict(ix.meta, gaps=info)
|
|
103
|
+
(ix.dir / "meta.json").write_text(json.dumps(meta, indent=2, ensure_ascii=False), encoding="utf-8")
|
|
104
|
+
if "error" in info:
|
|
105
|
+
sys.exit(f"boyan: gaps not computed: {info['error']}")
|
|
106
|
+
print(f"gaps: {info['rules']} rules from {info['tasks']} tasks ({info['source']}) -> {ix.dir / 'gaps.json'}")
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def cmd_detail(a):
|
|
110
|
+
from .detail import as_text, detail
|
|
111
|
+
ix = _index(a)
|
|
112
|
+
d = detail(ix, [t for x in a.terms for t in x.replace(",", " ").split()], leaf=a.leaf, query=a.query)
|
|
113
|
+
_end()
|
|
114
|
+
if d["leaf"] and d["files"] and not ix.gap_rules: # on stderr: not into a model's prompt
|
|
115
|
+
why = (ix.meta.get("gaps") or {}).get("error") or "no gaps.json in this index"
|
|
116
|
+
print(f"boyan: WARNING no GAP lines - {why}; `boyan gaps` computes them", file=sys.stderr)
|
|
117
|
+
if a.format == "json":
|
|
118
|
+
print(json.dumps(d, ensure_ascii=False, indent=1))
|
|
119
|
+
return
|
|
120
|
+
print(as_text(d))
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def cmd_names(a):
|
|
124
|
+
ix = _index(a)
|
|
125
|
+
if a.tree:
|
|
126
|
+
def show(n, d):
|
|
127
|
+
if n.get("kind") == "group":
|
|
128
|
+
print(" " * d + f"[{n['name']}] (group: {n['names']} names, {n['files']} files)")
|
|
129
|
+
else:
|
|
130
|
+
print(" " * d + f"{n['name']} ({n['files']} files, explains {n['explains']})")
|
|
131
|
+
for c in n["children"]:
|
|
132
|
+
show(c, d + 1)
|
|
133
|
+
for n in ix.tree():
|
|
134
|
+
show(n, 0)
|
|
135
|
+
return
|
|
136
|
+
for n in ix.vocabulary["names"][: a.top or None]:
|
|
137
|
+
print(f"{n['rank']:4}. {n['name']:30} {len(n['files']):5} files explains {n['explains']:4}"
|
|
138
|
+
+ (f" < {n['parent']}" if n.get("parent") else ""))
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def cmd_list(a):
|
|
142
|
+
from .index import projects
|
|
143
|
+
for p in projects():
|
|
144
|
+
m = p["meta"]
|
|
145
|
+
print(f"{p['project']:20} {m.get('names', 0):4} names {m.get('files', 0):6} files "
|
|
146
|
+
f"masks {'yes' if m.get('masks') else 'no '} {m.get('built', '')} {p['dir']}")
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def main(argv=None):
|
|
150
|
+
ap = argparse.ArgumentParser(prog="boyan", description="the project's own vocabulary, from its files and tasks")
|
|
151
|
+
ap.add_argument("--progress", dest="progress", action="store_const", const=True, default=None,
|
|
152
|
+
help="the steps and their seconds on stderr (default: only at a terminal; BOYAN_PROGRESS=1)")
|
|
153
|
+
ap.add_argument("--quiet", dest="progress", action="store_const", const=False, help="no steps")
|
|
154
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
155
|
+
pi = sub.add_parser("index", help="build the vocabulary and the D-masks model of a repository")
|
|
156
|
+
pi.add_argument("repo", help="the git repository (today's code)")
|
|
157
|
+
pi.add_argument("--db", required=True, help="its mokosh task database (mokosh ingest; mokosh clean)")
|
|
158
|
+
pi.add_argument("--project", help="the index name (default: the folder's name)")
|
|
159
|
+
pi.add_argument("--map", help="its svitovyd map (default: <repo>/.svitovyd/<name>/map.txt)")
|
|
160
|
+
pi.add_argument("--simargl", help="simargl's store of past tasks for the neighbours: <store dir>[/<index>] "
|
|
161
|
+
"(as measured); default: boyan's own word index")
|
|
162
|
+
pi.add_argument("--no-masks", action="store_true", help="the vocabulary only, no word2vec")
|
|
163
|
+
for name, hlp in (("search", "a query -> the names it asks about, their files, the D-masks words"),
|
|
164
|
+
("expand", "a query -> its D-masks words only")):
|
|
165
|
+
p = sub.add_parser(name, help=hlp)
|
|
166
|
+
p.add_argument("query")
|
|
167
|
+
p.add_argument("--root", default=".")
|
|
168
|
+
p.add_argument("--project")
|
|
169
|
+
p.add_argument("--top", type=int, default=10)
|
|
170
|
+
p.add_argument("--words-mode", choices=("masks", "vote"), default="masks",
|
|
171
|
+
help="masks: the D-masks guesses (default); vote: the D-masks guesses and RM3's rare words of "
|
|
172
|
+
"the nearest past tasks voted together, 20 words (what magura asks for; simrgl exp17.16)")
|
|
173
|
+
p.add_argument("--n-words", type=int, default=None, help="how many words (search: 10 masks, 20 vote; expand: --top)")
|
|
174
|
+
if name == "search":
|
|
175
|
+
p.add_argument("--format", choices=("text", "json", "paths"), default="text")
|
|
176
|
+
p.add_argument("--no-words", action="store_true", help="skip the D-masks words")
|
|
177
|
+
pt = sub.add_parser("terms", help="a query -> the project's words for it (names + D-masks words), to choose from")
|
|
178
|
+
pt.add_argument("query")
|
|
179
|
+
pt.add_argument("--root", default=".")
|
|
180
|
+
pt.add_argument("--project")
|
|
181
|
+
pt.add_argument("--names", type=int, default=5)
|
|
182
|
+
pt.add_argument("--words", type=int, default=10)
|
|
183
|
+
pt.add_argument("--format", choices=("text", "json"), default="text")
|
|
184
|
+
pd = sub.add_parser("detail", help="chosen terms -> narrower terms, or (few files) the files and their words")
|
|
185
|
+
pd.add_argument("terms", nargs="+", help="names, groups or words of the project (several: their common files)")
|
|
186
|
+
pd.add_argument("--root", default=".")
|
|
187
|
+
pd.add_argument("--project")
|
|
188
|
+
pd.add_argument("--leaf", type=int, default=12, help="this many files or fewer: the files, not narrower terms")
|
|
189
|
+
pd.add_argument("--query", help="the task: a GAP line's name comes from it (else from the terms)")
|
|
190
|
+
pd.add_argument("--format", choices=("text", "json"), default="text")
|
|
191
|
+
pg = sub.add_parser("gaps", help="(re)learn where new files go (gaps.json) for an index built before GAP")
|
|
192
|
+
pg.add_argument("--root", default=".")
|
|
193
|
+
pg.add_argument("--project")
|
|
194
|
+
pn = sub.add_parser("names", help="the vocabulary: its names in the order chosen, or nested (--tree)")
|
|
195
|
+
pn.add_argument("--root", default=".")
|
|
196
|
+
pn.add_argument("--project")
|
|
197
|
+
pn.add_argument("--tree", action="store_true")
|
|
198
|
+
pn.add_argument("--top", type=int, default=0)
|
|
199
|
+
sub.add_parser("list", help="the registered indexes")
|
|
200
|
+
pu = sub.add_parser("ui", help="the web UI (Flask)")
|
|
201
|
+
pu.add_argument("--port", type=int, default=8094)
|
|
202
|
+
pu.add_argument("--root", default=".")
|
|
203
|
+
pu.add_argument("--bind", dest="bind", default=None, metavar="ADDR",
|
|
204
|
+
help="where to listen: 127.0.0.1 = this computer only (default), 0.0.0.0 = the network; else \"bind\" in ~/.boyan/config.json")
|
|
205
|
+
a = ap.parse_args(argv)
|
|
206
|
+
for s in (sys.stdout, sys.stderr): # a Windows console (cp1251) must not stop the output; a pipe
|
|
207
|
+
try: # (an agent, 1bcoder's /flow boyan) gets UTF-8, not the code page
|
|
208
|
+
s.reconfigure(errors="replace") if s.isatty() else s.reconfigure(encoding="utf-8", errors="replace")
|
|
209
|
+
except (AttributeError, ValueError):
|
|
210
|
+
pass
|
|
211
|
+
if a.cmd == "ui":
|
|
212
|
+
from .server import serve
|
|
213
|
+
serve(a.root, a.bind, a.port)
|
|
214
|
+
return
|
|
215
|
+
{"index": cmd_index, "search": cmd_search, "expand": cmd_expand, "terms": cmd_terms, "detail": cmd_detail, "gaps": cmd_gaps,
|
|
216
|
+
"names": cmd_names, "list": cmd_list}[a.cmd](a)
|
|
217
|
+
from . import progress
|
|
218
|
+
progress.done()
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
if __name__ == "__main__":
|
|
222
|
+
main()
|
boyan/corpus.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
"""What boyan learns from: the files of a repository, the tasks of a mokosh database, a svitovyd map.
|
|
2
|
+
|
|
3
|
+
code_files(repo) {path: words} of every tracked, non-binary file (git ls-files; no extension
|
|
4
|
+
list, no size limit — simrgl exp17's rerun: a 300 KB limit had dropped a
|
|
5
|
+
dialect's whole code)
|
|
6
|
+
renames(repo) old path -> today's path, through every rename git recorded
|
|
7
|
+
read_tasks(db, now) {task: Task(title, text, files)} — files as today's paths; the text is
|
|
8
|
+
TITLE + DESCRIPTION_CLEAN (mokosh clean) or DESCRIPTION when not cleaned
|
|
9
|
+
read_map(path) (defines {file: {name, parts}}, vocabulary {the code's names})
|
|
10
|
+
"""
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import os
|
|
14
|
+
import re
|
|
15
|
+
import sqlite3
|
|
16
|
+
import subprocess
|
|
17
|
+
from collections import defaultdict
|
|
18
|
+
from dataclasses import dataclass, field
|
|
19
|
+
|
|
20
|
+
from .text import parts, words
|
|
21
|
+
|
|
22
|
+
MAX_WORDS_PER_FILE = 200_000 # a generated megabyte file would only repeat itself
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass
|
|
26
|
+
class Task:
|
|
27
|
+
title: str
|
|
28
|
+
text: str
|
|
29
|
+
files: set = field(default_factory=set)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _git(repo, *args):
|
|
33
|
+
r = subprocess.run(["git", *args], cwd=repo, capture_output=True, text=True, encoding="utf-8", errors="replace")
|
|
34
|
+
if r.returncode:
|
|
35
|
+
raise RuntimeError(f"git {' '.join(args[:2])} failed in {repo}: {r.stderr.strip()[:300]}")
|
|
36
|
+
return r.stdout
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def hidden(path):
|
|
40
|
+
"""A path with a part starting with a dot (.github/workflows/x.yml, .pre-commit-config.yaml):
|
|
41
|
+
left out by every tool of the pantheon — a dot means "not the project's content"."""
|
|
42
|
+
return any(p.startswith(".") and p not in (".", "..") for p in str(path).replace("\\", "/").split("/"))
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def tracked(repo):
|
|
46
|
+
return [f for f in _git(repo, "ls-files").splitlines() if f and not hidden(f)]
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def code_files(repo, log=None):
|
|
50
|
+
files = {}
|
|
51
|
+
for f in tracked(repo):
|
|
52
|
+
p = os.path.join(repo, f)
|
|
53
|
+
if not os.path.isfile(p):
|
|
54
|
+
continue
|
|
55
|
+
try:
|
|
56
|
+
with open(p, "rb") as fh:
|
|
57
|
+
data = fh.read()
|
|
58
|
+
except OSError:
|
|
59
|
+
continue
|
|
60
|
+
if b"\x00" in data[:8192]:
|
|
61
|
+
continue
|
|
62
|
+
text = data.decode("utf-8", "replace")
|
|
63
|
+
files[f] = words(" ".join(re.split(r"[/._-]", f)) + "\n" + text)[:MAX_WORDS_PER_FILE]
|
|
64
|
+
if log:
|
|
65
|
+
log(f"code: {len(files)} text files")
|
|
66
|
+
return files
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def renames(repo):
|
|
70
|
+
try:
|
|
71
|
+
out = _git(repo, "log", "-M", "--diff-filter=R", "--name-status", "--format=", "--reverse", "HEAD")
|
|
72
|
+
except RuntimeError:
|
|
73
|
+
out = ""
|
|
74
|
+
nxt = {}
|
|
75
|
+
for ln in out.splitlines():
|
|
76
|
+
p = ln.split("\t")
|
|
77
|
+
if len(p) == 3 and p[0].startswith("R"):
|
|
78
|
+
nxt[p[1]] = p[2]
|
|
79
|
+
|
|
80
|
+
def now(path):
|
|
81
|
+
seen = set()
|
|
82
|
+
while path in nxt and path not in seen:
|
|
83
|
+
seen.add(path)
|
|
84
|
+
path = nxt[path]
|
|
85
|
+
return path
|
|
86
|
+
return now
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def read_tasks(db_path, now=lambda p: p):
|
|
90
|
+
from mokosh.schema import tables
|
|
91
|
+
db = sqlite3.connect(db_path)
|
|
92
|
+
try:
|
|
93
|
+
task_t, commit_t = tables(db)
|
|
94
|
+
cols = {r[1].upper() for r in db.execute(f"PRAGMA table_info({task_t})")}
|
|
95
|
+
desc = "DESCRIPTION_CLEAN" if "DESCRIPTION_CLEAN" in cols else "DESCRIPTION"
|
|
96
|
+
tasks = {str(n): Task(t or "", f"{t or ''}\n{d or ''}") for n, t, d in
|
|
97
|
+
db.execute(f"SELECT NAME, TITLE, {desc} FROM {task_t}")}
|
|
98
|
+
for name, path in db.execute(f"SELECT DISTINCT TASK_NAME, PATH FROM {commit_t} "
|
|
99
|
+
"WHERE TASK_NAME IS NOT NULL AND TASK_NAME != ''"):
|
|
100
|
+
t = tasks.get(str(name))
|
|
101
|
+
if t is not None and path and not hidden(path):
|
|
102
|
+
t.files.add(now(str(path).replace("\\", "/")))
|
|
103
|
+
cleaned = desc == "DESCRIPTION_CLEAN"
|
|
104
|
+
finally:
|
|
105
|
+
db.close()
|
|
106
|
+
return tasks, cleaned
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def read_map(path):
|
|
110
|
+
"""A svitovyd map -> ({file: {defined names and their parts}}, {every defined name, part, file stem})."""
|
|
111
|
+
defines, vocab = defaultdict(set), set()
|
|
112
|
+
if not path or not os.path.isfile(path):
|
|
113
|
+
return defines, vocab
|
|
114
|
+
cur = None
|
|
115
|
+
with open(path, encoding="utf-8", errors="replace") as fh:
|
|
116
|
+
for ln in fh:
|
|
117
|
+
if ln and not ln[0].isspace() and ln.strip() and not ln.startswith("#"):
|
|
118
|
+
cur = ln.strip().replace("\\", "/")
|
|
119
|
+
vocab.add(os.path.splitext(os.path.basename(cur))[0].lower())
|
|
120
|
+
elif cur and ln.strip().startswith("defines"):
|
|
121
|
+
for n in re.findall(r"([A-Za-z_][A-Za-z0-9_.]*)\(ln:", ln):
|
|
122
|
+
vocab.add(n.lower())
|
|
123
|
+
vocab.update(parts(n))
|
|
124
|
+
for n in re.findall(r"([A-Za-z_][A-Za-z0-9_]*)\(ln:", ln): # a dotted name: its last part
|
|
125
|
+
defines[cur].add(n.lower())
|
|
126
|
+
defines[cur].update(parts(n))
|
|
127
|
+
return defines, vocab
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def find_map(root="."):
|
|
131
|
+
"""The svitovyd map of a folder: <root>/.svitovyd/<name>/map.txt — the one named like the folder, else
|
|
132
|
+
the first by name; a map written before the .<tool>/<name>/ rule (.svitovyd/map.txt) still read.
|
|
133
|
+
(A copy of svitovyd.layout.find_map: this tool does not import svitovyd for it.) None when there is none."""
|
|
134
|
+
import os as _os
|
|
135
|
+
import re as _re
|
|
136
|
+
d = _os.path.join(_os.path.abspath(root), ".svitovyd")
|
|
137
|
+
if not _os.path.isdir(d):
|
|
138
|
+
return None
|
|
139
|
+
found = [_os.path.join(d, n, "map.txt") for n in sorted(_os.listdir(d)) if _os.path.isfile(_os.path.join(d, n, "map.txt"))]
|
|
140
|
+
own = _re.sub(r"[^A-Za-z0-9._-]", "_", _os.path.basename(_os.path.abspath(root))).strip("._-")
|
|
141
|
+
for p in found:
|
|
142
|
+
if _os.path.basename(_os.path.dirname(p)) == own:
|
|
143
|
+
return p
|
|
144
|
+
if found:
|
|
145
|
+
return found[0]
|
|
146
|
+
old = _os.path.join(d, "map.txt")
|
|
147
|
+
return old if _os.path.isfile(old) else None
|
boyan/detail.py
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
"""Terms and details — boyan for a model that narrows a task down step by step (1bcoder's /flow boyan).
|
|
2
|
+
|
|
3
|
+
terms(query) the project's words for a query: the vocabulary's names it asks about (as search),
|
|
4
|
+
the query's own words the project knows (folder names, names and groups first —
|
|
5
|
+
duckdb, postgres —, then the rest in the query's order, >= 2 files each) and the D-masks words —
|
|
6
|
+
a short list to choose from
|
|
7
|
+
detail(terms) what the chosen terms mean in this project: the files they lead to (a name -> its
|
|
8
|
+
files, a group -> its files, any other word -> the files whose path holds it or that
|
|
9
|
+
define a name holding it — the svitovyd map), narrowed to the files every term leads
|
|
10
|
+
to (else the files most of them do); then
|
|
11
|
+
many files the narrower terms inside them — words and names that pick out a part
|
|
12
|
+
of those files and little else (to choose from again)
|
|
13
|
+
few files the files themselves and their own words: the names defined in
|
|
14
|
+
them that few other files define (max_alias_length), and GAP —
|
|
15
|
+
the folder a new file of such a task goes to, with a name from
|
|
16
|
+
the query (gaps.py, exp17.15)
|
|
17
|
+
|
|
18
|
+
No model here: the choosing is the caller's (an LLM, a person). "You give it a word, it gives you ten."
|
|
19
|
+
"""
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import math
|
|
23
|
+
import os
|
|
24
|
+
from collections import Counter, defaultdict
|
|
25
|
+
|
|
26
|
+
from . import corpus, gaps, progress
|
|
27
|
+
from .text import STOP, parts, path_words
|
|
28
|
+
from .text import words as qwords
|
|
29
|
+
|
|
30
|
+
LEAF = 12 # this many files or fewer: the files and their words, not narrower terms
|
|
31
|
+
TOP_TERMS = 12
|
|
32
|
+
TOP_WORDS = 15
|
|
33
|
+
TOP_FILES = 10
|
|
34
|
+
QUERY_WORDS = 10 # the query's own words that are words of the project, in terms()
|
|
35
|
+
MIN_FILES = 2 # ... leading to at least this many files (one file: a test's name, an accident)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class Words:
|
|
39
|
+
"""word -> the files it leads to, from the index's svitovyd map and the files' paths (built once)."""
|
|
40
|
+
|
|
41
|
+
def __init__(self, ix):
|
|
42
|
+
self.ix = ix
|
|
43
|
+
m = ix.meta.get("map")
|
|
44
|
+
root = ix.meta.get("root") or ""
|
|
45
|
+
path = m if (m and os.path.isabs(m)) else (os.path.join(root, m) if m else None)
|
|
46
|
+
defines, _ = corpus.read_map(path) if path else ({}, set())
|
|
47
|
+
self.defines = defines
|
|
48
|
+
inv = defaultdict(set)
|
|
49
|
+
files = set(defines)
|
|
50
|
+
for fs in ix.files.values():
|
|
51
|
+
files |= fs
|
|
52
|
+
for f in files:
|
|
53
|
+
if corpus.hidden(f):
|
|
54
|
+
continue
|
|
55
|
+
for w in set(path_words(f)) | defines.get(f, set()):
|
|
56
|
+
if len(w) >= 3 and w not in STOP:
|
|
57
|
+
inv[w].add(f)
|
|
58
|
+
self.inv = inv
|
|
59
|
+
self.keys = sorted(inv)
|
|
60
|
+
longer = defaultdict(list) # stem -> the words 1-3 letters longer (kin, both >= 4)
|
|
61
|
+
for w in self.keys:
|
|
62
|
+
for k in (1, 2, 3):
|
|
63
|
+
if len(w) - k >= 4:
|
|
64
|
+
longer[w[:-k]].append(w)
|
|
65
|
+
self.longer = longer
|
|
66
|
+
self.folders = {p.lower() for f in files for p in f.split("/")[:-1]} # duckdb, postgres, aliasing
|
|
67
|
+
self.root = root
|
|
68
|
+
self.in_folder = defaultdict(list)
|
|
69
|
+
for f in files:
|
|
70
|
+
self.in_folder[f.rsplit("/", 1)[0] if "/" in f else ""].append(f)
|
|
71
|
+
self.n = max(len(files), 1)
|
|
72
|
+
touched = Counter(f for fs in ix.tasks.values() for f in fs)
|
|
73
|
+
self.touched = touched # how many past tasks changed a file: the order of ties
|
|
74
|
+
|
|
75
|
+
def folder_files(self, d):
|
|
76
|
+
"""The files of a folder now: on disk when the repository is there, else as the index saw them."""
|
|
77
|
+
p = os.path.join(self.root, d) if self.root else ""
|
|
78
|
+
if p and os.path.isdir(p):
|
|
79
|
+
return [f"{d}/{n}" if d else n for n in os.listdir(p) if not n.startswith(".") and os.path.isfile(os.path.join(p, n))]
|
|
80
|
+
return list(self.in_folder.get(d, ()))
|
|
81
|
+
|
|
82
|
+
def files_of(self, term):
|
|
83
|
+
t = term.strip().lower()
|
|
84
|
+
if t in self.ix.files:
|
|
85
|
+
return set(self.ix.files[t]), "name"
|
|
86
|
+
if t in self.ix.groups:
|
|
87
|
+
return set(self.ix.groups[t]["files"]), "group"
|
|
88
|
+
out = self._word(t)
|
|
89
|
+
if not out and ("_" in t or len(parts(t)) > 1): # table_alias, unknown as a whole: its parts together
|
|
90
|
+
sets = [self._word(p) for p in parts(t)]
|
|
91
|
+
sets = [x for x in sets if x]
|
|
92
|
+
if sets:
|
|
93
|
+
both = set.intersection(*sets)
|
|
94
|
+
out = both or set.union(*sets)
|
|
95
|
+
return out, "word"
|
|
96
|
+
|
|
97
|
+
def _word(self, t):
|
|
98
|
+
out = set(self.inv.get(t, ()))
|
|
99
|
+
for w in self.kin(t): # alias -> aliases, aliasing (AL06's folder)
|
|
100
|
+
out |= self.inv[w]
|
|
101
|
+
return out
|
|
102
|
+
|
|
103
|
+
def kin(self, t):
|
|
104
|
+
"""The words of the project of one stem with t: one is the other + at most 3 letters (>= 4 each).
|
|
105
|
+
Looked up, not scanned: t's 1-3 letters shorter prefixes, and the words registered under t as
|
|
106
|
+
their stem (a scan of every word with t's first 4 letters took 3.7 s for `detail rules` on sqlfluff)."""
|
|
107
|
+
if len(t) < 4:
|
|
108
|
+
return []
|
|
109
|
+
out = [w for w in self.longer.get(t, ()) if w != t]
|
|
110
|
+
out += [t[:-k] for k in (1, 2, 3) if len(t) - k >= 4 and t[:-k] in self.inv]
|
|
111
|
+
return sorted(out)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
_cache = {}
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def words_of(ix):
|
|
118
|
+
w = _cache.get(id(ix))
|
|
119
|
+
if w is None or w.ix is not ix:
|
|
120
|
+
progress.step("the project's words (svitovyd map + paths)")
|
|
121
|
+
w = _cache[id(ix)] = Words(ix)
|
|
122
|
+
return w
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def terms(ix, query, names=5, words=10):
|
|
126
|
+
"""-> {"names": [...], "words": [...], "terms": names + words (no repeats)}"""
|
|
127
|
+
top, _, _ = ix.translate(query, names)
|
|
128
|
+
ns = [n for n, _ in top]
|
|
129
|
+
ws = ix.expand(query, words) if ix.meta.get("masks") else []
|
|
130
|
+
W = words_of(ix) # the query's own words the project knows, rarest first
|
|
131
|
+
key = lambda w: w in W.folders or w in ix.files or w in ix.groups # duckdb, postgres, a name, a group
|
|
132
|
+
own = [w for w in dict.fromkeys(qwords(query)) if w not in STOP and len(w) >= 3
|
|
133
|
+
and (key(w) or len(W.files_of(w)[0]) >= MIN_FILES)] # a word of one file: an accident
|
|
134
|
+
own = sorted(own, key=lambda w: not key(w))[:QUERY_WORDS] # those first, then in the query's order
|
|
135
|
+
seen, out = set(), []
|
|
136
|
+
for t in ns + own + ws:
|
|
137
|
+
if t not in seen:
|
|
138
|
+
seen.add(t)
|
|
139
|
+
out.append(t)
|
|
140
|
+
return {"names": ns, "own": own, "words": ws, "terms": out,
|
|
141
|
+
"groups": sorted({ix.names[n].get("group") for n in ns if ix.names[n].get("group")})}
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def detail(ix, terms_, leaf=LEAF, top_terms=TOP_TERMS, top_words=TOP_WORDS, query=None):
|
|
145
|
+
"""-> {"terms": {term: (kind, files)}, "unknown": [...], "how": all|most, "files": [...ranked],
|
|
146
|
+
"leaf": bool, "narrower": [{term, kind, files, inside}], "words": [...], "gaps": [...]}
|
|
147
|
+
query: the task — the source of a GAP's name (else the terms themselves)"""
|
|
148
|
+
W = words_of(ix)
|
|
149
|
+
progress.step("the files the chosen words lead to")
|
|
150
|
+
sets, unknown, kinds = {}, [], {}
|
|
151
|
+
for t in terms_:
|
|
152
|
+
fs, kind = W.files_of(t)
|
|
153
|
+
if fs:
|
|
154
|
+
sets[t.lower()] = fs
|
|
155
|
+
kinds[t.lower()] = kind
|
|
156
|
+
else:
|
|
157
|
+
unknown.append(t)
|
|
158
|
+
if not sets:
|
|
159
|
+
return {"terms": {}, "unknown": unknown, "how": "none", "files": [], "leaf": True, "narrower": [], "words": [],
|
|
160
|
+
"gaps": []}
|
|
161
|
+
hits = Counter(f for fs in sets.values() for f in fs)
|
|
162
|
+
best = max(hits.values())
|
|
163
|
+
how = "all" if best == len(sets) else "most"
|
|
164
|
+
pool = [f for f, c in hits.items() if c == best]
|
|
165
|
+
pool.sort(key=lambda f: (-W.touched.get(f, 0), f))
|
|
166
|
+
out = {"terms": {t: (kinds[t], len(fs)) for t, fs in sets.items()}, "unknown": unknown, "how": how,
|
|
167
|
+
"files": pool, "leaf": len(pool) <= leaf}
|
|
168
|
+
P = set(pool)
|
|
169
|
+
if not out["leaf"]:
|
|
170
|
+
cand = Counter()
|
|
171
|
+
for f in pool:
|
|
172
|
+
for w in set(path_words(f)) | W.defines.get(f, set()):
|
|
173
|
+
cand[w] += 1
|
|
174
|
+
for n, fs in ix.files.items():
|
|
175
|
+
k = len(fs & P)
|
|
176
|
+
if k:
|
|
177
|
+
cand[n] = max(cand[n], k)
|
|
178
|
+
scored = []
|
|
179
|
+
for c, inside in cand.items():
|
|
180
|
+
if c in sets or c in STOP or len(c) < 3 or c.isdigit():
|
|
181
|
+
continue
|
|
182
|
+
fs, kind = W.files_of(c)
|
|
183
|
+
if not fs or inside < 2 or inside > 0.7 * len(P):
|
|
184
|
+
continue
|
|
185
|
+
prec = inside / len(fs)
|
|
186
|
+
s = prec * math.log(1 + inside) * (1.5 if kind != "word" else 1.0)
|
|
187
|
+
scored.append((s, c, kind, len(fs), inside))
|
|
188
|
+
scored.sort(key=lambda x: (-x[0], x[1]))
|
|
189
|
+
out["narrower"] = [{"term": c, "kind": k, "files": n, "inside": i} for _, c, k, n, i in scored[:top_terms]]
|
|
190
|
+
out["words"] = []
|
|
191
|
+
else:
|
|
192
|
+
out["narrower"] = []
|
|
193
|
+
cw = Counter()
|
|
194
|
+
for f in pool:
|
|
195
|
+
for w in W.defines.get(f, ()):
|
|
196
|
+
if w not in sets and w not in STOP and len(w) >= 4:
|
|
197
|
+
cw[w] += 1
|
|
198
|
+
stems = {k for t in sets for k in [t] + W.kin(t)}
|
|
199
|
+
near = lambda w: sum(1 for x in stems if x in w) # holds a chosen term (max_alias_length)
|
|
200
|
+
ranked = sorted(cw, key=lambda w: (-near(w), w.startswith("test"), # the code's own names before tests'
|
|
201
|
+
-(cw[w] / len(W.inv.get(w, ())) if W.inv.get(w) else 0),
|
|
202
|
+
-("_" in w), -cw[w], w))
|
|
203
|
+
out["words"] = ranked[:top_words]
|
|
204
|
+
if out["leaf"] and ix.gap_rules:
|
|
205
|
+
progress.step("GAP: where a new file would go")
|
|
206
|
+
out["gaps"] = (gaps.propose(ix.gap_rules, pool, query or " ".join(terms_), W.folder_files)
|
|
207
|
+
if out["leaf"] and ix.gap_rules else [])
|
|
208
|
+
return out
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def as_text(d, top_files=TOP_FILES):
|
|
212
|
+
"""The answer as a model reads it: TERMS (choose again) or FILES + WORDS (done)."""
|
|
213
|
+
lines = []
|
|
214
|
+
if d["unknown"]:
|
|
215
|
+
lines.append("UNKNOWN: " + " ".join(d["unknown"]) + " (not words of this project)")
|
|
216
|
+
if not d["files"]:
|
|
217
|
+
lines.append("FILES: none")
|
|
218
|
+
return "\n".join(lines)
|
|
219
|
+
if d["how"] == "most":
|
|
220
|
+
lines.append("NOTE: no file has all the terms; the files most of them lead to")
|
|
221
|
+
if d["leaf"]:
|
|
222
|
+
lines.append(f"FILES ({len(d['files'])}):")
|
|
223
|
+
lines += [f" {f}" for f in d["files"]]
|
|
224
|
+
if d["words"]:
|
|
225
|
+
lines.append("WORDS: " + " ".join(d["words"]))
|
|
226
|
+
lines += [gaps.as_line(g) for g in d.get("gaps", [])]
|
|
227
|
+
else:
|
|
228
|
+
lines.append("TERMS: " + " ".join(x["term"] for x in d["narrower"]))
|
|
229
|
+
lines.append(f"FILES ({len(d['files'])}, the first {min(top_files, len(d['files']))}): "
|
|
230
|
+
+ " ".join(d["files"][:top_files]))
|
|
231
|
+
return "\n".join(lines)
|