Initial open source release

This commit is contained in:
tv5171621-source
2026-06-15 02:47:14 +03:00
commit 5c59152c06
44 changed files with 1640 additions and 0 deletions
+23
View File
@@ -0,0 +1,23 @@
---
name: local-doc-ops
description: Use when extracting, inspecting, splitting, or converting local PDFs, documents, and image-based files before they enter a knowledge pipeline.
---
# Local Document Operations
Use local deterministic tools before spending model context.
Preferred order:
1. Use structured parsers for PDFs and office documents.
2. Use Apple Vision OCR for images on macOS.
3. Use transcription for audio or video.
4. Only then ask a model to interpret unclear content.
Keep raw extracted text in cache or inbox. Write only refined knowledge into the vault.
Bundled helper:
```bash
python skills/local-doc-ops/pdf-kit.py --help
```
+108
View File
@@ -0,0 +1,108 @@
#!/usr/bin/env python3
"""
pdf-kit — локальный PDF-тулкит для юрпрактики. $0, без Docker, на PyMuPDF (fitz).
OCR делает Apple Vision (vision-ocr) — здесь НЕ дублируется.
Команды:
merge OUT.pdf IN1 IN2 ... сшить файлы (PDF+картинки) в один PDF ПО ПОРЯДКУ
compress IN.pdf OUT.pdf сжать PDF (deflate + чистка мусора + сабсет шрифтов)
img2pdf OUT.pdf IMG1 IMG2 ... картинки → один PDF (по порядку)
sign IN.pdf OUT.pdf SIG.png наложить подпись-картинку: --page N (1-based, def посл.) --x --y (доля 0..1, def 0.62/0.78) --w (доля ширины, def 0.25)
extract IN.pdf [OUT.md] PDF → markdown (markitdown) для изучения в Мнемозине
pages IN.pdf инфо: число страниц, размер
Пути с пробелами/юникодом — в кавычках. Документы остаются ЛОКАЛЬНО (ничего не уходит наружу).
"""
import sys, os, subprocess
def _fitz():
import fitz
return fitz
IMG_EXT = (".png", ".jpg", ".jpeg", ".webp", ".tif", ".tiff", ".bmp", ".heic", ".heif", ".gif")
def _add_file_to_doc(doc, fitz, path):
ext = os.path.splitext(path)[1].lower()
if ext == ".pdf":
with fitz.open(path) as src:
doc.insert_pdf(src)
elif ext in IMG_EXT:
img = fitz.open(path)
rect = img[0].rect
pdfbytes = img.convert_to_pdf()
img.close()
with fitz.open("pdf", pdfbytes) as imgpdf:
doc.insert_pdf(imgpdf)
else:
raise SystemExit(f"merge: не поддержан тип {ext} ({os.path.basename(path)}). PDF/картинки.")
def cmd_merge(args):
fitz = _fitz()
out, ins = args[0], args[1:]
if not ins:
raise SystemExit("merge OUT.pdf IN1 IN2 ...")
doc = fitz.open()
for p in ins:
if not os.path.exists(p):
raise SystemExit(f"нет файла: {p}")
_add_file_to_doc(doc, fitz, p)
doc.save(out, garbage=4, deflate=True)
doc.close()
print(f"OK merge → {out} ({len(ins)} файлов по порядку)")
def cmd_img2pdf(args):
cmd_merge(args) # merge уже принимает картинки
def cmd_compress(args):
fitz = _fitz()
src, out = args[0], args[1]
before = os.path.getsize(src)
doc = fitz.open(src)
doc.save(out, garbage=4, deflate=True, deflate_images=True, deflate_fonts=True, clean=True)
doc.close()
after = os.path.getsize(out)
pct = round((1 - after / before) * 100) if before else 0
print(f"OK compress → {out} ({before//1024}KB → {after//1024}KB, -{pct}%)")
def cmd_sign(args):
fitz = _fitz()
opts = {a.split("=")[0]: a.split("=")[1] for a in args if a.startswith("--") and "=" in a}
pos = [a for a in args if not a.startswith("--")]
src, out, sig = pos[0], pos[1], pos[2]
doc = fitz.open(src)
page_n = int(opts.get("--page", len(doc))) # 1-based; def последняя
page = doc[page_n - 1]
pr = page.rect
fx = float(opts.get("--x", 0.62)); fy = float(opts.get("--y", 0.78)); fw = float(opts.get("--w", 0.25))
from PIL import Image
iw, ih = Image.open(sig).size
w = pr.width * fw
h = w * ih / iw
x0 = pr.width * fx; y0 = pr.height * fy
page.insert_image(fitz.Rect(x0, y0, x0 + w, y0 + h), filename=sig, keep_proportion=True, overlay=True)
doc.save(out, garbage=4, deflate=True)
doc.close()
print(f"OK sign → {out} (стр {page_n}, подпись {os.path.basename(sig)})")
def cmd_extract(args):
src = args[0]
out = args[1] if len(args) > 1 else os.path.splitext(src)[0] + ".md"
r = subprocess.run(["markitdown", src], capture_output=True, text=True)
if r.returncode != 0:
raise SystemExit("markitdown error: " + r.stderr[:300])
open(out, "w").write(r.stdout)
print(f"OK extract → {out} ({len(r.stdout)} симв, для Мнемозины)")
def cmd_pages(args):
fitz = _fitz()
doc = fitz.open(args[0])
print(f"{os.path.basename(args[0])}: {len(doc)} стр, {os.path.getsize(args[0])//1024}KB")
doc.close()
CMDS = {"merge": cmd_merge, "img2pdf": cmd_img2pdf, "compress": cmd_compress,
"sign": cmd_sign, "extract": cmd_extract, "pages": cmd_pages}
if __name__ == "__main__":
if len(sys.argv) < 2 or sys.argv[1] not in CMDS:
print(__doc__); sys.exit(0 if len(sys.argv) < 2 else 1)
CMDS[sys.argv[1]](sys.argv[2:])
+52
View File
@@ -0,0 +1,52 @@
---
name: mnemazine
description: Use when turning raw files, links, screenshots, transcripts, PDFs, guides, or repositories into verified reusable knowledge for an Obsidian-compatible vault.
---
# Mnemazine
Mnemazine is a knowledge refinery skill.
Use it when the user gives raw material and wants it preserved as durable knowledge, not as a dump.
## Contract
The vault stores final knowledge only.
Do not write raw OCR, copied fragments, noisy transcripts, or unverified paste dumps directly into the vault.
## Workflow
1. Identify what the source is: screenshot, PDF, site, code repo, video, transcript, guide, or inline text.
2. Extract locally when possible: text parser, PDF parser, Apple Vision OCR, or transcription.
3. Understand the topic before writing.
4. Research public sources when the claim depends on current or external facts.
5. Split one source into multiple notes when it contains multiple unrelated ideas.
6. Write clear notes with source links, verification status, practical use, and related concepts.
7. Run the vault quality gate.
8. Update Graphify when available.
9. Produce a short action brief when the new knowledge implies work.
## Note Shape
Every durable note should contain:
- `What This Is`;
- `Why It Matters`;
- `How To Use It`;
- `Source`;
- `Verification`;
- `Related Notes`;
- `Reuse`.
## Local Paths
Use environment variables:
- `MNEMAZINE_ROOT`;
- `MNEMAZINE_INBOX`;
- `MNEMAZINE_VAULT`;
- `MNEMAZINE_REPORTS`;
- `MNEMAZINE_STATE`.
Never assume a specific username, home path, private project, SSH host, or API key.
+125
View File
@@ -0,0 +1,125 @@
#!/usr/bin/env python3
"""kb-embed — локальный семантический индекс vault для дедупа Мнемозины.
Без Ollama/облака: fastembed (onnxruntime) + multilingual-e5-small, CPU.
Ловит смысловые дубли, которые hash-cache (байтовый) пропускает —
пере-скриншот/пере-сейв того же знания с другим хэшем.
Запуск:
python skills/mnemazine/kb-embed.py <cmd> ...
Команды:
build <vault> <out.json> — эмбеддит все ноты → индекс
add <out.json> <note.md> [note.md...] — дозаписать ноты в индекс
query <idx.json> <text> [topk] [thr] — топ-похожих нот (cosine)
Все ответы — одна строка JSON (для парсинга агентом).
"""
import sys
import os
import json
import glob
import math
import warnings
warnings.filterwarnings("ignore") # чистый JSON-выхлоп для парсинга агентом
MODEL = "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2" # 384d, ~220MB, мультиязык RU
MAX_CHARS = 2000 # хвост ноты не нужен для темы
def _emb(texts, prefix):
from fastembed import TextEmbedding
model = TextEmbedding(MODEL)
return [v.tolist() for v in model.embed([prefix + t for t in texts])]
def _strip_fm(text):
"""Убрать YAML-frontmatter, оставить тело."""
t = text
if t.startswith("---"):
end = t.find("\n---", 3)
if end != -1:
t = t[end + 4:]
return t.strip()
def _is_content_note(p):
bad = ("/graphify-out/", "/.git/", "/.obsidian/")
if any(b in p for b in bad):
return False
return not os.path.basename(p).startswith("_")
def _read_body(p):
try:
return _strip_fm(open(p, encoding="utf-8").read())[:MAX_CHARS]
except Exception:
return ""
def _cos(a, b):
d = sum(x * y for x, y in zip(a, b))
na = math.sqrt(sum(x * x for x in a))
nb = math.sqrt(sum(y * y for y in b))
return d / (na * nb) if na and nb else 0.0
def cmd_build(vault, out):
notes = [p for p in glob.glob(vault + "/**/*.md", recursive=True) if _is_content_note(p)]
bodies = [_read_body(p) for p in notes]
pairs = [(p, b) for p, b in zip(notes, bodies) if b]
vecs = _emb([b for _, b in pairs], "") if pairs else []
idx = {p: v for (p, _), v in zip(pairs, vecs)}
json.dump(idx, open(out, "w"), ensure_ascii=False)
print(json.dumps({"indexed": len(idx), "out": out}))
def cmd_add(out, notes):
idx = json.load(open(out)) if os.path.exists(out) else {}
bodies = [_read_body(p) for p in notes]
pairs = [(p, b) for p, b in zip(notes, bodies) if b]
if pairs:
vecs = _emb([b for _, b in pairs], "")
for (p, _), v in zip(pairs, vecs):
idx[p] = v
json.dump(idx, open(out, "w"), ensure_ascii=False)
print(json.dumps({"added": len(pairs), "total": len(idx)}))
def cmd_query(idxfile, text, topk=3, thr=0.0):
idx = json.load(open(idxfile)) if os.path.exists(idxfile) else {}
if not idx:
print(json.dumps({"matches": [], "top": 0.0, "note": "index empty"}))
return
qv = _emb([text[:MAX_CHARS]], "")[0]
scored = sorted(((_cos(qv, v), p) for p, v in idx.items()), reverse=True)[:topk]
matches = [{"note": p, "score": round(s, 4)} for s, p in scored if s >= thr]
print(json.dumps({"matches": matches, "top": round(scored[0][0], 4) if scored else 0.0},
ensure_ascii=False))
def main():
if len(sys.argv) < 2:
print(json.dumps({"error": "usage: build|add|query"}))
sys.exit(1)
cmd = sys.argv[1]
try:
if cmd == "build":
cmd_build(sys.argv[2], sys.argv[3])
elif cmd == "add":
cmd_add(sys.argv[2], sys.argv[3:])
elif cmd == "query":
topk = int(sys.argv[4]) if len(sys.argv) > 4 else 3
thr = float(sys.argv[5]) if len(sys.argv) > 5 else 0.0
cmd_query(sys.argv[2], sys.argv[3], topk, thr)
else:
print(json.dumps({"error": "unknown cmd: " + cmd}))
sys.exit(1)
except Exception as e:
print(json.dumps({"error": str(e)}))
sys.exit(1)
if __name__ == "__main__":
main()
+17
View File
@@ -0,0 +1,17 @@
import Foundation
import Vision
import AppKit
let args = CommandLine.arguments
guard args.count > 1, let img = NSImage(contentsOfFile: args[1]),
let cg = img.cgImage(forProposedRect: nil, context: nil, hints: nil) else {
FileHandle.standardError.write("load fail\n".data(using:.utf8)!); exit(1)
}
let req = VNRecognizeTextRequest { r, _ in
guard let obs = r.results as? [VNRecognizedTextObservation] else { return }
for o in obs { if let t = o.topCandidates(1).first { print(t.string) } }
}
req.recognitionLevel = .accurate
req.recognitionLanguages = ["ru-RU","en-US"]
req.usesLanguageCorrection = true
try? VNImageRequestHandler(cgImage: cg, options: [:]).perform([req])