64 lines
2.4 KiB
Python
64 lines
2.4 KiB
Python
#!/usr/bin/env python3
|
|
"""Bounded lexical retrieval from an explicit, committed Doctor knowledge corpus."""
|
|
import hashlib
|
|
from pathlib import Path
|
|
import re
|
|
import subprocess
|
|
|
|
PATHS = (
|
|
'homelab.yml', 'apps/gitea-runner/deployment.yaml',
|
|
'apps/opentelemetry-lab/collector.yaml', 'infra/monitoring-debian/README.md',
|
|
'scripts/monitoring-exporter-access.py', 'scripts/doctor-k3s-storage.py',
|
|
'scripts/doctor-k3s-storage-host.py', 'scripts/compose-intent.py',
|
|
'docs/doctor-overview.md', 'lib/jeannie/pipeline.sh',
|
|
)
|
|
|
|
|
|
def tokens(text):
|
|
return set(re.findall(r'[a-z0-9_]+', text.lower()))
|
|
|
|
|
|
def snapshot(repo):
|
|
repo = Path(repo)
|
|
def git(*args):
|
|
return subprocess.check_output(['git', '-C', str(repo), *args], text=True, timeout=15)
|
|
revision = git('rev-parse', 'HEAD').strip()
|
|
documents = {}
|
|
for path in PATHS:
|
|
text = git('show', revision + ':' + path)
|
|
if len(text.encode()) > 2 * 1024 ** 2:
|
|
raise ValueError('Allowlisted repository file exceeds indexing limit: ' + path)
|
|
documents[path] = text
|
|
return revision, documents
|
|
|
|
|
|
def retrieve(documents, query, paths, budget=6500, limit=4):
|
|
if not set(paths).issubset(PATHS):
|
|
raise ValueError('Retrieval path is outside the non-secret corpus allowlist')
|
|
terms = tokens(query)
|
|
candidates = []
|
|
for path in paths:
|
|
lines = documents[path].splitlines()
|
|
for start in range(0, len(lines), 27):
|
|
selected = lines[start:start + 35]
|
|
text = '\n'.join(selected)
|
|
overlap = terms & tokens(text)
|
|
if overlap:
|
|
score = len(overlap) / (len(tokens(text)) + 30) ** 0.35
|
|
candidates.append((score, path, start + 1, start + len(selected), text))
|
|
candidates.sort(key=lambda row: (-row[0], row[1], row[2]))
|
|
result = []
|
|
used = 0
|
|
for score, path, start, end, text in candidates:
|
|
if any(c['path'] == path and max(start, c['start']) <= min(end, c['end']) for c in result):
|
|
continue
|
|
size = len(text) + len(path) + 100
|
|
if used + size > budget:
|
|
continue
|
|
result.append(dict(id='R' + str(len(result) + 1).zfill(2), path=path, start=start, end=end,
|
|
sha256=hashlib.sha256(documents[path].encode()).hexdigest(), text=text))
|
|
used += size
|
|
if len(result) >= limit:
|
|
break
|
|
return result
|