File size: 5,207 Bytes
6e2225f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
"""project_answer - a question asked in an open project, answered from the project's own text (revised 12.0, 2026-11-17).



With a folder open, "Where does the writer decide how many sentences to write?" or "How are sizes read?" is a question

about this project, not about the world: before this it reached the page discussion and was offered a Wikipedia lookup.

Here the question's content words (the store's lemmas, closed-class words and question words left out) are matched

against each function's and module's own words: its name split at underscores, its docstring and its comments. The

answer names file:line and quotes the code's own description; every sentence is a project record, cited by path and line.

A question none of the project's text answers well enough returns None and keeps its existing owner.



Would not solve: code with no names, docstrings or comments that share the asker's words (a reader of the code's

behaviour, not its words, would be needed); questions about runtime behaviour, which are runs, not readings.

"""
import ast
import re
from pathlib import Path

SKIP = {".git", "__pycache__", "node_modules", ".venv", "venv", "local", "state"}
QUESTION = {"where", "what", "which", "who", "when", "why", "how", "does", "do", "did", "is", "are", "was", "were", "can",
            "could", "should", "would", "will", "the", "this", "that", "these", "those", "code", "project", "file",
            "function", "part", "happen", "happens", "get", "gets", "done", "decide", "decides", "handle", "handles"}


def _lemmas(text, reader):
    out = set()
    for w in re.findall(r"[a-z]{3,}", text.lower().replace("_", " ")):
        if w in QUESTION:
            continue
        pos = reader.d.pos(w) if reader is not None else set()
        if pos & {"article", "det", "pron", "prep", "conj", "particle"}:
            continue
        out.add(reader.d.lemma(w, "noun" if "noun" in pos else "verb" if "verb" in pos else None) if reader is not None else w)
    return out


def _units(root, limit=600):
    """(path, line, name, args, own words, description) for each module and function of the project"""
    base = Path(root).resolve()
    seen = 0
    for path in sorted(base.rglob("*.py")):
        if any(part in SKIP or part.startswith(".") for part in path.relative_to(base).parts[:-1]):
            continue
        seen += 1
        if seen > limit:
            return
        try:
            source = path.read_text(encoding="utf-8")
            tree = ast.parse(source)
        except (SyntaxError, UnicodeError, OSError):
            continue
        lines = source.splitlines()
        rel = path.relative_to(base).as_posix()
        doc = ast.get_docstring(tree) or ""
        if doc:
            yield rel, 1, path.stem, [], path.stem + " " + doc, doc
        for node in ast.walk(tree):
            if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
                body = lines[node.lineno - 1: getattr(node, "end_lineno", node.lineno)][:60]
                comments = " ".join(c for line in body for c in re.findall(r"#\s*(.+)$", line))
                fdoc = ast.get_docstring(node) or ""
                args = [a.arg for a in getattr(getattr(node, "args", None), "args", [])][:6]
                yield rel, node.lineno, node.name, args, " ".join([node.name, fdoc, comments]), fdoc or comments


def answer(text, root, reader, k=3):
    # a question that names one of the project's files is that file's explainer's (code_discussion), not a search
    for named in re.findall(r"[\w./-]+\.\w+", text):
        if (Path(root) / named).is_file():
            return None
    asked = _lemmas(text, reader) - QUESTION
    if len(asked) < 2:
        return None
    scored = []
    for rel, line, name, args, words, description in _units(root):
        own = _lemmas(words, reader)
        hit = asked & own
        if len(hit) >= max(2, (len(asked) + 1) // 2):
            in_name = len(asked & _lemmas(name, reader))
            scored.append((len(hit) + in_name, rel, line, name, args, description, sorted(hit)))
    if not scored:
        return None
    scored.sort(key=lambda s: (-s[0], s[1], s[2]))
    rows, refs = [], []
    for i, (_score, rel, line, name, args, description, hit) in enumerate(scored[:k], 1):
        first = re.split(r"(?<=[.!?])\s+", " ".join(description.split()))[0][:300] if description else ""
        rows.append("%s%s at %s:%d%s [%d]" % (name, "(%s)" % ", ".join(args) if args or name != Path(rel).stem else "",
                                              rel, line, (": " + first) if first else "", i))
        refs.append("%d. %s:%d (this project's own text; words matched: %s)" % (i, rel, line, ", ".join(hit)))
    return {"status": "answered", "path": "bench:code:where",
            "response": "In this project:\n" + "\n".join("- " + r for r in rows) + "\n\n### Sources\n\n" + "\n".join(refs),
            "records": [r.split(" ")[1] for r in refs],
            "basis": {"kind": "project record", "asked": sorted(asked), "matches": len(scored)},
            "execution": {"state": "read", "check": {"ok": True}}}