auto-sync 2026-07-25 10:16:42
This commit is contained in:
+17
-2
@@ -1,9 +1,24 @@
|
|||||||
{
|
{
|
||||||
"hooks": {
|
"hooks": {
|
||||||
|
"PreToolUse": [
|
||||||
|
{
|
||||||
|
"matcher": "Read|Write|Edit|NotebookEdit|Bash",
|
||||||
|
"hooks": [
|
||||||
|
{
|
||||||
|
"type": "command",
|
||||||
|
"command": "python3 \"$CLAUDE_PROJECT_DIR/scripts/claude_guard.py\""
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
"Stop": [
|
"Stop": [
|
||||||
{
|
{
|
||||||
"command": "mkdir -p $CLAUDE_PROJECT_DIR/cases/_logs && echo \"Session ended: $(date '+%d.%m.%Y %H:%M')\" >> $CLAUDE_PROJECT_DIR/cases/_logs/_session_history.txt",
|
"hooks": [
|
||||||
"description": "Log session end timestamp"
|
{
|
||||||
|
"type": "command",
|
||||||
|
"command": "mkdir -p \"$CLAUDE_PROJECT_DIR/cases/_logs\" && echo \"Session ended: $(date '+%d.%m.%Y %H:%M')\" >> \"$CLAUDE_PROJECT_DIR/cases/_logs/_session_history.txt\""
|
||||||
|
}
|
||||||
|
]
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -26,3 +26,15 @@
|
|||||||
- **Причина:** команда `/new-case` по умолчанию перемещает ВСЕ файлы инбокса в одно новое дело, что корректно только при монотематическом инбоксе.
|
- **Причина:** команда `/new-case` по умолчанию перемещает ВСЕ файлы инбокса в одно новое дело, что корректно только при монотематическом инбоксе.
|
||||||
- **Исправлено:** фильтр по метке времени поступления (последний час) + тематическая сверка содержимого (OCR первой страницы) до перемещения.
|
- **Исправлено:** фильтр по метке времени поступления (последний час) + тематическая сверка содержимого (OCR первой страницы) до перемещения.
|
||||||
- **Системное правило:** перед массовым перемещением инбокса в `00_intake/` — группировать файлы по времени поступления и тематике; перемещать только группу текущего дела, остальное оставлять на месте с записью в `_index.md` → раздел Inbox. При сомнении — спросить, а не перемещать все подряд.
|
- **Системное правило:** перед массовым перемещением инбокса в `00_intake/` — группировать файлы по времени поступления и тематике; перемещать только группу текущего дела, остальное оставлять на месте с записью в `_index.md` → раздел Inbox. При сомнении — спросить, а не перемещать все подряд.
|
||||||
|
|
||||||
|
## 23.07.2026 — внешняя апелляционная жалоба содержала выдуманную опору на КС РФ; анонимизация совета читается по стилю
|
||||||
|
|
||||||
|
По делу doveritel-6/elling-apellyaciya-2026 поданная извне апелляционная жалоба ссылалась на КС РФ № 1-П от 14.01.2016 как на позицию о защите доверия к документам госорганов. Проверка по первоисточнику (ksrf.ru) охотником-тактиком: это постановление по пенсионному делу Иванова, к теме отношения не имеет. Ошибка поймана только потому, что охотник обязан верифицировать каждый акт по первоисточнику. В дополнении к жалобе дана формула уточнения позиции с заменой на КС № 22-П от 26.05.2025 и № 35-П от 28.05.2026.
|
||||||
|
|
||||||
|
- **Причина:** документ, составленный вне конвейера, содержал неверифицированную ссылку, перекочевавшую бы и в наши документы.
|
||||||
|
- **Системное правило:** ссылки на КС РФ/Пленумы в ЛЮБЫХ документах, пришедших извне (иск, жалоба доверителя), сверять по первоисточнику до заимствования в наших текстах; доверителю — отдельное предупреждение о замене.
|
||||||
|
|
||||||
|
Второй урок той же сессии: анонимизация /askacouncil не работает, если стиль отчета выдает охотника (враждебный поиск скептика узнаваем) — 2 из 3 рецензентов приписали отчету «Б» черты чужого отчета.
|
||||||
|
|
||||||
|
- **Исправлено:** маппинг зафиксирован в council_reviews.md, председатель оценивал по деанонимизированным отчетам, вердикт не пострадал.
|
||||||
|
- **Системное правило:** перед раздачей рецензентам снимать с hunter-файлов заголовки/самоназвания охотников, либо предупреждать рецензентов, что стиль отчета не является основанием атрибуции.
|
||||||
|
|||||||
@@ -0,0 +1,62 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""PreToolUse guard Фемиды: детерминированное исполнение железных правил.
|
||||||
|
|
||||||
|
Блокирует (exit 2, причина в stderr — видна модели):
|
||||||
|
1. Read бинарных документов (.docx/.pdf/.xlsx/.pptx/.doc/.xls) —
|
||||||
|
только через scripts/markdown_extract.py (LOCAL-FIRST, кеш, requisites.json).
|
||||||
|
2. Write/Edit внутрь 00_intake/ — исходники клиента неприкосновенны.
|
||||||
|
3. Bash rm/rmdir по 00_intake/ или _baselines/ — защита первички и базы «ДО».
|
||||||
|
|
||||||
|
Правила-инварианты продублированы текстом в .claude/CLAUDE.md;
|
||||||
|
здесь — их жесткое исполнение (advisory-текст модель может пропустить, хук — нет).
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
import sys
|
||||||
|
|
||||||
|
|
||||||
|
def block(msg: str) -> None:
|
||||||
|
print(msg, file=sys.stderr)
|
||||||
|
sys.exit(2)
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
try:
|
||||||
|
d = json.load(sys.stdin)
|
||||||
|
except (json.JSONDecodeError, ValueError):
|
||||||
|
sys.exit(0) # нет валидного входа — не мешать
|
||||||
|
|
||||||
|
tool = d.get("tool_name", "")
|
||||||
|
ti = d.get("tool_input") or {}
|
||||||
|
|
||||||
|
if tool == "Read":
|
||||||
|
p = ti.get("file_path", "")
|
||||||
|
if re.search(r"\.(docx|xlsx|pptx|pdf|doc|xls)$", p, re.I):
|
||||||
|
block(
|
||||||
|
"БЛОК (LOCAL-FIRST): бинарные документы читать только через "
|
||||||
|
"python3 scripts/markdown_extract.py FILE --json-meta "
|
||||||
|
"(роутер выдаст кеш-путь, срезы и requisites.json). "
|
||||||
|
"Read напрямую для .docx/.pdf/.xlsx/.pptx запрещен."
|
||||||
|
)
|
||||||
|
|
||||||
|
if tool in ("Write", "Edit", "NotebookEdit"):
|
||||||
|
p = ti.get("file_path", "") or ti.get("notebook_path", "")
|
||||||
|
if "/00_intake/" in p:
|
||||||
|
block(
|
||||||
|
"БЛОК: 00_intake/ неприкосновенен — исходники клиента "
|
||||||
|
"не редактировать и не перезаписывать (железное правило)."
|
||||||
|
)
|
||||||
|
|
||||||
|
if tool == "Bash":
|
||||||
|
cmd = ti.get("command", "")
|
||||||
|
if re.search(r"\b(rm|rmdir)\b", cmd) and re.search(r"00_intake|_baselines", cmd):
|
||||||
|
block(
|
||||||
|
"БЛОК: удаление в 00_intake/ или _baselines/ запрещено "
|
||||||
|
"(железное правило). Действительно нужно — только пользователь вручную."
|
||||||
|
)
|
||||||
|
|
||||||
|
sys.exit(0)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
+30
-10
@@ -452,21 +452,41 @@ class DocBuilder:
|
|||||||
Плюс неизменяемый снимок-черновик в `_baselines/` рядом — база «ДО» для
|
Плюс неизменяемый снимок-черновик в `_baselines/` рядом — база «ДО» для
|
||||||
самообучения по правкам доверителя (redline). Снимок = последняя выданная
|
самообучения по правкам доверителя (redline). Снимок = последняя выданная
|
||||||
версия; правки доверителя сравниваются именно с ней.
|
версия; правки доверителя сравниваются именно с ней.
|
||||||
|
|
||||||
|
Guard (урок 14.07.2026): если выданный файл отличается от baseline —
|
||||||
|
его правил доверитель; перезапись вслепую запрещена
|
||||||
|
(обход: THEMIS_FORCE_OVERWRITE=1).
|
||||||
"""
|
"""
|
||||||
self._strip_yo()
|
import filecmp
|
||||||
self.doc.save(path)
|
import os
|
||||||
print(f"Сохранено: {path}")
|
|
||||||
try:
|
|
||||||
import shutil
|
import shutil
|
||||||
from pathlib import Path as _P
|
from pathlib import Path as _P
|
||||||
|
|
||||||
|
self._strip_yo()
|
||||||
p = _P(path)
|
p = _P(path)
|
||||||
# снимок только для реальных документов дел (не тест/tmp), без рекурсии
|
# снимок только для реальных документов дел (не тест/tmp), без рекурсии
|
||||||
if p.parent.name != "_baselines" and ("cases" in p.parts or "03_drafts" in p.parts):
|
is_case_doc = p.parent.name != "_baselines" and ("cases" in p.parts or "03_drafts" in p.parts)
|
||||||
bdir = p.parent / "_baselines"
|
bfile = p.parent / "_baselines" / p.name
|
||||||
bdir.mkdir(exist_ok=True)
|
|
||||||
shutil.copy2(path, bdir / p.name) # перезапись: baseline = свежая версия
|
if (is_case_doc and p.exists() and bfile.exists()
|
||||||
except OSError:
|
and not filecmp.cmp(p, bfile, shallow=False)
|
||||||
pass
|
and os.environ.get("THEMIS_FORCE_OVERWRITE") != "1"):
|
||||||
|
print(f"СТОП, НЕ СОХРАНЕНО: {p} отличается от _baselines/ — "
|
||||||
|
f"вероятны правки доверителя, внесенные напрямую в файл. "
|
||||||
|
f"Сначала redline-разбор («изучи мои правки»), "
|
||||||
|
f"либо повторить с THEMIS_FORCE_OVERWRITE=1.")
|
||||||
|
return
|
||||||
|
|
||||||
|
self.doc.save(path)
|
||||||
|
print(f"Сохранено: {path}")
|
||||||
|
if is_case_doc:
|
||||||
|
try:
|
||||||
|
bfile.parent.mkdir(exist_ok=True)
|
||||||
|
shutil.copy2(path, bfile) # перезапись: baseline = свежая версия
|
||||||
|
except OSError as e:
|
||||||
|
print(f"ВНИМАНИЕ: снимок в _baselines/ не записан ({e}). "
|
||||||
|
f"База «ДО» для redline-разбора устарела — закройте файл "
|
||||||
|
f"в других приложениях и повторите save().")
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
@@ -37,13 +37,28 @@ fi
|
|||||||
COUNT=$(echo "$FILES" | wc -l | xargs)
|
COUNT=$(echo "$FILES" | wc -l | xargs)
|
||||||
echo "$(date '+%Y-%m-%d %H:%M') | INBOX | Найдено файлов: $COUNT" >> "$LOG"
|
echo "$(date '+%Y-%m-%d %H:%M') | INBOX | Найдено файлов: $COUNT" >> "$LOG"
|
||||||
|
|
||||||
|
# Метки времени в помощь группировке (урок 19.07.2026: мультидельный инбокс)
|
||||||
|
FILES_TS=$(echo "$FILES" | while IFS= read -r f; do
|
||||||
|
stat -f '%Sm %N' -t '%Y-%m-%d %H:%M' "$f" 2>/dev/null || echo "????-??-?? ??:?? $f"
|
||||||
|
done)
|
||||||
|
|
||||||
PROMPT="Используй агент inbox-triage. Разложи входящие файлы из папки: $INBOX
|
PROMPT="Используй агент inbox-triage. Разложи входящие файлы из папки: $INBOX
|
||||||
Индекс дел: $CASES/_index.md
|
Индекс дел: $CASES/_index.md
|
||||||
Папка дел: $CASES
|
Папка дел: $CASES
|
||||||
Папка unsorted: $UNSORTED
|
Папка unsorted: $UNSORTED
|
||||||
|
|
||||||
Файлы для обработки:
|
ЖЕСТКИЕ ПРАВИЛА (уроки боевых прогонов, нарушение = авария):
|
||||||
$FILES"
|
1. Инбокс может содержать файлы РАЗНЫХ дел. Сгруппируй по времени поступления
|
||||||
|
(метки ниже, окно ~1 час) и тематике (первая страница через
|
||||||
|
scripts/markdown_extract.py). НЕ переносить весь инбокс в одно дело.
|
||||||
|
2. Переносить только группы, уверенно привязанные к СУЩЕСТВУЮЩЕМУ делу
|
||||||
|
из _index.md. Новое дело в автоматическом режиме НЕ создавать —
|
||||||
|
такие файлы в $UNSORTED + заметка *.note.md рядом с причиной.
|
||||||
|
3. Сомнение в принадлежности → $UNSORTED. Смешивать дела запрещено.
|
||||||
|
4. В 00_intake/ существующих дел только добавлять, ничего не менять.
|
||||||
|
|
||||||
|
Файлы (время поступления · путь):
|
||||||
|
$FILES_TS"
|
||||||
|
|
||||||
"$CLAUDE" --print "$PROMPT" 2>> "$LOG"
|
"$CLAUDE" --print "$PROMPT" 2>> "$LOG"
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,324 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""
|
||||||
|
Универсальный конвертер .md -> .docx через DocBuilder.
|
||||||
|
Использование:
|
||||||
|
python3 scripts/md_to_docx.py cases/.../03_drafts/document.md
|
||||||
|
Сохраняет document.docx рядом с исходным .md.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import re
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||||
|
from scripts.create_docx import DocBuilder, FONT, _set_font
|
||||||
|
from docx.shared import Pt, Cm
|
||||||
|
from docx.enum.text import WD_ALIGN_PARAGRAPH
|
||||||
|
from docx.oxml.ns import qn
|
||||||
|
from docx.oxml import OxmlElement
|
||||||
|
|
||||||
|
|
||||||
|
def strip_markdown_bold(text: str) -> list:
|
||||||
|
"""Превращает строку с **жирным** текстом в список (text, bold)."""
|
||||||
|
parts = []
|
||||||
|
while "**" in text:
|
||||||
|
idx = text.index("**")
|
||||||
|
if idx > 0:
|
||||||
|
parts.append((text[:idx], False))
|
||||||
|
text = text[idx + 2:]
|
||||||
|
if "**" in text:
|
||||||
|
idx = text.index("**")
|
||||||
|
parts.append((text[:idx], True))
|
||||||
|
text = text[idx + 2:]
|
||||||
|
else:
|
||||||
|
parts.append((text, True))
|
||||||
|
text = ""
|
||||||
|
if text:
|
||||||
|
parts.append((text, False))
|
||||||
|
return parts
|
||||||
|
|
||||||
|
|
||||||
|
DOCUMENT_TITLES = {
|
||||||
|
"ВОЗРАЖЕНИЯ", "ВОЗРАЖЕНИЕ", "ЗАЯВЛЕНИЕ", "ИСКОВОЕ ЗАЯВЛЕНИЕ",
|
||||||
|
"ХОДАТАЙСТВО", "ОПРЕДЕЛЕНИЕ", "ПРЕДЛОЖЕНИЕ",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def is_document_heading(line: str) -> bool:
|
||||||
|
"""Определяет, заканчивается ли шапка на данной строке."""
|
||||||
|
stripped = line.strip()
|
||||||
|
if re.match(r"^#{1,4} \S", stripped):
|
||||||
|
return True
|
||||||
|
if stripped in DOCUMENT_TITLES:
|
||||||
|
return True
|
||||||
|
if re.match(r"^[IVXLC]+\.\s", stripped):
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def parse_header(lines: list) -> dict:
|
||||||
|
"""Парсит шапку документа (до первого ---, заголовка или раздела)."""
|
||||||
|
court_name = ""
|
||||||
|
court_route_parts = []
|
||||||
|
case_number = ""
|
||||||
|
parties = []
|
||||||
|
current_party = None
|
||||||
|
|
||||||
|
for line in lines:
|
||||||
|
line = line.rstrip()
|
||||||
|
if not line:
|
||||||
|
if current_party is not None:
|
||||||
|
parties.append(current_party)
|
||||||
|
current_party = None
|
||||||
|
continue
|
||||||
|
|
||||||
|
# суд
|
||||||
|
if line.startswith("В ") and "суд" in line.lower():
|
||||||
|
court_name = line[2:].strip()
|
||||||
|
continue
|
||||||
|
|
||||||
|
# адрес / судья
|
||||||
|
if line.lower().startswith("адрес:") or line.lower().startswith("судья"):
|
||||||
|
court_route_parts.append(line)
|
||||||
|
continue
|
||||||
|
|
||||||
|
# дело
|
||||||
|
if line.lower().startswith("дело №"):
|
||||||
|
case_number = line
|
||||||
|
continue
|
||||||
|
|
||||||
|
# метка стороны (заканчивается двоеточием)
|
||||||
|
if line.endswith(":") and ("истец" in line.lower() or "ответчик" in line.lower() or "третье" in line.lower() or "лицо" in line.lower()):
|
||||||
|
if current_party is not None:
|
||||||
|
parties.append(current_party)
|
||||||
|
current_party = {"label": line, "lines": []}
|
||||||
|
continue
|
||||||
|
|
||||||
|
# строка данных стороны
|
||||||
|
if current_party is not None:
|
||||||
|
clean = line.rstrip(",;").strip()
|
||||||
|
# первая строка блока — имя, делаем жирным
|
||||||
|
is_bold = len(current_party["lines"]) == 0
|
||||||
|
current_party["lines"].append((clean, is_bold))
|
||||||
|
|
||||||
|
if current_party is not None:
|
||||||
|
parties.append(current_party)
|
||||||
|
|
||||||
|
court_route = "\n".join(court_route_parts)
|
||||||
|
return {
|
||||||
|
"court": court_name,
|
||||||
|
"court_route": court_route,
|
||||||
|
"case": case_number,
|
||||||
|
"parties": parties,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def add_table_to_doc(doc, rows: list):
|
||||||
|
"""Добавляет markdown-таблицу в docx с базовым форматированием."""
|
||||||
|
if not rows:
|
||||||
|
return
|
||||||
|
# отфильтровать разделительные строки
|
||||||
|
data_rows = [r for r in rows if not re.match(r"^\|[-:\|\s]+\|$", r.strip())]
|
||||||
|
if not data_rows:
|
||||||
|
return
|
||||||
|
|
||||||
|
cells = [list(map(str.strip, row.strip("|").split("|"))) for row in data_rows]
|
||||||
|
num_cols = max(len(c) for c in cells)
|
||||||
|
table = doc.add_table(rows=len(cells), cols=num_cols)
|
||||||
|
|
||||||
|
# убрать границы
|
||||||
|
tbl = table._tbl
|
||||||
|
tblPr = tbl.find(qn("w:tblPr"))
|
||||||
|
if tblPr is None:
|
||||||
|
tblPr = OxmlElement("w:tblPr")
|
||||||
|
tbl.insert(0, tblPr)
|
||||||
|
tblBorders = OxmlElement("w:tblBorders")
|
||||||
|
for side in ["top", "left", "bottom", "right", "insideH", "insideV"]:
|
||||||
|
el = OxmlElement(f"w:{side}")
|
||||||
|
el.set(qn("w:val"), "none")
|
||||||
|
tblBorders.append(el)
|
||||||
|
tblPr.append(tblBorders)
|
||||||
|
|
||||||
|
# автоширина
|
||||||
|
tblLayout = OxmlElement("w:tblLayout")
|
||||||
|
tblLayout.set(qn("w:type"), "autofit")
|
||||||
|
tblPr.append(tblLayout)
|
||||||
|
|
||||||
|
for i, row_cells in enumerate(cells):
|
||||||
|
for j in range(num_cols):
|
||||||
|
cell = table.rows[i].cells[j]
|
||||||
|
cell.paragraphs[0].clear()
|
||||||
|
cell.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.LEFT
|
||||||
|
text = row_cells[j] if j < len(row_cells) else ""
|
||||||
|
_set_font(cell.paragraphs[0].add_run(text), 12)
|
||||||
|
|
||||||
|
# отступ после таблицы
|
||||||
|
p = doc.add_paragraph()
|
||||||
|
p.paragraph_format.space_after = Pt(6)
|
||||||
|
|
||||||
|
|
||||||
|
def convert(md_path: str):
|
||||||
|
md_file = Path(md_path)
|
||||||
|
out_path = md_file.with_suffix(".docx")
|
||||||
|
|
||||||
|
content = md_file.read_text(encoding="utf-8")
|
||||||
|
lines = content.splitlines()
|
||||||
|
|
||||||
|
# разделить шапку и тело
|
||||||
|
header_lines = []
|
||||||
|
body_lines = []
|
||||||
|
in_header = True
|
||||||
|
for line in lines:
|
||||||
|
if in_header and line.strip() == "---":
|
||||||
|
in_header = False
|
||||||
|
continue
|
||||||
|
if in_header and is_document_heading(line):
|
||||||
|
in_header = False
|
||||||
|
body_lines.append(line)
|
||||||
|
continue
|
||||||
|
if in_header:
|
||||||
|
header_lines.append(line)
|
||||||
|
else:
|
||||||
|
body_lines.append(line)
|
||||||
|
|
||||||
|
header_info = parse_header(header_lines)
|
||||||
|
|
||||||
|
b = DocBuilder()
|
||||||
|
|
||||||
|
# шапка
|
||||||
|
b.add_header_table(
|
||||||
|
court_name=header_info["court"] or "Суд",
|
||||||
|
court_route=header_info["court_route"],
|
||||||
|
parties=header_info["parties"],
|
||||||
|
case_number=header_info["case"],
|
||||||
|
)
|
||||||
|
b.add_empty()
|
||||||
|
|
||||||
|
# тело
|
||||||
|
i = 0
|
||||||
|
state = "body" # body | proshyu | appendices
|
||||||
|
|
||||||
|
while i < len(body_lines):
|
||||||
|
line = body_lines[i]
|
||||||
|
stripped = line.strip()
|
||||||
|
|
||||||
|
# пустая строка
|
||||||
|
if not stripped:
|
||||||
|
i += 1
|
||||||
|
continue
|
||||||
|
|
||||||
|
# горизонтальная черта
|
||||||
|
if stripped == "---":
|
||||||
|
b.add_empty()
|
||||||
|
i += 1
|
||||||
|
continue
|
||||||
|
|
||||||
|
# заголовок документа (# )
|
||||||
|
if re.match(r"^# ", line):
|
||||||
|
b.add_title(stripped[2:])
|
||||||
|
i += 1
|
||||||
|
continue
|
||||||
|
|
||||||
|
# документный заголовок без решетки (ВОЗРАЖЕНИЯ, ЗАЯВЛЕНИЕ и т.д.)
|
||||||
|
if stripped in DOCUMENT_TITLES:
|
||||||
|
b.add_title(stripped)
|
||||||
|
i += 1
|
||||||
|
# следующие непустые строки до разделителя — подзаголовки
|
||||||
|
while i < len(body_lines) and body_lines[i].strip() and not is_document_heading(body_lines[i]):
|
||||||
|
b.add_subtitle(body_lines[i].strip())
|
||||||
|
i += 1
|
||||||
|
continue
|
||||||
|
|
||||||
|
# подзаголовок (## )
|
||||||
|
if re.match(r"^## ", line):
|
||||||
|
b.add_subtitle(stripped[3:])
|
||||||
|
i += 1
|
||||||
|
continue
|
||||||
|
|
||||||
|
# секция (### )
|
||||||
|
if re.match(r"^### ", line):
|
||||||
|
b.add_section(stripped[4:])
|
||||||
|
i += 1
|
||||||
|
continue
|
||||||
|
|
||||||
|
# подсекция (#### )
|
||||||
|
if re.match(r"^#### ", line):
|
||||||
|
b.add_subsection(stripped[5:])
|
||||||
|
i += 1
|
||||||
|
continue
|
||||||
|
|
||||||
|
# таблица
|
||||||
|
if stripped.startswith("|"):
|
||||||
|
table_rows = []
|
||||||
|
while i < len(body_lines) and body_lines[i].strip().startswith("|"):
|
||||||
|
table_rows.append(body_lines[i])
|
||||||
|
i += 1
|
||||||
|
add_table_to_doc(b.doc, table_rows)
|
||||||
|
continue
|
||||||
|
|
||||||
|
# маркированный список
|
||||||
|
if stripped.startswith("- "):
|
||||||
|
item = stripped[2:]
|
||||||
|
b.add_bullet(item)
|
||||||
|
i += 1
|
||||||
|
continue
|
||||||
|
|
||||||
|
# ПРОСИМ / ПРОШУ
|
||||||
|
if stripped in ("ПРОСИМ:", "ПРОШУ:"):
|
||||||
|
b.add_proshyu()
|
||||||
|
state = "proshyu"
|
||||||
|
i += 1
|
||||||
|
continue
|
||||||
|
|
||||||
|
# ПРИЛОЖЕНИЯ
|
||||||
|
if stripped == "ПРИЛОЖЕНИЯ:":
|
||||||
|
b.add_appendices()
|
||||||
|
state = "appendices"
|
||||||
|
i += 1
|
||||||
|
continue
|
||||||
|
|
||||||
|
# просительная часть: пункты вида "1. ..."
|
||||||
|
if state == "proshyu" and re.match(r"^\d+\.\s", stripped):
|
||||||
|
b.add_request_item(stripped)
|
||||||
|
i += 1
|
||||||
|
continue
|
||||||
|
|
||||||
|
# приложения: пункты вида "1. ..."
|
||||||
|
if state == "appendices" and re.match(r"^\d+\.\s", stripped):
|
||||||
|
b.add_appendix_item(stripped)
|
||||||
|
i += 1
|
||||||
|
continue
|
||||||
|
|
||||||
|
# подпись: строка с ролью и длинным подчеркиванием
|
||||||
|
if "____________" in stripped or "________________" in stripped:
|
||||||
|
# роль — предыдущая непустая строка, если есть
|
||||||
|
role = ""
|
||||||
|
name = stripped
|
||||||
|
if i > 0:
|
||||||
|
prev = body_lines[i - 1].strip()
|
||||||
|
if prev and not prev.startswith("#") and prev not in ("ПРОСИМ:", "ПРОШУ:", "ПРИЛОЖЕНИЯ:"):
|
||||||
|
role = prev
|
||||||
|
# дата — следующая непустая строка
|
||||||
|
date_str = ""
|
||||||
|
j = i + 1
|
||||||
|
while j < len(body_lines) and not body_lines[j].strip():
|
||||||
|
j += 1
|
||||||
|
if j < len(body_lines):
|
||||||
|
date_str = body_lines[j].strip()
|
||||||
|
b.add_signature_table(role=role, name=name, date=date_str)
|
||||||
|
i = j + 1 if date_str else i + 1
|
||||||
|
continue
|
||||||
|
|
||||||
|
# обычный абзац
|
||||||
|
b.add_body(strip_markdown_bold(stripped))
|
||||||
|
i += 1
|
||||||
|
|
||||||
|
b.save(str(out_path))
|
||||||
|
print(f"✓ Создано: {out_path}")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
if len(sys.argv) < 2:
|
||||||
|
print("Использование: python3 scripts/md_to_docx.py <путь к .md>")
|
||||||
|
sys.exit(1)
|
||||||
|
convert(sys.argv[1])
|
||||||
@@ -0,0 +1,219 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""
|
||||||
|
Универсальный конвертер markdown -> docx для судебных документов.
|
||||||
|
Поддерживает: заголовки, параграфы, маркированные списки, таблицы,
|
||||||
|
жирный текст (**text**).
|
||||||
|
"""
|
||||||
|
|
||||||
|
import re
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
from docx import Document
|
||||||
|
from docx.shared import Pt, Cm
|
||||||
|
from docx.enum.text import WD_ALIGN_PARAGRAPH
|
||||||
|
from docx.oxml.ns import qn
|
||||||
|
from docx.oxml import OxmlElement
|
||||||
|
|
||||||
|
FONT = "Times New Roman"
|
||||||
|
|
||||||
|
|
||||||
|
def _set_font(run, size_pt, bold=False):
|
||||||
|
run.font.name = FONT
|
||||||
|
run.font.size = Pt(size_pt)
|
||||||
|
run.font.bold = bold
|
||||||
|
|
||||||
|
|
||||||
|
def _strip_yo(doc):
|
||||||
|
for t in doc.element.iter(qn("w:t")):
|
||||||
|
if t.text and ("ё" in t.text or "Ё" in t.text):
|
||||||
|
t.text = t.text.replace("ё", "е").replace("Ё", "Е")
|
||||||
|
|
||||||
|
|
||||||
|
def _add_table(doc, lines):
|
||||||
|
"""lines - строки markdown таблицы (без разделителя)."""
|
||||||
|
rows = []
|
||||||
|
for line in lines:
|
||||||
|
if line.strip().startswith("|"):
|
||||||
|
cells = [c.strip() for c in line.strip()[1:].split("|")]
|
||||||
|
if cells and not cells[-1].strip():
|
||||||
|
cells = cells[:-1]
|
||||||
|
rows.append(cells)
|
||||||
|
|
||||||
|
if not rows:
|
||||||
|
return
|
||||||
|
|
||||||
|
# отфильтровать пустые строки
|
||||||
|
rows = [r for r in rows if any(c.strip() for c in r)]
|
||||||
|
if not rows:
|
||||||
|
return
|
||||||
|
|
||||||
|
n_cols = max(len(r) for r in rows)
|
||||||
|
table = doc.add_table(rows=len(rows), cols=n_cols)
|
||||||
|
|
||||||
|
# убрать границы
|
||||||
|
tbl = table._tbl
|
||||||
|
tblPr = tbl.find(qn("w:tblPr"))
|
||||||
|
if tblPr is None:
|
||||||
|
tblPr = OxmlElement("w:tblPr")
|
||||||
|
tbl.insert(0, tblPr)
|
||||||
|
tblBorders = OxmlElement("w:tblBorders")
|
||||||
|
for side in ["top", "left", "bottom", "right", "insideH", "insideV"]:
|
||||||
|
el = OxmlElement(f"w:{side}")
|
||||||
|
el.set(qn("w:val"), "none")
|
||||||
|
tblBorders.append(el)
|
||||||
|
tblPr.append(tblBorders)
|
||||||
|
|
||||||
|
# автоподбор ширины
|
||||||
|
tblPr.append(OxmlElement("w:tblLayout"))
|
||||||
|
tblPr.find(qn("w:tblLayout")).set(qn("w:type"), "autofit")
|
||||||
|
|
||||||
|
for i, row_data in enumerate(rows):
|
||||||
|
row = table.rows[i]
|
||||||
|
for j in range(n_cols):
|
||||||
|
cell = row.cells[j]
|
||||||
|
cell.text = ""
|
||||||
|
p = cell.paragraphs[0]
|
||||||
|
p.alignment = WD_ALIGN_PARAGRAPH.LEFT
|
||||||
|
text = row_data[j] if j < len(row_data) else ""
|
||||||
|
# парсим жирный текст
|
||||||
|
parts = re.split(r"\*\*(.*?)\*\*", text)
|
||||||
|
for k, part in enumerate(parts):
|
||||||
|
if not part:
|
||||||
|
continue
|
||||||
|
bold = (k % 2 == 1)
|
||||||
|
_set_font(p.add_run(part), 11, bold=bold)
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_bold_text(text):
|
||||||
|
parts = re.split(r"\*\*(.*?)\*\*", text)
|
||||||
|
result = []
|
||||||
|
for k, part in enumerate(parts):
|
||||||
|
if not part:
|
||||||
|
continue
|
||||||
|
result.append((part, k % 2 == 1))
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def md_to_docx(md_path, out_path):
|
||||||
|
md_path = Path(md_path)
|
||||||
|
out_path = Path(out_path)
|
||||||
|
|
||||||
|
text = md_path.read_text(encoding="utf-8")
|
||||||
|
lines = text.splitlines()
|
||||||
|
|
||||||
|
doc = Document()
|
||||||
|
section = doc.sections[0]
|
||||||
|
section.page_width = Cm(21)
|
||||||
|
section.page_height = Cm(29.7)
|
||||||
|
section.top_margin = Cm(2)
|
||||||
|
section.bottom_margin = Cm(2)
|
||||||
|
section.left_margin = Cm(3)
|
||||||
|
section.right_margin = Cm(1.5)
|
||||||
|
|
||||||
|
# удалить дефолтный пустой параграф
|
||||||
|
for p in doc.paragraphs:
|
||||||
|
p._element.getparent().remove(p._element)
|
||||||
|
|
||||||
|
i = 0
|
||||||
|
header_lines = []
|
||||||
|
in_header = True
|
||||||
|
|
||||||
|
while i < len(lines):
|
||||||
|
line = lines[i]
|
||||||
|
|
||||||
|
# разделитель шапки
|
||||||
|
if in_header and line.strip() == "---":
|
||||||
|
in_header = False
|
||||||
|
i += 1
|
||||||
|
continue
|
||||||
|
|
||||||
|
# заголовок первого уровня - основной заголовок документа
|
||||||
|
if re.match(r"^# ", line):
|
||||||
|
in_header = False
|
||||||
|
p = doc.add_paragraph()
|
||||||
|
p.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
||||||
|
p.paragraph_format.space_before = Pt(6)
|
||||||
|
p.paragraph_format.space_after = Pt(4)
|
||||||
|
_set_font(p.add_run(line[2:].strip().upper()), 14, bold=True)
|
||||||
|
i += 1
|
||||||
|
continue
|
||||||
|
|
||||||
|
# подзаголовок второго уровня
|
||||||
|
if re.match(r"^## ", line):
|
||||||
|
in_header = False
|
||||||
|
p = doc.add_paragraph()
|
||||||
|
p.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
||||||
|
p.paragraph_format.space_after = Pt(4)
|
||||||
|
_set_font(p.add_run(line[3:].strip()), 13, bold=True)
|
||||||
|
i += 1
|
||||||
|
continue
|
||||||
|
|
||||||
|
# раздел
|
||||||
|
if re.match(r"^### ", line):
|
||||||
|
in_header = False
|
||||||
|
p = doc.add_paragraph()
|
||||||
|
p.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
|
||||||
|
p.paragraph_format.space_before = Pt(12)
|
||||||
|
p.paragraph_format.space_after = Pt(6)
|
||||||
|
_set_font(p.add_run(line[4:].strip()), 12, bold=True)
|
||||||
|
i += 1
|
||||||
|
continue
|
||||||
|
|
||||||
|
# таблица
|
||||||
|
if line.strip().startswith("|"):
|
||||||
|
in_header = False
|
||||||
|
table_lines = []
|
||||||
|
while i < len(lines) and lines[i].strip().startswith("|"):
|
||||||
|
table_lines.append(lines[i])
|
||||||
|
i += 1
|
||||||
|
# пропустить разделительную строку |---|---|
|
||||||
|
table_lines = [
|
||||||
|
l for l in table_lines
|
||||||
|
if not re.match(r"^\|[-:\s|]+\|$", l.strip())
|
||||||
|
]
|
||||||
|
_add_table(doc, table_lines)
|
||||||
|
continue
|
||||||
|
|
||||||
|
# маркированный список
|
||||||
|
if line.strip().startswith("- "):
|
||||||
|
in_header = False
|
||||||
|
p = doc.add_paragraph(style="List Bullet")
|
||||||
|
p.paragraph_format.space_before = Pt(2)
|
||||||
|
p.paragraph_format.space_after = Pt(2)
|
||||||
|
p.paragraph_format.left_indent = Cm(1.5)
|
||||||
|
item_text = line.strip()[2:]
|
||||||
|
for part, bold in _parse_bold_text(item_text):
|
||||||
|
_set_font(p.add_run(part), 12, bold=bold)
|
||||||
|
i += 1
|
||||||
|
continue
|
||||||
|
|
||||||
|
# пустая строка
|
||||||
|
if not line.strip():
|
||||||
|
if in_header:
|
||||||
|
pass # просто пропускаем в шапке
|
||||||
|
i += 1
|
||||||
|
continue
|
||||||
|
|
||||||
|
# обычный параграф
|
||||||
|
in_header = False
|
||||||
|
p = doc.add_paragraph()
|
||||||
|
p.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
|
||||||
|
p.paragraph_format.space_after = Pt(6)
|
||||||
|
if header_lines:
|
||||||
|
# это все еще может быть шапка - левое выравнивание
|
||||||
|
p.alignment = WD_ALIGN_PARAGRAPH.LEFT
|
||||||
|
|
||||||
|
for part, bold in _parse_bold_text(line.strip()):
|
||||||
|
_set_font(p.add_run(part), 12, bold=bold)
|
||||||
|
i += 1
|
||||||
|
|
||||||
|
_strip_yo(doc)
|
||||||
|
doc.save(out_path)
|
||||||
|
print(f"Создано: {out_path}")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
if len(sys.argv) < 3:
|
||||||
|
print("Использование: python scripts/md_to_docx_universal.py input.md output.docx")
|
||||||
|
sys.exit(1)
|
||||||
|
md_to_docx(sys.argv[1], sys.argv[2])
|
||||||
@@ -0,0 +1,152 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""Parse T-Bank funds movement statement from markitdown cache."""
|
||||||
|
|
||||||
|
import re
|
||||||
|
from decimal import Decimal
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
def parse_amount(s: str) -> Decimal:
|
||||||
|
s_clean = s.replace('₽', '').replace(' ', '').replace(',', '.').replace('+', '').replace('−', '-')
|
||||||
|
return Decimal(s_clean)
|
||||||
|
|
||||||
|
|
||||||
|
def is_date(s: str) -> bool:
|
||||||
|
return bool(re.match(r'^\d{2}\.\d{2}\.\d{4}$', s))
|
||||||
|
|
||||||
|
|
||||||
|
def clean_desc(s: str) -> str:
|
||||||
|
s = re.sub(r'\s+\d{4}$', '', s)
|
||||||
|
s = re.sub(r'\bоперации\s+карты\b', '', s)
|
||||||
|
s = re.sub(r'\s+', ' ', s)
|
||||||
|
return s.strip()
|
||||||
|
|
||||||
|
|
||||||
|
def split_plain_line(line: str) -> list[str]:
|
||||||
|
"""Split a plain-text line containing multiple operations into individual strings."""
|
||||||
|
amount_re = r'[+-]?\s*[\d\s]+[\,\.]\d{2}'
|
||||||
|
op_start_re = re.compile(r'\d{2}\.\d{2}\.\d{4}\s+\d{2}\.\d{2}\.\d{4}\s+' + amount_re + r'\s*₽\s+' + amount_re + r'\s*₽')
|
||||||
|
starts = [m.start() for m in op_start_re.finditer(line)]
|
||||||
|
if not starts:
|
||||||
|
return [line] if line.strip() else []
|
||||||
|
parts = []
|
||||||
|
for i in range(len(starts)):
|
||||||
|
start = starts[i]
|
||||||
|
end = starts[i + 1] if i + 1 < len(starts) else len(line)
|
||||||
|
parts.append(line[start:end].strip())
|
||||||
|
return parts
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_statement(path: str) -> list[str]:
|
||||||
|
"""Return a list of markdown-style rows ready for uniform parsing."""
|
||||||
|
raw_lines = Path(path).read_text(encoding='utf-8').splitlines()
|
||||||
|
normalized: list[str] = []
|
||||||
|
|
||||||
|
for line in raw_lines:
|
||||||
|
s = line.strip()
|
||||||
|
if not s:
|
||||||
|
continue
|
||||||
|
if s.startswith('АО «ТБанк»') or s.startswith('БИК ') or s.startswith('С уважением') or s.startswith('Руководитель'):
|
||||||
|
continue
|
||||||
|
if re.match(r'^\d+$', s):
|
||||||
|
continue
|
||||||
|
if any(h in s for h in ['Дата и время', 'Дата Сумма в валюте', 'Сумма операции Описание Номер', 'операции списания', 'операции списания операции']):
|
||||||
|
continue
|
||||||
|
if re.match(r'^\|?\s*[-:]+\s*\|', s):
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Phone number lines pass through unchanged (will be handled later)
|
||||||
|
if re.match(r'^\+7\d{10}$', s):
|
||||||
|
normalized.append('__PHONE__' + s)
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Plain text line that contains operations -> convert each to markdown row
|
||||||
|
if not s.startswith('|'):
|
||||||
|
if re.match(r'^\d{2}\.\d{2}\.\d{4}\s+\d{2}\.\d{2}\.\d{4}\s+[+-]?\s*[\d\s]+[\,\.]\d{2}\s*₽', s):
|
||||||
|
amount_re = r'([+-]?\s*[\d\s]+[\,\.]\d{2})\s*₽'
|
||||||
|
op_re = re.compile(
|
||||||
|
r'^(\d{2}\.\d{2}\.\d{4})\s+(\d{2}\.\d{2}\.\d{4})\s+' + amount_re + r'\s+' + amount_re + r'\s+(.*)$'
|
||||||
|
)
|
||||||
|
for op_str in split_plain_line(s):
|
||||||
|
m = op_re.match(op_str)
|
||||||
|
if not m:
|
||||||
|
continue
|
||||||
|
op_date, debit_date, amount1, amount2, desc = m.groups()
|
||||||
|
row = f"| {op_date} | {debit_date} | {amount1} ₽ | {amount2} ₽ | {clean_desc(desc)} | |"
|
||||||
|
normalized.append(row)
|
||||||
|
continue
|
||||||
|
# Non-operation plain text continuation
|
||||||
|
normalized.append('__CONT__' + s)
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Markdown table line passes through
|
||||||
|
normalized.append(s)
|
||||||
|
|
||||||
|
return normalized
|
||||||
|
|
||||||
|
|
||||||
|
def parse_statement(path: str) -> list[dict]:
|
||||||
|
lines = normalize_statement(path)
|
||||||
|
operations: list[dict] = []
|
||||||
|
current: dict | None = None
|
||||||
|
|
||||||
|
def flush_current():
|
||||||
|
nonlocal current
|
||||||
|
if current:
|
||||||
|
operations.append(current)
|
||||||
|
current = None
|
||||||
|
|
||||||
|
for s in lines:
|
||||||
|
if s.startswith('__PHONE__'):
|
||||||
|
phone = s[len('__PHONE__'):]
|
||||||
|
if current:
|
||||||
|
current['phone'] = phone
|
||||||
|
continue
|
||||||
|
|
||||||
|
if s.startswith('__CONT__'):
|
||||||
|
text = s[len('__CONT__'):]
|
||||||
|
if current:
|
||||||
|
current['description'] = (current['description'] + ' ' + text).strip()
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Markdown table line
|
||||||
|
cells = [c.strip() for c in s[1:-1].split('|')]
|
||||||
|
while len(cells) < 6:
|
||||||
|
cells.append('')
|
||||||
|
op_date, debit_date, amount1, amount2, desc, card = cells[:6]
|
||||||
|
|
||||||
|
amount_str = amount1 or amount2
|
||||||
|
has_amount = amount_str and '₽' in amount_str
|
||||||
|
|
||||||
|
if has_amount:
|
||||||
|
flush_current()
|
||||||
|
current = {
|
||||||
|
'op_date': op_date if is_date(op_date) else '',
|
||||||
|
'debit_date': debit_date if is_date(debit_date) else '',
|
||||||
|
'amount': parse_amount(amount_str),
|
||||||
|
'description': clean_desc(desc.strip()),
|
||||||
|
'phone': None,
|
||||||
|
'card': card.strip()
|
||||||
|
}
|
||||||
|
elif current:
|
||||||
|
if is_date(op_date) and current['op_date'] == '':
|
||||||
|
current['op_date'] = op_date
|
||||||
|
current['debit_date'] = debit_date
|
||||||
|
if desc:
|
||||||
|
current['description'] = (current['description'] + ' ' + clean_desc(desc)).strip()
|
||||||
|
if card and not re.match(r'^\d{4}$', card):
|
||||||
|
current['description'] = (current['description'] + ' ' + clean_desc(card)).strip()
|
||||||
|
|
||||||
|
flush_current()
|
||||||
|
return operations
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
import sys
|
||||||
|
ops = parse_statement(sys.argv[1])
|
||||||
|
income = sum(o['amount'] for o in ops if o['amount'] > 0)
|
||||||
|
expense = sum(o['amount'] for o in ops if o['amount'] < 0)
|
||||||
|
print(f'Total operations: {len(ops)}')
|
||||||
|
print(f'Income: {income}')
|
||||||
|
print(f'Expense: {expense}')
|
||||||
Reference in New Issue
Block a user