feat: add resumable local OpenSearch loading

This commit is contained in:
agent committed 2026-08-14 17:24:35 +03:00
1 parent dddb07f393
commit 8e3bfaa9c4
18 files changed
+311 -62

No files matched your search

+4 -4
View File
@@ -10,15 +10,15 @@ Telegram-бот — только часть рабочего окружения
## Текущее состояние
Сейчас реализованы Telegram-бот-секретарь версии `0.2.2` и backend версии
`0.3.0`: возобновляемая выгрузка, нормализация и подготовка индекса документов
`0.4.1`: возобновляемая загрузка индекса документов Министерства юстиции
ЦБД Минюста КР.
| Компонент | Версия | Состояние |
|---|---:|---|
| Telegram-бот | `0.2.2` | на Synology работает `0.2.1`; обновление после слияния |
| Backend | `0.3.0` | реализованы выгрузка, нормализация и экспорт для OpenSearch |
| Backend | `0.4.1` | добавлено продолжение прерванной Bulk-загрузки |
| Frontend | — | ещё не создан |
| Сбор и обработка правовых данных | `0.3.0` | добавлены mapping и Bulk NDJSON для OpenSearch |
| Сбор и обработка правовых данных | `0.4.1` | добавлено продолжение загрузки существующего индекса |
| RAG и база знаний | — | ещё не созданы |
## Структура репозитория
@@ -59,4 +59,4 @@ python3 -m unittest discover -s tools/telegram-bot -v
---
Акылдаш · Telegram-бот v0.2.2 · Backend v0.3.0 · Frontend — не создан
Акылдаш · Telegram-бот v0.2.2 · Backend v0.4.1 · Frontend — не создан
+40 -5
View File
@@ -1,6 +1,6 @@
# Backend Акылдаш
Версия: `0.3.0`
Версия: `0.4.1`
Первая backend-область проекта — загрузка правовых документов из официального
Open Data API ЦБД Минюста Кыргызской Республики. Код расположен в
@@ -114,10 +114,45 @@ python3 backend/search/minjust_opensearch.py
По умолчанию создаётся `data/opensearch/minjust-fragments.ndjson`. Экспорт
атомарный и детерминированный; для проверки можно передать `--limit 1`.
Полный файл может быть большим, поэтому перед запуском нужно проверить
свободное место. Загружать данные следует в новый версионный индекс и после
проверки переключать alias, чтобы удалённые фрагменты не оставались в поиске.
Для прямой загрузки без большого промежуточного файла используется `--url`:
```bash
python3 backend/search/minjust_opensearch.py \
--url http://127.0.0.1:9200 \
--index akyldash-fragments-dev-v1 \
--limit 1
```
Запросы Bulk API ограничены 25 МБ и не разрывают пару action/source. Для
полного прохода убрать `--limit` и выбрать новое имя версионного индекса.
После проверки production-индекса следует переключать alias, чтобы удалённые
фрагменты не оставались в поиске.
Прерванную загрузку можно продолжить с последнего документа; этот документ
безопасно перезаписывается по детерминированным ID:
```bash
python3 backend/search/minjust_opensearch.py \
--url http://127.0.0.1:9200 \
--index akyldash-fragments-v1 \
--resume --start-at 207670
```
## Локальный OpenSearch
Стенд использует один узел OpenSearch без Dashboards, устанавливает
`analysis-icu`, выделяет JVM 8 ГБ и доступен только на `127.0.0.1:9200`.
Индекс хранится в `data/opensearch-node` на диске проекта.
```bash
sudo sysctl -w vm.max_map_count=262144
docker compose -f deploy/local-opensearch/compose.yaml up -d --build
curl http://127.0.0.1:9200/_cluster/health
```
Security plugin отключён только для локальной разработки; этот compose нельзя
публиковать в сеть или использовать в production.
---
Акылдаш · Backend v0.3.0 · Frontend — не создан
Акылдаш · Backend v0.4.1 · Frontend — не создан
+1 -1
View File
@@ -21,7 +21,7 @@ from datetime import datetime, timezone
from pathlib import Path
from typing import Callable, Iterable
APP_VERSION = "0.3.0"
APP_VERSION = "0.4.1"
API_BASE_URL = "https://cbd.minjust.gov.kg/api/v1/OpenData/"
LANGUAGES = {"Rus": "ru", "Kyr": "ky"}
IMAGE_LANGUAGES = {"Russian": "ru", "Kyrgyz": "ky"}
+1 -1
View File
@@ -23,7 +23,7 @@ from pathlib import Path
from typing import Callable
from urllib.parse import urlsplit
APP_VERSION = "0.3.0"
APP_VERSION = "0.4.1"
SCHEMA_VERSION = "1"
NORMALIZER_VERSION = "1.0.0"
LANGUAGES = ("ru", "ky")
@@ -1,4 +1,11 @@
{
"settings": {
"index": {
"number_of_shards": 1,
"number_of_replicas": 0,
"refresh_interval": "30s"
}
},
"mappings": {
"dynamic": "strict",
"properties": {
+152 -34
View File
@@ -8,18 +8,29 @@ import json
import os
import sqlite3
import tempfile
import time
import urllib.parse
import urllib.request
from pathlib import Path
from typing import Iterator
APP_VERSION = "0.3.0"
APP_VERSION = "0.4.1"
LANGUAGES = {"ru", "ky"}
DEFAULT_MAPPING = Path(__file__).with_name("minjust-fragments-index.json")
def read_json(path: Path):
def reject_constant(value: str):
raise ValueError(f"Invalid JSON constant: {value}")
with path.open(encoding="utf-8") as source:
return json.load(source, parse_constant=reject_constant)
for attempt in range(3):
try:
with path.open(encoding="utf-8") as source:
return json.load(source, parse_constant=reject_constant)
except (OSError, UnicodeError, json.JSONDecodeError) as error:
if attempt == 2:
raise ValueError(f"Cannot read JSON {path}: {error}") from error
time.sleep(0.1)
def localized(value: object, language: str):
@@ -73,49 +84,131 @@ def search_document(document: dict, fragment: dict, expected: tuple[str, str, st
return {key: value for key, value in result.items() if value is not None}
def document_codes(input_root: Path, limit: int | None = None, start_at: str | None = None) -> list[str]:
connection = sqlite3.connect(f"file:{input_root / 'manifest.sqlite3'}?mode=ro", uri=True)
try:
query = "SELECT code FROM documents WHERE state = 'success'"
parameters: list[str | int] = []
if start_at is not None:
found = connection.execute(
"SELECT 1 FROM documents WHERE state = 'success' AND code = ?",
(start_at,),
).fetchone()
if found is None:
raise ValueError(f"Resume document not found: {start_at}")
query += " AND CAST(code AS INTEGER) >= CAST(? AS INTEGER)"
parameters.append(start_at)
query += " ORDER BY CAST(code AS INTEGER), code"
if limit is not None:
query += " LIMIT ?"
parameters.append(limit)
return [str(code) for (code,) in connection.execute(query, parameters)]
finally:
connection.close()
def bulk_pairs(
input_root: Path,
index: str,
limit: int | None = None,
start_at: str | None = None,
) -> Iterator[tuple[str, bytes]]:
document_root = input_root / "documents"
if not document_root.is_dir():
raise FileNotFoundError(f"Document directory not found: {document_root}")
for code in document_codes(input_root, limit, start_at):
directory = document_root / code
document = read_json(directory / "document.json")
if document.get("source_code") != directory.name:
raise ValueError(f"Document identity does not match its path: {directory}")
for fragment_path in sorted(directory.glob("editions/*/*/fragments.json")):
edition_code, language = fragment_path.parts[-3:-1]
values = read_json(fragment_path)
if not isinstance(values, list):
raise ValueError(f"Fragments must be a list: {fragment_path}")
for position, fragment in enumerate(values, 1):
source = search_document(document, fragment, (directory.name, edition_code, language, position))
action = json.dumps({"index": {"_index": index, "_id": fragment["id"]}}, ensure_ascii=False, allow_nan=False)
body = json.dumps(source, ensure_ascii=False, allow_nan=False)
yield directory.name, f"{action}\n{body}\n".encode()
def document_count(input_root: Path, limit: int | None, start_at: str | None = None) -> int:
return len(document_codes(input_root, limit, start_at))
def bulk_batches(pairs: Iterator[tuple[str, bytes]], maximum_bytes: int) -> Iterator[tuple[set[str], bytes]]:
batch = bytearray()
documents: set[str] = set()
for code, pair in pairs:
if len(pair) > maximum_bytes:
raise ValueError(f"One Bulk pair exceeds the {maximum_bytes}-byte batch limit")
if batch and len(batch) + len(pair) > maximum_bytes:
yield documents, bytes(batch)
batch.clear()
documents = set()
documents.add(code)
batch.extend(pair)
if batch:
yield documents, bytes(batch)
def export_bulk(input_root: Path, output: Path, index: str, limit: int | None = None) -> tuple[int, int]:
source = input_root.resolve()
destination = output.resolve()
if destination == source or destination.is_relative_to(source):
raise ValueError("--output must not be inside --input")
document_root = input_root / "documents"
if not document_root.is_dir():
raise FileNotFoundError(f"Document directory not found: {document_root}")
connection = sqlite3.connect(f"file:{input_root / 'manifest.sqlite3'}?mode=ro", uri=True)
query = "SELECT code FROM documents WHERE state = 'success' ORDER BY CAST(code AS INTEGER), code"
parameters: tuple[int, ...] = ()
if limit is not None:
query += " LIMIT ?"
parameters = (limit,)
output.parent.mkdir(parents=True, exist_ok=True)
documents = fragments = 0
with tempfile.NamedTemporaryFile("w", encoding="utf-8", dir=output.parent, delete=False) as target:
fragments = 0
with tempfile.NamedTemporaryFile("wb", dir=output.parent, delete=False) as target:
temporary = Path(target.name)
try:
for (code,) in connection.execute(query, parameters):
directory = document_root / str(code)
document = read_json(directory / "document.json")
if document.get("source_code") != directory.name:
raise ValueError(f"Document identity does not match its path: {directory}")
documents += 1
for fragment_path in sorted(directory.glob("editions/*/*/fragments.json")):
edition_code, language = fragment_path.parts[-3:-1]
values = read_json(fragment_path)
if not isinstance(values, list):
raise ValueError(f"Fragments must be a list: {fragment_path}")
for position, fragment in enumerate(values, 1):
source = search_document(document, fragment, (directory.name, edition_code, language, position))
target.write(json.dumps({"index": {"_index": index, "_id": fragment["id"]}}, ensure_ascii=False, allow_nan=False) + "\n")
target.write(json.dumps(source, ensure_ascii=False, allow_nan=False) + "\n")
fragments += 1
for code, pair in bulk_pairs(input_root, index, limit):
target.write(pair)
fragments += 1
target.flush()
os.fsync(target.fileno())
os.replace(temporary, output)
except BaseException:
temporary.unlink(missing_ok=True)
raise
finally:
connection.close()
return document_count(input_root, limit), fragments
def request_json(url: str, method: str, body: bytes | None, content_type: str) -> dict:
request = urllib.request.Request(url, data=body, method=method, headers={"Content-Type": content_type})
with urllib.request.urlopen(request, timeout=120) as response:
return json.load(response)
def load_bulk(
input_root: Path,
url: str,
index: str,
mapping: Path = DEFAULT_MAPPING,
maximum_bytes: int = 25 * 1024 * 1024,
limit: int | None = None,
resume: bool = False,
start_at: str | None = None,
) -> tuple[int, int]:
base = url.rstrip("/")
documents = document_count(input_root, limit, start_at)
index_url = f"{base}/{urllib.parse.quote(index, safe='')}"
if resume:
request_json(index_url, "GET", None, "application/json")
else:
request_json(index_url, "PUT", mapping.read_bytes(), "application/json")
fragments = 0
for _, batch in bulk_batches(bulk_pairs(input_root, index, limit, start_at), maximum_bytes):
result = request_json(f"{base}/_bulk", "POST", batch, "application/x-ndjson")
expected = batch.count(b"\n") // 2
items = result.get("items", [])
if result.get("errors"):
failures = [item for item in result.get("items", []) if item.get("index", {}).get("error")]
raise RuntimeError(f"OpenSearch Bulk API failed for {len(failures)} item(s)")
if len(items) != expected:
raise RuntimeError(f"OpenSearch Bulk API returned {len(items)} of {expected} item result(s)")
fragments += len(items)
return documents, fragments
@@ -125,12 +218,37 @@ def main() -> int:
parser.add_argument("--output", type=Path, default=Path("data/opensearch/minjust-fragments.ndjson"))
parser.add_argument("--index", default="akyldash-fragments-v1")
parser.add_argument("--limit", type=int)
parser.add_argument("--url", help="create the index and stream bounded Bulk requests instead of writing a file")
parser.add_argument("--mapping", type=Path, default=DEFAULT_MAPPING)
parser.add_argument("--batch-mb", type=int, default=25)
parser.add_argument("--resume", action="store_true", help="load into an existing index")
parser.add_argument("--start-at", help="resume at this document code, reindexing that document safely")
parser.add_argument("--version", action="version", version=APP_VERSION)
arguments = parser.parse_args()
if arguments.limit is not None and arguments.limit <= 0:
raise SystemExit("--limit must be greater than zero")
documents, fragments = export_bulk(arguments.input, arguments.output, arguments.index, arguments.limit)
print(f"documents={documents} fragments={fragments} output={arguments.output}\nAkyldash Backend v{APP_VERSION} · Frontend — not created")
if arguments.batch_mb <= 0:
raise SystemExit("--batch-mb must be greater than zero")
if arguments.resume and not arguments.url:
raise SystemExit("--resume requires --url")
if arguments.start_at and not arguments.resume:
raise SystemExit("--start-at requires --resume")
if arguments.url:
documents, fragments = load_bulk(
arguments.input,
arguments.url,
arguments.index,
arguments.mapping,
arguments.batch_mb * 1024 * 1024,
arguments.limit,
arguments.resume,
arguments.start_at,
)
destination = arguments.url
else:
documents, fragments = export_bulk(arguments.input, arguments.output, arguments.index, arguments.limit)
destination = arguments.output
print(f"documents={documents} fragments={fragments} destination={destination}\nAkyldash Backend v{APP_VERSION} · Frontend — not created")
return 0
+55 -4
View File
@@ -4,8 +4,9 @@ import sqlite3
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
from search.minjust_opensearch import export_bulk
from search.minjust_opensearch import bulk_batches, export_bulk, load_bulk
class MinjustOpenSearchTest(unittest.TestCase):
@@ -17,6 +18,7 @@ class MinjustOpenSearchTest(unittest.TestCase):
with sqlite3.connect(root / "normalized/manifest.sqlite3") as connection:
connection.execute("CREATE TABLE documents (code TEXT, state TEXT)")
connection.execute("INSERT INTO documents VALUES ('7', 'success')")
connection.execute("INSERT INTO documents VALUES ('8', 'success')")
(document_root / "document.json").write_text(
json.dumps(
{
@@ -33,6 +35,11 @@ class MinjustOpenSearchTest(unittest.TestCase):
),
encoding="utf-8",
)
empty = root / "normalized/documents/8"
empty.mkdir()
(empty / "document.json").write_text(
json.dumps({"schema_version": "1", "source_code": "8"}), encoding="utf-8"
)
for language, text in (("ru", "Текст \"RU\"\nстрока"), ("ky", "Кыргызча текст")):
path = document_root / f"editions/10/{language}/fragments.json"
path.parent.mkdir(parents=True)
@@ -56,7 +63,7 @@ class MinjustOpenSearchTest(unittest.TestCase):
)
output = root / "bulk.ndjson"
self.assertEqual(export_bulk(root / "normalized", output, "test-index"), (1, 2))
self.assertEqual(export_bulk(root / "normalized", output, "test-index"), (2, 2))
content = output.read_bytes()
self.assertTrue(content.endswith(b"\n"))
lines = [json.loads(line) for line in content.splitlines()]
@@ -65,6 +72,42 @@ class MinjustOpenSearchTest(unittest.TestCase):
self.assertIn("text_ky", lines[1])
self.assertNotIn("text_ru", lines[1])
self.assertEqual(lines[3]["text_ru"], "Текст \"RU\"\nстрока")
self.assertEqual(
list(bulk_batches(iter((("7", b"a\nb\n"), ("8", b"c\nd\n"))), 4)),
[({"7"}, b"a\nb\n"), ({"8"}, b"c\nd\n")],
)
with patch("search.minjust_opensearch.request_json") as request:
request.side_effect = [{}, {"errors": False, "items": [{"index": {}}, {"index": {}}]}]
self.assertEqual(
load_bulk(root / "normalized", "http://127.0.0.1:9200", "test-index", maximum_bytes=4096),
(2, 2),
)
self.assertEqual(request.call_args_list[1].args[3], "application/x-ndjson")
with patch("search.minjust_opensearch.request_json", return_value={}) as request:
self.assertEqual(
load_bulk(
root / "normalized",
"http://127.0.0.1:9200",
"test-index",
maximum_bytes=4096,
resume=True,
start_at="8",
),
(1, 0),
)
self.assertEqual(request.call_args.args[1], "GET")
with self.assertRaisesRegex(ValueError, "Resume document not found"):
load_bulk(
root / "normalized",
"http://127.0.0.1:9200",
"test-index",
maximum_bytes=4096,
resume=True,
start_at="9",
)
bad = document_root / "editions/10/ru/fragments.json"
fragments = json.loads(bad.read_text(encoding="utf-8"))
@@ -83,9 +126,17 @@ class MinjustOpenSearchTest(unittest.TestCase):
export_bulk(root / "normalized", root / "normalized/manifest.sqlite3", "test-index")
self.assertEqual(output.read_bytes(), content)
mapping = json.loads(
bad.write_text("", encoding="utf-8")
with self.assertRaisesRegex(ValueError, "fragments.json"):
export_bulk(root / "normalized", output, "test-index")
self.assertEqual(output.read_bytes(), content)
definition = json.loads(
(Path(__file__).parent / "search/minjust-fragments-index.json").read_text(encoding="utf-8")
)["mappings"]
)
mapping = definition["mappings"]
self.assertEqual(definition["settings"]["index"]["number_of_shards"], 1)
self.assertEqual(definition["settings"]["index"]["number_of_replicas"], 0)
self.assertEqual(mapping["dynamic"], "strict")
self.assertEqual(mapping["properties"]["position"]["type"], "integer")
self.assertEqual(mapping["properties"]["text_ru"]["analyzer"], "russian")
+3
View File
@@ -0,0 +1,3 @@
FROM opensearchproject/opensearch:3.7.0
RUN /usr/share/opensearch/bin/opensearch-plugin install --batch analysis-icu
+21
View File
@@ -0,0 +1,21 @@
services:
opensearch:
build: .
container_name: akyldash-opensearch
environment:
discovery.type: single-node
bootstrap.memory_lock: "true"
DISABLE_SECURITY_PLUGIN: "true"
OPENSEARCH_JAVA_OPTS: -Xms8g -Xmx8g
mem_limit: 12g
ports:
- 127.0.0.1:9200:9200
ulimits:
memlock:
soft: -1
hard: -1
nofile:
soft: 65536
hard: 65536
volumes:
- ../../data/opensearch-node:/usr/share/opensearch/data
+1 -1
View File
@@ -33,4 +33,4 @@
---
Акылдаш · Telegram-бот v0.2.2 · Backend v0.3.0 · Frontend — не создан
Акылдаш · Telegram-бот v0.2.2 · Backend v0.4.1 · Frontend — не создан
+1 -1
View File
@@ -78,4 +78,4 @@ Telegram позволяет запретить пользователям отп
---
Акылдаш · Telegram-бот v0.2.2 · Backend v0.3.0 · Frontend — не создан
Акылдаш · Telegram-бот v0.2.2 · Backend v0.4.1 · Frontend — не создан
+19 -5
View File
@@ -1,19 +1,19 @@
# Статус проекта
Последняя проверка: 2026-08-13
Последняя проверка: 2026-08-14
Назначение документа: быстро восстановить контекст проекта для участников команды и будущих агентов.
- Telegram-бот: `0.2.2`
- Telegram-бот на Synology: `0.2.1`
- Backend: `0.3.0`
- Backend: `0.4.1`
- Frontend: не создан
## Краткий итог
Репозиторий переориентирован с отдельного бота на весь проект юридической информационно-аналитической платформы. Telegram-бот выделен в инструмент рабочего окружения. Реализованы возобновляемая выгрузка документов из официального Open Data API ЦБД Минюста КР и их локальная воспроизводимая нормализация.
Ближайшая цель — развернуть проверяемый OpenSearch с `analysis-icu`, загрузить
подготовленный Bulk NDJSON и оценить поиск на 50–100 запросах RU/KY.
Ближайшая цель — оценить полный локальный индекс на 50–100 запросах RU/KY и
настроить ранжирование до начала разработки поискового API.
## Уже сделано
@@ -135,6 +135,20 @@
## История изменений статуса
### 2026-08-14
- Полный локальный индекс содержит 56 295 965 фрагментов и успешно отвечает на
RU/KY-запросы.
- Добавлено безопасное продолжение прерванной загрузки существующего индекса.
- Ошибки чтения JSON теперь содержат точный путь и повторяются при временном сбое.
- Версия backend обновлена до `0.4.1`.
### 2026-08-13
- Добавлен локальный одноузловой OpenSearch с `analysis-icu` без Dashboards.
- Добавлена прямая потоковая загрузка корпуса пакетами до 25 МБ.
- Версия backend обновлена до `0.4.0`.
### 2026-08-13
- Подтверждена полная успешная нормализация 209 958 загруженных документов.
@@ -207,4 +221,4 @@
---
Акылдаш · Telegram-бот v0.2.2 · Backend v0.3.0 · Frontend — не создан
Акылдаш · Telegram-бот v0.2.2 · Backend v0.4.1 · Frontend — не создан
+1 -1
View File
@@ -398,4 +398,4 @@ Git сохраняет актуальную версию
---
Акылдаш · Telegram-бот v0.2.2 · Backend v0.3.0 · Frontend — не создан
Акылдаш · Telegram-бот v0.2.2 · Backend v0.4.1 · Frontend — не создан
+1 -1
View File
@@ -258,4 +258,4 @@ runtime-зависимостями frontend. Регистрация в стор
---
Акылдаш · Telegram-бот v0.2.2 · Backend v0.3.0 · Frontend — не создан
Акылдаш · Telegram-бот v0.2.2 · Backend v0.4.1 · Frontend — не создан
@@ -214,4 +214,4 @@ python3 backend/normalization/minjust_cbd.py
---
Акылдаш · Telegram-бот v0.2.2 · Backend v0.3.0 · Frontend — не создан
Акылдаш · Telegram-бот v0.2.2 · Backend v0.4.1 · Frontend — не создан
+1 -1
View File
@@ -44,4 +44,4 @@
---
Акылдаш · Telegram-бот v0.2.2 · Backend v0.3.0 · Frontend — не создан
Акылдаш · Telegram-бот v0.2.2 · Backend v0.4.1 · Frontend — не создан
+1 -1
View File
@@ -180,4 +180,4 @@
---
Акылдаш · Telegram-бот v0.2.2 · Backend v0.3.0 · Frontend — не создан
Акылдаш · Telegram-бот v0.2.2 · Backend v0.4.1 · Frontend — не создан
+1 -1
View File
@@ -48,4 +48,4 @@ python3 -m unittest -v
---
Акылдаш · Telegram-бот v0.2.2 · Backend v0.3.0 · Frontend — не создан
Акылдаш · Telegram-бот v0.2.2 · Backend v0.4.1 · Frontend — не создан