Spaces:
Runtime error

ammo-card / memory.py
Expanded-Repetition's picture
Upload 17 files
2b4b6d8 verified
Raw History Blame Contribute Delete
14.5 kB
from __future__ import annotations
import json
import re
import sqlite3
import zipfile
from datetime import datetime, timezone
from pathlib import Path, PurePosixPath
from typing import Iterable
DB_PATH = Path(__file__).resolve().parent.parent / "data" / "amo_memory.sqlite3"
ALLOWED_SUFFIXES = {
".txt", ".md", ".py", ".json", ".yaml", ".yml", ".html", ".css",
".js", ".ts", ".tsx", ".jsx", ".toml", ".ini", ".log", ".sql",
".sh", ".xml", ".rst", ".java", ".kt", ".go", ".rs", ".c", ".h",
".cpp", ".hpp", ".cs", ".php", ".rb", ".swift"
}
MAX_FILE_BYTES = 1_000_000
MAX_ARCHIVE_FILES = 100
MAX_TOTAL_UPLOAD_BYTES = 8_000_000
def _now() -> str:
return datetime.now(timezone.utc).isoformat(timespec="seconds")
def _chunks(text: str, size: int = 2200, overlap: int = 250) -> list[str]:
clean = text.replace("\x00", " ").strip()
if not clean:
return []
out = []
start = 0
while start < len(clean):
part = clean[start : start + size].strip()
if part:
out.append(part)
if start + size >= len(clean):
break
start += size - overlap
return out
def _fts_query(query: str) -> str:
# FTS receives only quoted tokens, never raw FTS syntax from the user.
tokens = re.findall(r"[^\W_]+", query, flags=re.UNICODE)
tokens = [t for t in tokens if len(t) >= 2][:12]
return " OR ".join('"' + token.replace('"', '""') + '"' for token in tokens)
class MemoryStore:
"""A lightweight SQLite/FTS memory index. Secrets should never be saved here."""
def __init__(self, db_path: str | Path | None = None):
self.db_path = Path(db_path) if db_path else DB_PATH
self.db_path.parent.mkdir(parents=True, exist_ok=True)
self._init_db()
def _connect(self) -> sqlite3.Connection:
db = sqlite3.connect(self.db_path, timeout=15)
db.row_factory = sqlite3.Row
return db
def _init_db(self) -> None:
with self._connect() as db:
db.execute("""
CREATE TABLE IF NOT EXISTS memory_items (
id INTEGER PRIMARY KEY AUTOINCREMENT,
content TEXT NOT NULL,
source TEXT NOT NULL DEFAULT 'manual',
category TEXT NOT NULL DEFAULT 'note',
created_at TEXT NOT NULL
)
""")
db.execute("""
CREATE TABLE IF NOT EXISTS improvement_examples (
id INTEGER PRIMARY KEY AUTOINCREMENT,
task TEXT NOT NULL,
before_code TEXT NOT NULL,
after_code TEXT NOT NULL,
tests_code TEXT NOT NULL,
summary TEXT NOT NULL,
before_score REAL,
after_score REAL NOT NULL,
test_status TEXT NOT NULL,
accepted_at TEXT NOT NULL
)
""")
db.execute("""
CREATE VIRTUAL TABLE IF NOT EXISTS memory_fts USING fts5(
content, source, category, tokenize='unicode61'
)
""")
# Rebuild FTS if a previous process inserted rows before FTS was available.
fts_count = db.execute("SELECT count(*) FROM memory_fts").fetchone()[0]
item_count = db.execute("SELECT count(*) FROM memory_items").fetchone()[0]
if item_count and not fts_count:
db.execute("INSERT INTO memory_fts(rowid, content, source, category) SELECT id, content, source, category FROM memory_items")
def add(self, content: str, source: str = "manual", category: str = "note") -> int:
content = str(content).strip()
if not content:
raise ValueError("لا يمكن حفظ نص فارغ في الذاكرة.")
if len(content) > 50_000:
content = content[:50_000]
with self._connect() as db:
cur = db.execute(
"INSERT INTO memory_items(content, source, category, created_at) VALUES (?, ?, ?, ?)",
(content, source[:300], category[:80], _now()),
)
db.execute("INSERT INTO memory_fts(rowid, content, source, category) VALUES (?, ?, ?, ?)", (cur.lastrowid, content, source[:300], category[:80]))
return int(cur.lastrowid)
def search(self, query: str, limit: int = 5) -> list[dict]:
query = (query or "").strip()
if not query:
return []
limit = max(1, min(int(limit), 12))
fts_query = _fts_query(query)
with self._connect() as db:
rows = []
if fts_query:
try:
rows = db.execute(
"""SELECT m.id, m.content, m.source, m.category, m.created_at,
bm25(memory_fts) AS rank
FROM memory_fts JOIN memory_items m ON m.id = memory_fts.rowid
WHERE memory_fts MATCH ? ORDER BY rank LIMIT ?""",
(fts_query, limit),
).fetchall()
except sqlite3.Error:
rows = []
if not rows:
tokens = re.findall(r"[^\W_]+", query, flags=re.UNICODE)[:5]
if not tokens:
return []
where = " OR ".join("content LIKE ?" for _ in tokens)
vals = [f"%{x}%" for x in tokens] + [limit]
rows = db.execute(
f"SELECT id, content, source, category, created_at FROM memory_items WHERE {where} ORDER BY id DESC LIMIT ?",
vals,
).fetchall()
return [dict(r) for r in rows]
def list_recent(self, limit: int = 20) -> list[dict]:
with self._connect() as db:
rows = db.execute(
"SELECT id, content, source, category, created_at FROM memory_items ORDER BY id DESC LIMIT ?",
(max(1, min(int(limit), 100)),),
).fetchall()
return [dict(r) for r in rows]
def clear_memory(self) -> int:
with self._connect() as db:
count = db.execute("SELECT count(*) FROM memory_items").fetchone()[0]
db.execute("DELETE FROM memory_items")
db.execute("DELETE FROM memory_fts")
return int(count)
def export_memory_jsonl(self, output_path: str | Path) -> int:
out = Path(output_path)
out.parent.mkdir(parents=True, exist_ok=True)
with self._connect() as db, out.open("w", encoding="utf-8") as f:
rows = db.execute("SELECT content, source, category, created_at FROM memory_items ORDER BY id").fetchall()
for row in rows:
f.write(json.dumps(dict(row), ensure_ascii=False) + "\n")
return len(rows)
def import_memory_jsonl(self, input_path: str | Path) -> tuple[int, list[str]]:
src = Path(input_path)
notes = []
imported = 0
if not src.is_file() or src.stat().st_size > 10_000_000:
return 0, ["ملف الذاكرة غير موجود أو أكبر من 10MB."]
try:
with src.open(encoding="utf-8") as f:
for line_no, line in enumerate(f, start=1):
if imported >= 2000:
notes.append("توقف الاستيراد عند 2000 مقطع.")
break
if not line.strip():
continue
try:
item = json.loads(line)
content = item.get("content") if isinstance(item, dict) else None
if not isinstance(content, str) or not content.strip():
notes.append(f"تخطي السطر {line_no}: لا يوجد content صالح.")
continue
content = content[:50_000]
with self._connect() as db:
exists = db.execute("SELECT 1 FROM memory_items WHERE content = ? LIMIT 1", (content,)).fetchone()
if exists:
continue
source_name = str(item.get("source") or "استيراد ذاكرة")[:250]
category = str(item.get("category") or "imported")[:80]
self.add(content, source=f"مستورد · {source_name}", category=category)
imported += 1
except (json.JSONDecodeError, OSError, TypeError, ValueError) as exc:
notes.append(f"السطر {line_no}: {type(exc).__name__}: {exc}")
except OSError as exc:
notes.append(f"تعذر قراءة الملف: {exc}")
return imported, notes
def save_improvement(
self, *, task: str, before_code: str, after_code: str, tests_code: str,
summary: str, before_score: float | None, after_score: float, test_status: str,
) -> int:
with self._connect() as db:
cur = db.execute(
"""INSERT INTO improvement_examples
(task,before_code,after_code,tests_code,summary,before_score,after_score,test_status,accepted_at)
VALUES (?,?,?,?,?,?,?,?,?)""",
(task[:20_000], before_code[:100_000], after_code[:100_000], tests_code[:50_000],
summary[:10_000], before_score, float(after_score), test_status[:200], _now()),
)
return int(cur.lastrowid)
def export_training_jsonl(self, output_path: str | Path) -> int:
out = Path(output_path)
out.parent.mkdir(parents=True, exist_ok=True)
with self._connect() as db, out.open("w", encoding="utf-8") as f:
rows = db.execute(
"SELECT task,before_code,after_code,tests_code,summary,test_status FROM improvement_examples WHERE test_status = 'passed' ORDER BY id"
).fetchall()
for r in rows:
user_text = (
"مهمة تحسين كود Python. حافظ على السلوك المطلوب، اقرأ الاختبارات، ولا تدّعِ نجاحاً لم يتم اختباره.\n"
f"المهمة:\n{r['task']}\n\nالكود السابق:\n```python\n{r['before_code']}\n```\n\n"
f"الاختبارات:\n```python\n{r['tests_code']}\n```\n\nملخص التغيير السابق: {r['summary']}"
)
record = {"messages": [
{"role": "user", "content": user_text},
{"role": "assistant", "content": r["after_code"]},
]}
f.write(json.dumps(record, ensure_ascii=False) + "\n")
return len(rows)
def import_files(self, filepaths: Iterable[str | Path]) -> tuple[int, int, list[str]]:
"""Index plain text/code files and safe ZIP members without extracting them."""
files_seen, chunks_saved, errors = 0, 0, []
total_bytes = 0
for raw in filepaths or []:
path = Path(raw)
try:
if not path.exists() or not path.is_file():
errors.append(f"تخطي ملف غير موجود: {path.name}")
continue
if path.suffix.lower() == ".zip":
with zipfile.ZipFile(path) as zf:
for info in zf.infolist()[:MAX_ARCHIVE_FILES]:
p = PurePosixPath(info.filename)
if info.is_dir() or p.is_absolute() or ".." in p.parts or p.suffix.lower() not in ALLOWED_SUFFIXES:
continue
if info.file_size > MAX_FILE_BYTES:
continue
total_bytes += info.file_size
if total_bytes > MAX_TOTAL_UPLOAD_BYTES:
raise ValueError("تجاوزت الملفات حد الحجم الإجمالي المسموح للفهرسة.")
try:
data = zf.read(info)
content = data.decode("utf-8", errors="replace")
chunks_saved += self._save_document_chunks(content, f"{path.name}/{info.filename}")
files_seen += 1
except (RuntimeError, zipfile.BadZipFile, OSError) as exc:
errors.append(f"تعذر قراءة {info.filename}: {exc}")
elif path.suffix.lower() in ALLOWED_SUFFIXES:
if path.stat().st_size > MAX_FILE_BYTES:
errors.append(f"تخطي {path.name}: أكبر من 1MB.")
continue
total_bytes += path.stat().st_size
if total_bytes > MAX_TOTAL_UPLOAD_BYTES:
raise ValueError("تجاوزت الملفات حد الحجم الإجمالي المسموح للفهرسة.")
content = path.read_text(encoding="utf-8", errors="replace")
chunks_saved += self._save_document_chunks(content, path.name)
files_seen += 1
else:
errors.append(f"تخطي امتداد غير مدعوم: {path.name}")
except (OSError, zipfile.BadZipFile, ValueError) as exc:
errors.append(f"{path.name}: {exc}")
return files_seen, chunks_saved, errors
def _save_document_chunks(self, content: str, source: str) -> int:
chunks = _chunks(content)
# Cap per file to keep accidental uploads from filling session storage.
for i, part in enumerate(chunks[:80], start=1):
self.add(part, source=f"{source} · جزء {i}", category="document")
return min(len(chunks), 80)
def format_memory_hits(hits: list[dict], max_chars: int = 6500) -> str:
out, used = [], 0
for hit in hits:
block = f"[المصدر: {hit['source']} | الفئة: {hit['category']}]\n{hit['content']}"
if used + len(block) > max_chars:
block = block[: max(0, max_chars - used)]
if block:
out.append(block)
used += len(block)
if used >= max_chars:
break
return "\n\n---\n\n".join(out)