Spaces:
Runtime error
Runtime error
File size: 14,468 Bytes
2b4b6d8 | 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 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 | 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)
|