SVO Semantic Chunker
The only release entrypoint is ./build.sh [dev=yes|no] [VERSION], run from
the authoritative checkout on branch local; DEV is the default. For
local-only client artifacts, use env dontpubpypi=1 ./build.sh dev=yes VERSION.
Production promotion requires a direct owner order and the exact sealed full-DEV
GREEN receipt; it performs no rebuild. See
DEV/PROD installation and promotion.
Описание
Алгоритм смыслового чанкования текста на основе SVO-троек и векторного распределения. Поддержка русского, английского и украинского языков. Выход — JSONL или SQLite с оценкой уверенности чанков.
Description
Semantic text chunking algorithm based on SVO triplets and vector proximity. Supports Russian, English, and Ukrainian. Output: JSONL or SQLite with chunk confidence scoring.
Public service API
Use svo_client.SvoChunkerClient for the running service. chunk(text, ...)
returns chunks for one input; chunk_batch(texts, ...) returns one ordered chunk
list per input. The JSON-RPC command is chunk and accepts texts (1..8 inputs),
each at most 1 MiB (1,048,576 UTF-8 bytes). The wire result is NDJSON, inline or
downloaded through an adapter transfer. The client handles both forms.
from svo_client import SvoChunkerClient
from svo_client.config import ClientConfig
# Alternatively pass your configured host, port and TLS credentials directly.
async with SvoChunkerClient(**ClientConfig().get_client_config()) as client:
source = "First paragraph.\n\nSecond paragraph with a long sentence."
chunks = await client.chunk(
source, split_level="paragraph", max_chars=32, use_sv=False,
)
assert "".join(chunk["body"] for chunk in chunks) == source
for chunk in chunks:
assert len(chunk["body"]) <= 32
assert source[chunk["global_start"]:chunk["global_end"]] == chunk["body"]
Exact segmentation and semantic chunking
split_level="paragraph"|"sentence"|"word" requests exact source segments.
Supplying split_level or a positive integer max_chars selects an early path
that skips code/formula/language processing, minimum-length merging, SV,
embedding, recovery and vector reuse. chunk_only is implicit on this path;
even explicit chunk_only=False does not request embeddings. use_sv=True is
rejected. max_chars alone uses paragraph boundaries, with sentence, word and
finally hard-split fallbacks. Its unit is Python characters, not tokens or UTF-8
bytes. No max_tokens parameter is implemented.
Without either segmentation option, ordinary chunking runs structural
paragraph splitting, code and formula handling, pySBD sentence splitting,
long-chunk splitting, language handling, short-chunk merging, optional paragraph
aggregation/preset policy, optional SV, then vectorization. pySBD supports
English, Russian and Ukrainian, with punctuation fallback. type="Comment"
skips sentence splitting, short-chunk merging and effective SV. Legacy defaults
are min_chunk_length=15 and max_chunk_length=2000 characters from server
configuration; short inputs produce per-item errors. window accepts 1..10,
default 3. Paragraph aggregation requires effective SV to be disabled and is
capped by max_chunk_length.
For ordinary chunking without final vectorization, use chunk_only=True and
use_sv=False. Chunk-only processing skips natural-language detection and the
entire language-analysis stage, whether language is supplied or omitted.
The legacy path still requires configured
embedding_config.base_url or embedding_client.base_url. chunk_only=True
alone does not promise that use_sv=True avoids embedding work. The early
segmentation path needs no embedding configuration.
body preserves the original source exactly, including whitespace and CRLF;
join it in source order to reconstruct an input. text is a separate normalized
representation for search/vectorization. Existing start/end retain
block-local compatibility; segmentation also supplies global_start and
global_end as character offsets into each original input. Do not use
normalized text or assume legacy offsets are global.
Presets, flags and file processing
The seven shipped chunk_set names are chat, docstring, fiction, log,
plain_text, scientific_text, and technical_text. Presets live in server
configuration (chunk_sets or chunk_sets_file); calls select a name rather
than define a preset. Explicit request values win over preset defaults. The
client's KNOWN_CHUNK_SET_PRESETS list is advisory: unknown names are forwarded
for server validation.
Preset sizes.target_chars controls merging toward a target, max_chars
controls splitting and hard_max_chars is the final cap; merges cannot break
that cap. These rules preserve body; preset text_transform changes only
text. Per-call max_chars selects exact segmentation and supersedes preset
size behavior. See the client option table for every
supported flag and omission/default behavior.
file acquires and filters a file into prepared texts. file_chunk runs file
acquisition/filtering plus chunking and returns an outbound transfer_id for a
UTF-8 NDJSON artifact. Both support a server-local filepath, inline
filename plus file_content_base64, or completed upload transfer_id plus
filename, with optional filter_name. File offsets refer to prepared text,
not original PDF/HTML bytes. Use the client's file and transfer helpers for
download size/checksum validation and acknowledgment.
Embedding model and positive integer dimension must be supplied together or
both omitted. Omission leaves both fields absent upstream; SVO does not choose
a default model. Server and standalone client share one version source and
must be deployed/packaged with equal versions.
See the client API and response contract for parsing, item errors, offset examples and transfer handling.
Pipeline
pipeline --list lists checks, pipeline <check-name> runs one check, and
pipeline runs the complete suite. The pipeline is a thin wrapper over the
public client: it owns fixtures/assertions and observed side-effect evidence;
transport, TLS, JSON-RPC, transfer and NDJSON parsing belong to svo_client.
- Границы чанков оптимизируются по максимизации семантического отклонения между блоком и его S–V-ядром (vector proximity, maximization).
Внешние зависимости / External dependencies
-
chunk-metadata-adapter
- PyPi:
pip install chunk-metadata-adapter - Служит "клеем" между разными микросервисами, проверяет отдаваемые метаданные на валидность, обеспечивает единый формат передачи chunk-метаданных между сервисами.
- Используется для валидации и стандартизации метаданных чанков, интеграции с другими сервисами экосистемы.
- PyPi:
-
mcp-proxy-adapter
- PyPi:
pip install mcp-proxy-adapter - Автоматизирует создание API и REST-интерфейсов, предоставляет сервер для MCP-Proxy.
- Позволяет быстро развернуть REST/JSON-RPC сервер для взаимодействия с MCP-Proxy и другими сервисами.
- PyPi:
Поддерживаемые языки / Supported languages
- Русский (ru)
- Английский (en)
- Украинский (uk)
- Смешанные тексты (автоматическое разбиение на языковые блоки)
Быстрый старт / Quickstart
pip install svo-chunker
python -m spacy download en_core_web_sm
Python API
from svo_chunker.svo_chunker import SVOChunker
# CPU (по умолчанию)
chunker = SVOChunker()
# Явно включить GPU (если доступен)
chunker_gpu = SVOChunker(use_gpu=True)
# Пример для смешанного текста (русский, английский, украинский)
text = "Вона відкрила вікно. She went to the kitchen. Она испугалась."
chunk_pairs = await chunker.chunk_by_sv_semantics(text)
for chunk, chunk_vector in chunk_pairs:
print(f"Chunk: {chunk}\nVector: {chunk_vector[:5]}...\n")
Формат вывода / Output format
chunk_by_sv_semantics возвращает список кортежей (chunk_dict, chunk_vector), где:
chunk_dict— словарь с полями:start,end— индексы токеновsv— словарь с S–V парой (subject,verb)block— список токеновscore— float, метрика качества
chunk_vector— list[float], эмбеддинг чанка
Fallback-эвристика по алфавиту
Если язык не определён автоматически, используется эвристика:
- Если есть уникальные украинские буквы (
ї,є,ґ) —uk - Если кириллица без уникальных украинских —
ru - Если латиница —
en - Иначе блок пропускается
CLI
python -m svo_chunker.utils.chunk_text_cli.py -i input.txt -o output.jsonl --host http://localhost --port 8001 --show-vectors
- По умолчанию используется CPU. Для GPU используйте SVOChunker(use_gpu=True) в своем скрипте.
Best practices
- Для больших и смешанных текстов используйте пакетную обработку и GPU.
- Для грязных данных — алгоритм устойчив к ошибкам и автоматически разбивает на языковые блоки.
- Для тестирования используйте датасеты из папки
datasets/.
Примеры / Examples
См. папку svo_chunker/examples/ (есть примеры для всех языков и смешанных текстов)
TODO
- SVO extraction
- Chunk boundary detection
- Residual allocation
- Confidence scoring
- Output formatting (JSONL/SQLite)
Установка моделей Stanza
Перед первым запуском необходимо вручную скачать модели Stanza для всех поддерживаемых языков:
python -c "import stanza; [stanza.download(lang) for lang in ['ru', 'en', 'uk']]"
Это действие требуется выполнить только один раз (или при обновлении моделей). После этого пакет будет использовать локальные копии моделей без повторных скачиваний.
⚠️ Загрузка моделей Stanza (RU/EN/UK)
Перед первым использованием необходимо скачать модели Stanza для русского, английского и украинского языков:
python -c "import stanza; stanza.download('ru'); stanza.download('en'); stanza.download('uk')"
Если вы запускаете тесты или используете пакет впервые, этот шаг обязателен. Иначе код попытается скачать модели автоматически при первом запуске (может "зависнуть" без интернета).
⚠️ Download Stanza models (RU/EN/UK)
Before first use, you must download Stanza models for Russian, English, and Ukrainian:
python -c "import stanza; stanza.download('ru'); stanza.download('en'); stanza.download('uk')"
If you run tests or use the package for the first time, this step is required. Otherwise, the code will try to download models automatically on first run (may hang if no internet).
Использование в Docker/контейнерах
1. Скачивание моделей при сборке контейнера
В Dockerfile:
FROM python:3.12
WORKDIR /app
COPY . /app
RUN pip install -r requirements.txt
# Скачиваем модели Stanza в /models/stanza_resources
RUN python -c "import stanza; stanza.download('ru', dir='/models/stanza_resources'); stanza.download('en', dir='/models/stanza_resources'); stanza.download('uk', dir='/models/stanza_resources')"
ENV STANZA_RESOURCES_DIR=/models/stanza_resources
CMD ["python", "your_script.py"]
2. Монтирование volume с моделями
На хосте:
python -c "import stanza; stanza.download('ru'); stanza.download('en'); stanza.download('uk')"
Запуск контейнера:
docker run -v ~/stanza_resources:/root/stanza_resources ...
3. Явное указание пути к моделям в коде
import stanza
stanza.download('ru', dir='/models/stanza_resources')
nlp = stanza.Pipeline(lang='ru', dir='/models/stanza_resources')
4. Рекомендации для production/CI/CD
- Всегда используйте переменную окружения
STANZA_RESOURCES_DIRили параметрdir. - Не храните большие модели внутри кода — используйте volume или отдельный слой Docker.
- Документируйте путь к моделям для всех участников команды.
Flat-модели метаданных чанков / Flat chunk metadata models
Что такое flat-модель?
Flat-модель — это упрощённое (плоское) представление метаданных чанка, где все поля вынесены на верхний уровень структуры (без вложенных объектов). Такой формат удобен для хранения в реляционных БД, передачи через API и интеграции с внешними сервисами.
Основные flat-модели:
- FlatSemanticChunk (из chunk-metadata-adapter):
- Используется для хранения и передачи метаданных в формате, совместимом с большинством хранилищ и API.
- Все поля — строки или простые типы (tags — строка, type — строка).
- Поддерживает строгую валидацию (UUID, ISO8601, enum-значения).
- Преобразование из/в полную модель:
.from_semantic_chunk(),.to_semantic_chunk().
- ApiSemanticChunk (локальная модель для API):
- Используется для формирования ответов сервера.
- Современный контракт:
tags— всегда список строк,type— строка (значение Enum), остальные поля совместимы с SemanticChunk. - Гарантирует строгую валидацию и прозрачность структуры для клиента.
Когда использовать flat-модель?
- Для интеграции с внешними сервисами, где требуется простой и предсказуемый формат (например, REST API, JSONL, SQLite).
- Для хранения в БД, где вложенные структуры неудобны.
- Для передачи между микросервисами, использующими разные языки/стек.
Когда использовать полную модель (SemanticChunk)?
- Для внутренней логики, сложной обработки, ML/аналитики, когда важна типизация и вложенность.
- Для валидации и преобразования данных перед сохранением или отправкой наружу.
Пример: FlatSemanticChunk (адаптер)
from chunk_metadata_adapter.models import FlatSemanticChunk
chunk = FlatSemanticChunk(
uuid="...",
type="Draft",
text="...",
tags="tag1,tag2",
...
)
Пример: ApiSemanticChunk (API)
from commands.api_models import ApiSemanticChunk
chunk = ApiSemanticChunk(
uuid="...",
type="Draft",
text="...",
tags=["tag1", "tag2"],
...
)
Варианты использования
- Сервер: всегда возвращает список объектов ApiSemanticChunk (контракт: tags — список, type — строка).
- Внешние клиенты: могут использовать FlatSemanticChunk для хранения или преобразования данных.
- Миграция и интеграция: flat-модели позволяют легко мигрировать данные между сервисами и версиями API.
Важно
- Всегда валидируйте данные перед отправкой клиенту через ApiSemanticChunk.
- Для совместимости с legacy-сервисами используйте FlatSemanticChunk и преобразование tags <-> строка.
Metadata
Release files for svo-client-dev 4.0.24
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| svo_client_dev-4.0.24.tar.gz | 40.7 kB | Without provenance | Details for svo_client_dev-4.0.24.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| svo_client_dev-4.0.24-py3-none-any.whl | Python 3 | none | any | Details for svo_client_dev-4.0.24-py3-none-any.whl |
Total release size: 79.6 kB
Release files / svo_client_dev-4.0.24.tar.gz
| Download URL | svo_client_dev-4.0.24.tar.gz |
|---|---|
| Size | 40.7 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
9040005b6e1df2107d592912851ca3d6706451175106143af531ae9aa30c6330
|
|
BLAKE2b-256 checksum How to use checksums |
6cf3233f6ce4883734d3e58e20dffbacc4ca2f923ab157cd79987b4d9b5ec8fe
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.14.4
|
Release files / svo_client_dev-4.0.24-py3-none-any.whl
| Download URL | svo_client_dev-4.0.24-py3-none-any.whl |
|---|---|
| Size | 38.9 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
e89ca6eb536a9e8a16874daa3339e1eb7befbc2deddb408235011b4c67007100
|
|
BLAKE2b-256 checksum How to use checksums |
927e4a99df4e1d41042e36ca4701b11abc665538189ef940b4a39d3630e4aadf
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.14.4
|
Security for svo-client-dev 4.0.24
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.