new features

This commit is contained in:
Mark Gregory
2026-11-17 15:35:04 +00:00
parent 71972cd843
commit d1a1b454f6
18 changed files with 2598 additions and 112 deletions
+140
View File
@@ -0,0 +1,140 @@
"""Manage the existing Pegasus index over an authenticated SSH connection."""
import fcntl
import json
from pathlib import Path
import re
import shutil
import sqlite3
import subprocess
import sys
PROJECT = Path("/mnt/knowledge-base")
DOCUMENTS = PROJECT / "documents"
DATABASE = PROJECT / "data/chroma"
STATE = Path.home() / ".local/state/aistudio-knowledge"
LOCK = STATE / "job.lock"
LAST_RUN = STATE / "last-run.json"
LOG = STATE / "index.log"
def is_locked(path):
try:
with path.open("rb") as handle:
try:
fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
return True
except FileNotFoundError:
pass
return False
def start():
if not PROJECT.is_mount():
raise RuntimeError("The knowledge-base volume is not mounted.")
if not DOCUMENTS.is_dir() or not DATABASE.is_dir():
raise RuntimeError("The Pegasus document or index directory is missing.")
STATE.mkdir(mode=0o700, parents=True, exist_ok=True)
with LOCK.open("a") as handle:
try:
fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
return {"started": False, "message": "Indexing is already running."}
if is_locked(DATABASE / ".index.lock"):
return {"started": False, "message": "Pegasus is already indexing outside AI Studio."}
# The detached worker inherits the lock and keeps it until the run has finished.
settings = [str(LAST_RUN), str(LOG), str(PROJECT), str(DOCUMENTS), str(DATABASE), str(handle.fileno())]
subprocess.Popen(
[sys.executable, "-B", "-c", WORKER, *settings],
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
start_new_session=True, pass_fds=(handle.fileno(),),
)
return {"started": True, "message": "Pegasus accepted the index refresh."}
def status():
mounted = PROJECT.is_mount()
result = {"mounted": mounted, "documents": str(DOCUMENTS), "database": str(DATABASE),
"running": is_locked(LOCK), "externalRunning": mounted and is_locked(DATABASE / ".index.lock")}
if mounted:
index = DATABASE / "chroma.sqlite3"
if index.is_file():
try:
with sqlite3.connect(index.as_uri() + "?mode=ro", uri=True, timeout=2) as connection:
result["sources"], result["chunks"] = connection.execute(
"SELECT COUNT(DISTINCT string_value), COUNT(*) FROM embedding_metadata WHERE key = 'source'"
).fetchone()
result["currentRootChunks"] = connection.execute(
"SELECT COUNT(*) FROM embedding_metadata WHERE key = 'root' AND string_value = ?",
(str(DOCUMENTS),),
).fetchone()[0]
result["modified"] = index.stat().st_mtime
result["bytes"] = sum(path.stat().st_size for path in DATABASE.rglob("*") if path.is_file())
except (OSError, sqlite3.Error) as error:
result["statisticsError"] = str(error)
result["freeBytes"] = shutil.disk_usage(PROJECT).free
if LAST_RUN.is_file():
result["lastRun"] = json.loads(LAST_RUN.read_text())
if LOG.is_file():
with LOG.open("rb") as handle:
size = handle.seek(0, 2)
handle.seek(max(0, size - 8192))
lines = handle.read(8192).decode("utf-8", errors="replace").splitlines()
result["log"] = "\n".join(lines[-20:])
for line in reversed(lines):
match = re.match(r"^\[(\d+)/(\d+)\]", line)
if match:
result["processed"], result["totalFiles"] = map(int, match.groups())
break
return result
WORKER = r"""
import json
from pathlib import Path
import subprocess
import sys
import time
state, log, root, documents, database = map(Path, sys.argv[1:6])
lock_fd = int(sys.argv[6])
started = time.time()
result = {"started": started}
def save():
temporary = state.with_suffix(".tmp")
temporary.write_text(json.dumps(result))
temporary.replace(state)
with log.open("w") as output:
save()
try:
# Keep the inherited lock in the index process if the worker is interrupted.
process = subprocess.run(
[sys.executable, "-B", str(root / "src/knowledge_mcp.py"), "--database",
str(database), "--index", str(documents)], cwd=root, stdout=output,
stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL, pass_fds=(lock_fd,),
)
result["exitCode"] = process.returncode
except Exception as error:
print(error, file=output, flush=True)
result["exitCode"] = 1
result["finished"] = time.time()
save()
"""
def main():
try:
operation = {"status": status, "start": start}[sys.argv[1]]
print(json.dumps(operation()))
except (OSError, RuntimeError, ValueError, KeyError) as error:
print(str(error), file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
+122
View File
@@ -0,0 +1,122 @@
#!/usr/bin/env python3
"""Validate local chat examples and run the MLX LM training stages."""
import argparse
import json
import os
from pathlib import Path
import shutil
import sys
def validate_dataset(directory):
previous_splits = {}
for split in ("train", "valid", "test"):
path = directory / f"{split}.jsonl"
count = 0
with path.open(encoding="utf-8") as examples:
for line_number, line in enumerate(examples, 1):
try:
example = json.loads(line)
messages = example.get("messages") if isinstance(example, dict) else None
if not isinstance(messages, list) or len(messages) < 2:
raise ValueError("expected a messages array with at least two turns")
if any(
not isinstance(message, dict)
or message.get("role") not in ("system", "user", "assistant")
or not isinstance(message.get("content"), str)
or not message["content"].strip()
for message in messages
):
raise ValueError("expected system, user, or assistant turns with nonempty text")
if messages[-1]["role"] != "assistant" or not any(
message["role"] == "user" for message in messages[:-1]
):
raise ValueError("expected a user turn followed by a final assistant answer")
key = tuple((message["role"], " ".join(message["content"].split())) for message in messages[:-1])
earlier = previous_splits.setdefault(key, split)
if earlier != split:
raise ValueError(f"the same prompt appears in {earlier} and {split}")
except ValueError as error:
raise ValueError(f"{path.name}:{line_number}: {error}") from error
count += 1
if count == 0:
raise ValueError(f"{path.name}: add at least one example")
print(f"{split}: {count} examples", flush=True)
def positive_int(value):
count = int(value)
if count < 1:
raise argparse.ArgumentTypeError("must be positive")
return count
def main():
parser = argparse.ArgumentParser(description=__doc__)
actions = parser.add_subparsers(dest="action", required=True)
for action in ("validate", "train", "evaluate", "fuse"):
command = actions.add_parser(action)
if action != "fuse":
command.add_argument("--data", required=True, type=Path)
if action != "validate":
command.add_argument("--base", required=True, type=Path)
command.add_argument("--adapter", required=True, type=Path)
if action == "train":
command.add_argument("--iters", type=positive_int, default=50)
command.add_argument("--layers", type=positive_int, default=4)
if action == "fuse":
command.add_argument("--out", required=True, type=Path)
convert = actions.add_parser("convert")
convert.add_argument("--source", required=True)
convert.add_argument("--out", required=True, type=Path)
convert.add_argument("--revision")
convert.add_argument("--quantize", action="store_true")
args = parser.parse_args()
try:
if args.action == "convert":
from mlx_lm.convert import convert as convert_model
convert_model(args.source, mlx_path=str(args.out.resolve()), revision=args.revision,
quantize=args.quantize, q_bits=4 if args.quantize else None)
return 0
if args.action != "fuse":
validate_dataset(args.data.resolve())
if args.action == "validate":
return 0
base = args.base.resolve()
adapter = args.adapter.resolve()
if not (base / "config.json").is_file() or not any(base.glob("*.safetensors")):
raise ValueError("choose a local MLX model folder with config.json and safetensors weights")
model = ["--model", str(base), "--adapter-path", str(adapter)]
if args.action == "train":
if adapter.exists() or base in adapter.parents:
raise ValueError("choose a new adapter directory outside the base checkpoint")
command = ["mlx_lm.lora", *model, "--train", "--data", str(args.data.resolve()),
"--mask-prompt", "--batch-size", "1", "--num-layers", str(args.layers),
"--iters", str(args.iters)]
else:
if not (adapter / "adapters.safetensors").is_file():
raise ValueError("choose a trained adapter folder containing adapters.safetensors")
if args.action == "evaluate":
command = ["mlx_lm.lora", *model, "--test", "--data", str(args.data.resolve())]
else:
out = args.out.resolve()
if out.exists() or base in out.parents or adapter in out.parents:
raise ValueError("choose a new output directory outside the base and adapter folders")
command = ["mlx_lm.fuse", *model, "--save-path", str(out)]
executable = shutil.which(command[0])
if executable is None:
raise FileNotFoundError(f"{command[0]} is missing. Install mlx-lm[train].")
os.execv(executable, command)
except (OSError, ValueError) as error:
print(f"Training workflow: {error}", file=sys.stderr)
return 1
except KeyboardInterrupt:
return 130
if __name__ == "__main__":
sys.exit(main())