Files
netbox/vinogorod/scripts/2_chunk_text.py
T
hermes bbf8b20802 vinogorod: проект СКС «Винный город» — скрипты, документация, снимки справочников NetBox
- скрипты: экспорт справочников (export_netbox_refs) и портовой модели
  (export_netbox_inventory) для составления CSV-импорта устройств/соединений
- docs: CSV-снимки справочников + inventory JSON (2026-10-12, сайт «Винный город»)
- статус/план/конспекты проекта; .gitignore исключает .venv, skc_pdfs, skc_texts
2026-10-12 05:41:30 +00:00

111 lines
4.2 KiB
Python
Executable File
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""
Шаг 2: Чанкинг markdown-текста СКС для инжекта в Qdrant.
Вход : каталог с .md (по умолчанию skc_texts/)
Выход: каталог с .json-чанками (по умолчанию skc_chunks/) — по одному файлу
на исходный PDF, список чанков [{text, meta}].
Стратегия чанкинга (как в bulk_wiki_ingest_ollama.py — рекурсивный сплит):
1. По заголовкам ## / ### / ####
2. Если большой — по абзацам
3. Последний резерв — по словам
MAX_CHUNK_SIZE=5000, CHUNK_OVERLAP=300 (совместимо с bge-m3, лимит ~6000).
Использование:
.venv/bin/python3 scripts/2_chunk_text.py [md_dir] [out_dir]
"""
import sys, json, re, pathlib
MAX_CHUNK_SIZE = 5000
CHUNK_OVERLAP = 300
def split_by_headings(text: str):
"""Сплит по ##/###/#### с сохранением заголовка в начале чанка."""
chunks, cur, cur_head = [], "", ""
for line in text.splitlines():
if re.match(r"^#{2,4} ", line):
if cur.strip():
chunks.append(((cur_head + "\n" + cur).strip()))
cur_head = line
cur = ""
else:
cur += line + "\n"
if cur.strip():
chunks.append((cur_head + "\n" + cur).strip())
return chunks or [text]
def split_paragraphs(text: str):
return [c.strip() for c in re.split(r"\n\s*\n", text) if c.strip()]
def chunk_text(text: str, max_size=MAX_CHUNK_SIZE):
"""Рекурсивный сплит: headings -> paragraphs -> words."""
if len(text) <= max_size:
return [text]
by_head = split_by_headings(text)
if len(by_head) > 1:
out = []
for h in by_head:
out.extend(chunk_text(h, max_size))
if out and sum(len(c) for c in out) <= max_size * 1.5:
return out
return _merge_or_return(out, max_size)
paras = split_paragraphs(text)
if len(paras) > 1:
return _merge_or_return([chunk_text(p, max_size)[0] for p in paras if p], max_size)
words = text.split()
if len(words) == 1:
return [text]
out, cur = [], ""
for w in words:
if len(cur) + len(w) + 1 > max_size:
out.append(cur.strip()); cur = w
else:
cur += (" " if cur else "") + w
if cur.strip():
out.append(cur.strip())
return out
def _merge_or_return(chunks, max_size):
"""Объединить мелкие чанки до ~max_size, но не ломая большие."""
merged, buf = [], ""
for c in chunks:
if len(c) > max_size:
if buf: merged.append(buf); buf = ""
merged.append(c)
elif len(buf) + len(c) + 1 <= max_size:
buf += ("\n\n" if buf else "") + c
else:
merged.append(buf); buf = c
if buf: merged.append(buf)
return merged
def main() -> int:
md_dir = pathlib.Path(sys.argv[1] if len(sys.argv) > 1 else "skc_texts")
out_dir = pathlib.Path(sys.argv[2] if len(sys.argv) > 2 else "skc_chunks")
out_dir.mkdir(parents=True, exist_ok=True)
mds = sorted(md_dir.glob("*.md"))
if not mds:
print(f"[!] Нет .md в {md_dir}")
return 1
manifest = []
for md in mds:
text = md.read_text(encoding="utf-8")
chunks = chunk_text(text)
recs = [{"text": c, "meta": {"source": md.name, "chunk_index": i,
"chunk_total": len(chunks)}} for i, c in enumerate(chunks)]
out_path = out_dir / f"{md.stem}.json"
out_path.write_text(json.dumps(recs, ensure_ascii=False, indent=1), encoding="utf-8")
manifest.append({"md": md.name, "json": out_path.name, "chunks": len(chunks),
"chars": len(text)})
print(f"[OK] {md.name}: {len(chunks)} чанков, {len(text)} симв.")
(out_dir / "manifest.json").write_text(
json.dumps(manifest, ensure_ascii=False, indent=2), encoding="utf-8")
print(f"\nМанифест: {out_dir / 'manifest.json'}")
return 0
if __name__ == "__main__":
sys.exit(main())