svo-client-dev 4.0.21__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,363 @@
1
+ Metadata-Version: 2.4
2
+ Name: svo-client-dev
3
+ Version: 4.0.21
4
+ Summary: Client for the SVO semantic chunking service
5
+ Home-page: https://github.com/maverikod/vvz-svo-chunker
6
+ Author: Vasiliy Zdanovskiy
7
+ Author-email: vasilyvz@gmail.com
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.9
12
+ Description-Content-Type: text/markdown
13
+ Requires-Dist: aiohttp
14
+ Requires-Dist: chunk-metadata-adapter>=3.4.0
15
+ Requires-Dist: jsonschema<5,>=4.18
16
+ Requires-Dist: mcp-proxy-adapter>=8.11.9
17
+ Dynamic: author
18
+ Dynamic: author-email
19
+ Dynamic: classifier
20
+ Dynamic: description
21
+ Dynamic: description-content-type
22
+ Dynamic: home-page
23
+ Dynamic: requires-dist
24
+ Dynamic: requires-python
25
+ Dynamic: summary
26
+
27
+ # SVO Semantic Chunker
28
+
29
+ The only release entrypoint is `./build.sh [dev=yes|no] [VERSION]`, run from
30
+ the authoritative checkout on branch `local`; DEV is the default. For
31
+ local-only client artifacts, use `env dontpubpypi=1 ./build.sh dev=yes VERSION`.
32
+ Production promotion requires a direct owner order and the exact sealed full-DEV
33
+ GREEN receipt; it performs no rebuild. See
34
+ [DEV/PROD installation and promotion](docs/dev-prod.md).
35
+
36
+ ## Описание
37
+
38
+ Алгоритм смыслового чанкования текста на основе SVO-троек и векторного распределения. Поддержка русского, английского и украинского языков. Выход — JSONL или SQLite с оценкой уверенности чанков.
39
+
40
+ ## Description
41
+
42
+ Semantic text chunking algorithm based on SVO triplets and vector proximity. Supports Russian, English, and Ukrainian. Output: JSONL or SQLite with chunk confidence scoring.
43
+
44
+ ## Public service API
45
+
46
+ Use `svo_client.SvoChunkerClient` for the running service. `chunk(text, ...)`
47
+ returns chunks for one input; `chunk_batch(texts, ...)` returns one ordered chunk
48
+ list per input. The JSON-RPC command is `chunk` and accepts `texts` (1..8 inputs),
49
+ each at most 1 MiB (1,048,576 UTF-8 bytes). The wire result is NDJSON, inline or
50
+ downloaded through an adapter transfer. The client handles both forms.
51
+
52
+ ```python
53
+ from svo_client import SvoChunkerClient
54
+ from svo_client.config import ClientConfig
55
+
56
+ # Alternatively pass your configured host, port and TLS credentials directly.
57
+ async with SvoChunkerClient(**ClientConfig().get_client_config()) as client:
58
+ source = "First paragraph.\n\nSecond paragraph with a long sentence."
59
+ chunks = await client.chunk(
60
+ source, split_level="paragraph", max_chars=32, use_sv=False,
61
+ )
62
+ assert "".join(chunk["body"] for chunk in chunks) == source
63
+ for chunk in chunks:
64
+ assert len(chunk["body"]) <= 32
65
+ assert source[chunk["global_start"]:chunk["global_end"]] == chunk["body"]
66
+ ```
67
+
68
+ ### Exact segmentation and semantic chunking
69
+
70
+ `split_level="paragraph"|"sentence"|"word"` requests exact source segments.
71
+ Supplying `split_level` or a positive integer `max_chars` selects an early path
72
+ that skips code/formula/language processing, minimum-length merging, SV,
73
+ embedding, recovery and vector reuse. `chunk_only` is implicit on this path;
74
+ even explicit `chunk_only=False` does not request embeddings. `use_sv=True` is
75
+ rejected. `max_chars` alone uses paragraph boundaries, with sentence, word and
76
+ finally hard-split fallbacks. Its unit is Python characters, not tokens or UTF-8
77
+ bytes. No `max_tokens` parameter is implemented.
78
+
79
+ Without either segmentation option, ordinary chunking runs structural
80
+ paragraph splitting, code and formula handling, pySBD sentence splitting,
81
+ long-chunk splitting, language handling, short-chunk merging, optional paragraph
82
+ aggregation/preset policy, optional SV, then vectorization. pySBD supports
83
+ English, Russian and Ukrainian, with punctuation fallback. `type="Comment"`
84
+ skips sentence splitting, short-chunk merging and effective SV. Legacy defaults
85
+ are `min_chunk_length=15` and `max_chunk_length=2000` characters from server
86
+ configuration; short inputs produce per-item errors. `window` accepts 1..10,
87
+ default 3. Paragraph aggregation requires effective SV to be disabled and is
88
+ capped by `max_chunk_length`.
89
+
90
+ For ordinary chunking without final vectorization, use `chunk_only=True` and
91
+ `use_sv=False`. Chunk-only processing skips natural-language detection and the
92
+ entire language-analysis stage, whether `language` is supplied or omitted.
93
+ The legacy path still requires configured
94
+ `embedding_config.base_url` or `embedding_client.base_url`. `chunk_only=True`
95
+ alone does not promise that `use_sv=True` avoids embedding work. The early
96
+ segmentation path needs no embedding configuration.
97
+
98
+ `body` preserves the original source exactly, including whitespace and CRLF;
99
+ join it in source order to reconstruct an input. `text` is a separate normalized
100
+ representation for search/vectorization. Existing `start`/`end` retain
101
+ block-local compatibility; segmentation also supplies `global_start` and
102
+ `global_end` as character offsets into each original input. Do not use
103
+ normalized `text` or assume legacy offsets are global.
104
+
105
+ ### Presets, flags and file processing
106
+
107
+ The seven shipped `chunk_set` names are `chat`, `docstring`, `fiction`, `log`,
108
+ `plain_text`, `scientific_text`, and `technical_text`. Presets live in server
109
+ configuration (`chunk_sets` or `chunk_sets_file`); calls select a name rather
110
+ than define a preset. Explicit request values win over preset defaults. The
111
+ client's `KNOWN_CHUNK_SET_PRESETS` list is advisory: unknown names are forwarded
112
+ for server validation.
113
+
114
+ Preset `sizes.target_chars` controls merging toward a target, `max_chars`
115
+ controls splitting and `hard_max_chars` is the final cap; merges cannot break
116
+ that cap. These rules preserve `body`; preset `text_transform` changes only
117
+ `text`. Per-call `max_chars` selects exact segmentation and supersedes preset
118
+ size behavior. See the [client option table](svo_client/README.md) for every
119
+ supported flag and omission/default behavior.
120
+
121
+ `file` acquires and filters a file into prepared texts. `file_chunk` runs file
122
+ acquisition/filtering plus chunking and returns an outbound `transfer_id` for a
123
+ UTF-8 NDJSON artifact. Both support a server-local `filepath`, inline
124
+ `filename` plus `file_content_base64`, or completed upload `transfer_id` plus
125
+ `filename`, with optional `filter_name`. File offsets refer to prepared text,
126
+ not original PDF/HTML bytes. Use the client's file and transfer helpers for
127
+ download size/checksum validation and acknowledgment.
128
+
129
+ Embedding `model` and positive integer `dimension` must be supplied together or
130
+ both omitted. Omission leaves both fields absent upstream; SVO does not choose
131
+ a default model. Server and standalone client share one version source and
132
+ must be deployed/packaged with equal versions.
133
+
134
+ See the [client API](svo_client/README.md) and
135
+ [response contract](docs/CHUNK_API_RESPONSE_FORMAT.md) for parsing, item errors,
136
+ offset examples and transfer handling.
137
+
138
+ ### Pipeline
139
+
140
+ `pipeline --list` lists checks, `pipeline <check-name>` runs one check, and
141
+ `pipeline` runs the complete suite. The pipeline is a thin wrapper over the
142
+ public client: it owns fixtures/assertions and observed side-effect evidence;
143
+ transport, TLS, JSON-RPC, transfer and NDJSON parsing belong to `svo_client`.
144
+
145
+ - Границы чанков оптимизируются по **максимизации** семантического отклонения между блоком и его S–V-ядром (vector proximity, maximization).
146
+
147
+ ## Внешние зависимости / External dependencies
148
+
149
+ - **chunk-metadata-adapter**
150
+ - PyPi: `pip install chunk-metadata-adapter`
151
+ - Служит "клеем" между разными микросервисами, проверяет отдаваемые метаданные на валидность, обеспечивает единый формат передачи chunk-метаданных между сервисами.
152
+ - Используется для валидации и стандартизации метаданных чанков, интеграции с другими сервисами экосистемы.
153
+
154
+ - **mcp-proxy-adapter**
155
+ - PyPi: `pip install mcp-proxy-adapter`
156
+ - Автоматизирует создание API и REST-интерфейсов, предоставляет сервер для MCP-Proxy.
157
+ - Позволяет быстро развернуть REST/JSON-RPC сервер для взаимодействия с MCP-Proxy и другими сервисами.
158
+
159
+ ---
160
+
161
+ ## Поддерживаемые языки / Supported languages
162
+ - Русский (ru)
163
+ - Английский (en)
164
+ - Украинский (uk)
165
+ - Смешанные тексты (автоматическое разбиение на языковые блоки)
166
+
167
+ ---
168
+
169
+ ## Быстрый старт / Quickstart
170
+
171
+ ```bash
172
+ pip install svo-chunker
173
+ python -m spacy download en_core_web_sm
174
+ ```
175
+
176
+ ### Python API
177
+ ```python
178
+ from svo_chunker.svo_chunker import SVOChunker
179
+ # CPU (по умолчанию)
180
+ chunker = SVOChunker()
181
+ # Явно включить GPU (если доступен)
182
+ chunker_gpu = SVOChunker(use_gpu=True)
183
+
184
+ # Пример для смешанного текста (русский, английский, украинский)
185
+ text = "Вона відкрила вікно. She went to the kitchen. Она испугалась."
186
+ chunk_pairs = await chunker.chunk_by_sv_semantics(text)
187
+ for chunk, chunk_vector in chunk_pairs:
188
+ print(f"Chunk: {chunk}\nVector: {chunk_vector[:5]}...\n")
189
+ ```
190
+
191
+ ### Формат вывода / Output format
192
+ `chunk_by_sv_semantics` возвращает список кортежей `(chunk_dict, chunk_vector)`, где:
193
+ - `chunk_dict` — словарь с полями:
194
+ - `start`, `end` — индексы токенов
195
+ - `sv` — словарь с S–V парой (`subject`, `verb`)
196
+ - `block` — список токенов
197
+ - `score` — float, метрика качества
198
+ - `chunk_vector` — list[float], эмбеддинг чанка
199
+
200
+ ### Fallback-эвристика по алфавиту
201
+ Если язык не определён автоматически, используется эвристика:
202
+ - Если есть уникальные украинские буквы (`ї`, `є`, `ґ`) — `uk`
203
+ - Если кириллица без уникальных украинских — `ru`
204
+ - Если латиница — `en`
205
+ - Иначе блок пропускается
206
+
207
+ ### CLI
208
+ ```bash
209
+ python -m svo_chunker.utils.chunk_text_cli.py -i input.txt -o output.jsonl --host http://localhost --port 8001 --show-vectors
210
+ ```
211
+ - По умолчанию используется CPU. Для GPU используйте SVOChunker(use_gpu=True) в своем скрипте.
212
+
213
+ ---
214
+
215
+ ## Best practices
216
+ - Для больших и смешанных текстов используйте пакетную обработку и GPU.
217
+ - Для грязных данных — алгоритм устойчив к ошибкам и автоматически разбивает на языковые блоки.
218
+ - Для тестирования используйте датасеты из папки `datasets/`.
219
+
220
+ ---
221
+
222
+ ## Примеры / Examples
223
+ См. папку svo_chunker/examples/ (есть примеры для всех языков и смешанных текстов)
224
+
225
+ ---
226
+
227
+ ## TODO
228
+ - SVO extraction
229
+ - Chunk boundary detection
230
+ - Residual allocation
231
+ - Confidence scoring
232
+ - Output formatting (JSONL/SQLite)
233
+
234
+ ## Установка моделей Stanza
235
+
236
+ Перед первым запуском необходимо вручную скачать модели Stanza для всех поддерживаемых языков:
237
+
238
+ ```bash
239
+ python -c "import stanza; [stanza.download(lang) for lang in ['ru', 'en', 'uk']]"
240
+ ```
241
+
242
+ Это действие требуется выполнить только один раз (или при обновлении моделей). После этого пакет будет использовать локальные копии моделей без повторных скачиваний.
243
+
244
+ ## ⚠️ Загрузка моделей Stanza (RU/EN/UK)
245
+
246
+ Перед первым использованием необходимо скачать модели Stanza для русского, английского и украинского языков:
247
+
248
+ ```bash
249
+ python -c "import stanza; stanza.download('ru'); stanza.download('en'); stanza.download('uk')"
250
+ ```
251
+
252
+ Если вы запускаете тесты или используете пакет впервые, этот шаг обязателен. Иначе код попытается скачать модели автоматически при первом запуске (может "зависнуть" без интернета).
253
+
254
+ ## ⚠️ Download Stanza models (RU/EN/UK)
255
+
256
+ Before first use, you must download Stanza models for Russian, English, and Ukrainian:
257
+
258
+ ```bash
259
+ python -c "import stanza; stanza.download('ru'); stanza.download('en'); stanza.download('uk')"
260
+ ```
261
+
262
+ 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).
263
+
264
+ ---
265
+
266
+ ## Использование в Docker/контейнерах
267
+
268
+ ### 1. Скачивание моделей при сборке контейнера
269
+
270
+ В Dockerfile:
271
+ ```dockerfile
272
+ FROM python:3.12
273
+ WORKDIR /app
274
+ COPY . /app
275
+ RUN pip install -r requirements.txt
276
+ # Скачиваем модели Stanza в /models/stanza_resources
277
+ 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')"
278
+ ENV STANZA_RESOURCES_DIR=/models/stanza_resources
279
+ CMD ["python", "your_script.py"]
280
+ ```
281
+
282
+ ### 2. Монтирование volume с моделями
283
+
284
+ На хосте:
285
+ ```bash
286
+ python -c "import stanza; stanza.download('ru'); stanza.download('en'); stanza.download('uk')"
287
+ ```
288
+ Запуск контейнера:
289
+ ```bash
290
+ docker run -v ~/stanza_resources:/root/stanza_resources ...
291
+ ```
292
+
293
+ ### 3. Явное указание пути к моделям в коде
294
+ ```python
295
+ import stanza
296
+ stanza.download('ru', dir='/models/stanza_resources')
297
+ nlp = stanza.Pipeline(lang='ru', dir='/models/stanza_resources')
298
+ ```
299
+
300
+ ### 4. Рекомендации для production/CI/CD
301
+ - Всегда используйте переменную окружения `STANZA_RESOURCES_DIR` или параметр `dir`.
302
+ - Не храните большие модели внутри кода — используйте volume или отдельный слой Docker.
303
+ - Документируйте путь к моделям для всех участников команды.
304
+
305
+ ---
306
+
307
+ ## Flat-модели метаданных чанков / Flat chunk metadata models
308
+
309
+ ### Что такое flat-модель?
310
+ Flat-модель — это упрощённое (плоское) представление метаданных чанка, где все поля вынесены на верхний уровень структуры (без вложенных объектов). Такой формат удобен для хранения в реляционных БД, передачи через API и интеграции с внешними сервисами.
311
+
312
+ ### Основные flat-модели:
313
+ - **FlatSemanticChunk** (из chunk-metadata-adapter):
314
+ - Используется для хранения и передачи метаданных в формате, совместимом с большинством хранилищ и API.
315
+ - Все поля — строки или простые типы (tags — строка, type — строка).
316
+ - Поддерживает строгую валидацию (UUID, ISO8601, enum-значения).
317
+ - Преобразование из/в полную модель: `.from_semantic_chunk()`, `.to_semantic_chunk()`.
318
+ - **ApiSemanticChunk** (локальная модель для API):
319
+ - Используется для формирования ответов сервера.
320
+ - Современный контракт: `tags` — всегда список строк, `type` — строка (значение Enum), остальные поля совместимы с SemanticChunk.
321
+ - Гарантирует строгую валидацию и прозрачность структуры для клиента.
322
+
323
+ ### Когда использовать flat-модель?
324
+ - Для интеграции с внешними сервисами, где требуется простой и предсказуемый формат (например, REST API, JSONL, SQLite).
325
+ - Для хранения в БД, где вложенные структуры неудобны.
326
+ - Для передачи между микросервисами, использующими разные языки/стек.
327
+
328
+ ### Когда использовать полную модель (SemanticChunk)?
329
+ - Для внутренней логики, сложной обработки, ML/аналитики, когда важна типизация и вложенность.
330
+ - Для валидации и преобразования данных перед сохранением или отправкой наружу.
331
+
332
+ ### Пример: FlatSemanticChunk (адаптер)
333
+ ```python
334
+ from chunk_metadata_adapter.models import FlatSemanticChunk
335
+ chunk = FlatSemanticChunk(
336
+ uuid="...",
337
+ type="Draft",
338
+ text="...",
339
+ tags="tag1,tag2",
340
+ ...
341
+ )
342
+ ```
343
+
344
+ ### Пример: ApiSemanticChunk (API)
345
+ ```python
346
+ from commands.api_models import ApiSemanticChunk
347
+ chunk = ApiSemanticChunk(
348
+ uuid="...",
349
+ type="Draft",
350
+ text="...",
351
+ tags=["tag1", "tag2"],
352
+ ...
353
+ )
354
+ ```
355
+
356
+ ### Варианты использования
357
+ - **Сервер**: всегда возвращает список объектов ApiSemanticChunk (контракт: tags — список, type — строка).
358
+ - **Внешние клиенты**: могут использовать FlatSemanticChunk для хранения или преобразования данных.
359
+ - **Миграция и интеграция**: flat-модели позволяют легко мигрировать данные между сервисами и версиями API.
360
+
361
+ ### Важно
362
+ - Всегда валидируйте данные перед отправкой клиенту через ApiSemanticChunk.
363
+ - Для совместимости с legacy-сервисами используйте FlatSemanticChunk и преобразование tags <-> строка.