141 lines
5.1 KiB
Python
141 lines
5.1 KiB
Python
"""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())
|