gramscii-semantic-chapters 0.3.0__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.
Files changed (29) hide show
  1. gramscii_semantic_chapters-0.3.0/LICENSE +21 -0
  2. gramscii_semantic_chapters-0.3.0/MANIFEST.in +1 -0
  3. gramscii_semantic_chapters-0.3.0/PKG-INFO +94 -0
  4. gramscii_semantic_chapters-0.3.0/README.md +77 -0
  5. gramscii_semantic_chapters-0.3.0/examples/build.json +51 -0
  6. gramscii_semantic_chapters-0.3.0/examples/passages.json +9 -0
  7. gramscii_semantic_chapters-0.3.0/examples/runtime.json +17 -0
  8. gramscii_semantic_chapters-0.3.0/pyproject.toml +30 -0
  9. gramscii_semantic_chapters-0.3.0/setup.cfg +4 -0
  10. gramscii_semantic_chapters-0.3.0/src/gramscii_semantic_chapters.egg-info/PKG-INFO +94 -0
  11. gramscii_semantic_chapters-0.3.0/src/gramscii_semantic_chapters.egg-info/SOURCES.txt +27 -0
  12. gramscii_semantic_chapters-0.3.0/src/gramscii_semantic_chapters.egg-info/dependency_links.txt +1 -0
  13. gramscii_semantic_chapters-0.3.0/src/gramscii_semantic_chapters.egg-info/entry_points.txt +2 -0
  14. gramscii_semantic_chapters-0.3.0/src/gramscii_semantic_chapters.egg-info/requires.txt +4 -0
  15. gramscii_semantic_chapters-0.3.0/src/gramscii_semantic_chapters.egg-info/top_level.txt +1 -0
  16. gramscii_semantic_chapters-0.3.0/src/semantic_chapters/__init__.py +11 -0
  17. gramscii_semantic_chapters-0.3.0/src/semantic_chapters/__main__.py +111 -0
  18. gramscii_semantic_chapters-0.3.0/src/semantic_chapters/build.py +265 -0
  19. gramscii_semantic_chapters-0.3.0/src/semantic_chapters/checkpoint.py +47 -0
  20. gramscii_semantic_chapters-0.3.0/src/semantic_chapters/clustering.py +135 -0
  21. gramscii_semantic_chapters-0.3.0/src/semantic_chapters/generation.py +101 -0
  22. gramscii_semantic_chapters-0.3.0/src/semantic_chapters/index.py +194 -0
  23. gramscii_semantic_chapters-0.3.0/src/semantic_chapters/prompts/chapter_keywords.md +13 -0
  24. gramscii_semantic_chapters-0.3.0/src/semantic_chapters/prompts/chapter_summary.md +13 -0
  25. gramscii_semantic_chapters-0.3.0/src/semantic_chapters/prompts/verify_summary.md +16 -0
  26. gramscii_semantic_chapters-0.3.0/src/semantic_chapters/vllm.py +123 -0
  27. gramscii_semantic_chapters-0.3.0/tests/test_cli.py +102 -0
  28. gramscii_semantic_chapters-0.3.0/tests/test_clustering.py +76 -0
  29. gramscii_semantic_chapters-0.3.0/tests/test_index.py +183 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Gramscii
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ include examples/*.json
@@ -0,0 +1,94 @@
1
+ Metadata-Version: 2.4
2
+ Name: gramscii-semantic-chapters
3
+ Version: 0.3.0
4
+ Summary: Group document passages and search verified summaries with source traceability.
5
+ Author: Gramscii
6
+ License-Expression: MIT
7
+ Project-URL: Repository, https://github.com/Gramscii-Git/semantic-chapters
8
+ Project-URL: Issues, https://github.com/Gramscii-Git/semantic-chapters/issues
9
+ Requires-Python: >=3.11
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Requires-Dist: filelock>=3.13
13
+ Requires-Dist: numpy>=1.26
14
+ Requires-Dist: pydantic<3,>=2.7
15
+ Requires-Dist: scipy>=1.11
16
+ Dynamic: license-file
17
+
18
+ # Semantic Chapters
19
+
20
+ Semantic Chapters groups document passages by embedding similarity, verifies summaries against quoted source passages, and builds an index for finding the original chunk IDs. Groups represent topics. Related passages can come from different pages.
21
+
22
+ ## Install
23
+
24
+ ```sh
25
+ python -m pip install .
26
+ semantic-chapters group examples/passages.json
27
+ ```
28
+
29
+ The grouping command uses prepared embeddings and runs locally. It evaluates feasible topic counts up to `max_topics` using cosine silhouette. It prefers the smaller count on ties. The single-topic and all-singleton partitions have a neutral score of zero. The optional `min_size` and `max_size` constrain sizes and report each changed chunk assignment. The score describes the partition before rebalancing. Grouping uses quadratic memory in the number of passages.
30
+
31
+ ## Build and search from the terminal
32
+
33
+ Prepare a JSON file with the document metadata, settings, chunk IDs, passage text, and embeddings. Use [the sample build input](examples/build.json) for the shape. Configure the generation, verification, and embedding endpoints with [the sample runtime file](examples/runtime.json). The CLI uses vLLM-compatible chat completions with JSON schema, embeddings, and tokenization endpoints. Set the model names and endpoints for your deployment. If an endpoint requires authentication, set `token_env` to the name of the environment variable containing its bearer credential.
34
+
35
+ ```sh
36
+ semantic-chapters build examples/build.json --runtime runtime.json \
37
+ --checkpoint report.sqlite --output report-topics.json
38
+ semantic-chapters search report-topics.json "Did the sample complete the test?" \
39
+ --runtime runtime.json --limit 3 --min-score 0.4
40
+ ```
41
+
42
+ Use the same embedding space for input passages and search queries. Search ranks vectors that contain the section title, its verified claims, and its keyword text. A keyword retains only its text and nearest source chunk IDs. Its temporary vector is used during indexing to locate those chunks.
43
+
44
+ The pipeline counts input tokens and reserves completion tokens before every generation request. Set the shared context window no higher than the smaller chat model context. Verification batching reserves room for both the candidate and the verdict. A large topic is summarized in multiple source batches. A chunk that cannot fit on its own produces an explicit error and should be split before indexing. The build checks that each cited quote occurs verbatim in its source chunk and sends the title and claims to a separate verification call. The verifier checks whether the evidence supports the claims in context. Verification is model-assisted and its accuracy depends on the models and documents.
45
+
46
+ Each successful verified summary, keyword extraction, section, and topic is persisted in the checkpoint database. Rerun with the same input, settings, model identifiers and checkpoint to continue. The build rejects a checkpoint for a different configuration. Model responses that violate the schema or grounding checks get up to the configured `max_attempts`. A fenced JSON response is accepted when its contents match the schema. Exhausted retries report the failed step. The final index is written atomically after all topics complete.
47
+
48
+ ## Python API
49
+
50
+ ```python
51
+ from pathlib import Path
52
+
53
+ from semantic_chapters import TopicIndex, build_index
54
+
55
+ index = build_index(
56
+ passages, document=document, settings=settings, runtime=runtime,
57
+ checkpoint=Path("report.sqlite"),
58
+ )
59
+ Path("report-topics.json").write_text(index.model_dump_json(), encoding="utf-8")
60
+
61
+ index = TopicIndex.model_validate_json(Path("report-topics.json").read_bytes())
62
+ query_vector = runtime.embed(["Did the sample complete the test?"])[0]
63
+ for match in index.search_summaries(
64
+ query_vector, embedding_model=runtime.embedding_model, limit=3, min_score=0.4,
65
+ ):
66
+ print(match.topic.title, match.topic.summary, match.topic.chunk_ids)
67
+ ```
68
+
69
+ The `Runtime` contract accepts generation, embedding and token counting functions. Generation receives the JSON schema and output token allowance in `GenerationRequest`. Input token counting includes the request's model-specific chat template and schema handling. Fetch and cite original passages using the returned chunk IDs.
70
+
71
+ ## Indexing cost
72
+
73
+ Clustering uses cosine similarity over the embeddings already computed for the chunks. The language model runs on the resulting topic sections. Each section typically takes three generative requests. One produces the title and claims, one verifies them against excerpts, and one extracts keywords. Long topics can span several sections, and verification batches or retries can add requests. Embedding and token counting have their own cost. For example, 1,000 chunks grouped into 20 single-section topics would take 60 generative requests if every stage fits and succeeds on the first attempt.
74
+
75
+ The standard Microsoft GraphRAG indexing pipeline uses an LLM to extract entities and relationships from each text unit, then summarizes graph descriptions and communities. FastGraphRAG uses linguistic methods for extraction and still generates community reports. Semantic Chapters produces a topic index for passage retrieval. Grouping and summaries can miss relevant details, so the index keeps the original chunk IDs and cited excerpts. Measure input and output tokens as well as request counts to compare the cost of indexing the same corpus. [Microsoft GraphRAG indexing methods](https://microsoft.github.io/graphrag/index/methods/)
76
+
77
+ ## Integrate with hybrid retrieval
78
+
79
+ The built-in search ranks enriched summary embeddings by cosine similarity and returns topics with their original chunk IDs. A chat application can show the topic titles as selectable search scopes. Selecting a topic supplies its chunk IDs as an allowlist for the application's passage search, within the user's existing access permissions.
80
+
81
+ A host application can also index topic summaries as the first stage of a hybrid search. Apply metadata and access filters, search by meaning and with BM25, fuse the scores, and rerank the summary candidates. A second query variant and a starting fusion weight of 70% vector and 30% BM25 are configurable choices for that host. Expand the selected summaries to their chunk IDs, then retrieve and rank the original passages for the answer and citations.
82
+
83
+ A compact summary index can narrow the candidate set. LLMs can make mistakes, and embedding-based clustering can put passages in the wrong group. That's why you should test the groups and tune similarity thresholds on real documents. To calibrate the minimum cosine score (`min_score`), use questions with known supporting chunks and compare evidence recall, answer quality and query latency against direct chunk retrieval.
84
+
85
+ ## Development
86
+
87
+ ```sh
88
+ python -m pip install -e .
89
+ python -m unittest discover -s tests -v
90
+ ```
91
+
92
+ ## License
93
+
94
+ [MIT](LICENSE)
@@ -0,0 +1,77 @@
1
+ # Semantic Chapters
2
+
3
+ Semantic Chapters groups document passages by embedding similarity, verifies summaries against quoted source passages, and builds an index for finding the original chunk IDs. Groups represent topics. Related passages can come from different pages.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ python -m pip install .
9
+ semantic-chapters group examples/passages.json
10
+ ```
11
+
12
+ The grouping command uses prepared embeddings and runs locally. It evaluates feasible topic counts up to `max_topics` using cosine silhouette. It prefers the smaller count on ties. The single-topic and all-singleton partitions have a neutral score of zero. The optional `min_size` and `max_size` constrain sizes and report each changed chunk assignment. The score describes the partition before rebalancing. Grouping uses quadratic memory in the number of passages.
13
+
14
+ ## Build and search from the terminal
15
+
16
+ Prepare a JSON file with the document metadata, settings, chunk IDs, passage text, and embeddings. Use [the sample build input](examples/build.json) for the shape. Configure the generation, verification, and embedding endpoints with [the sample runtime file](examples/runtime.json). The CLI uses vLLM-compatible chat completions with JSON schema, embeddings, and tokenization endpoints. Set the model names and endpoints for your deployment. If an endpoint requires authentication, set `token_env` to the name of the environment variable containing its bearer credential.
17
+
18
+ ```sh
19
+ semantic-chapters build examples/build.json --runtime runtime.json \
20
+ --checkpoint report.sqlite --output report-topics.json
21
+ semantic-chapters search report-topics.json "Did the sample complete the test?" \
22
+ --runtime runtime.json --limit 3 --min-score 0.4
23
+ ```
24
+
25
+ Use the same embedding space for input passages and search queries. Search ranks vectors that contain the section title, its verified claims, and its keyword text. A keyword retains only its text and nearest source chunk IDs. Its temporary vector is used during indexing to locate those chunks.
26
+
27
+ The pipeline counts input tokens and reserves completion tokens before every generation request. Set the shared context window no higher than the smaller chat model context. Verification batching reserves room for both the candidate and the verdict. A large topic is summarized in multiple source batches. A chunk that cannot fit on its own produces an explicit error and should be split before indexing. The build checks that each cited quote occurs verbatim in its source chunk and sends the title and claims to a separate verification call. The verifier checks whether the evidence supports the claims in context. Verification is model-assisted and its accuracy depends on the models and documents.
28
+
29
+ Each successful verified summary, keyword extraction, section, and topic is persisted in the checkpoint database. Rerun with the same input, settings, model identifiers and checkpoint to continue. The build rejects a checkpoint for a different configuration. Model responses that violate the schema or grounding checks get up to the configured `max_attempts`. A fenced JSON response is accepted when its contents match the schema. Exhausted retries report the failed step. The final index is written atomically after all topics complete.
30
+
31
+ ## Python API
32
+
33
+ ```python
34
+ from pathlib import Path
35
+
36
+ from semantic_chapters import TopicIndex, build_index
37
+
38
+ index = build_index(
39
+ passages, document=document, settings=settings, runtime=runtime,
40
+ checkpoint=Path("report.sqlite"),
41
+ )
42
+ Path("report-topics.json").write_text(index.model_dump_json(), encoding="utf-8")
43
+
44
+ index = TopicIndex.model_validate_json(Path("report-topics.json").read_bytes())
45
+ query_vector = runtime.embed(["Did the sample complete the test?"])[0]
46
+ for match in index.search_summaries(
47
+ query_vector, embedding_model=runtime.embedding_model, limit=3, min_score=0.4,
48
+ ):
49
+ print(match.topic.title, match.topic.summary, match.topic.chunk_ids)
50
+ ```
51
+
52
+ The `Runtime` contract accepts generation, embedding and token counting functions. Generation receives the JSON schema and output token allowance in `GenerationRequest`. Input token counting includes the request's model-specific chat template and schema handling. Fetch and cite original passages using the returned chunk IDs.
53
+
54
+ ## Indexing cost
55
+
56
+ Clustering uses cosine similarity over the embeddings already computed for the chunks. The language model runs on the resulting topic sections. Each section typically takes three generative requests. One produces the title and claims, one verifies them against excerpts, and one extracts keywords. Long topics can span several sections, and verification batches or retries can add requests. Embedding and token counting have their own cost. For example, 1,000 chunks grouped into 20 single-section topics would take 60 generative requests if every stage fits and succeeds on the first attempt.
57
+
58
+ The standard Microsoft GraphRAG indexing pipeline uses an LLM to extract entities and relationships from each text unit, then summarizes graph descriptions and communities. FastGraphRAG uses linguistic methods for extraction and still generates community reports. Semantic Chapters produces a topic index for passage retrieval. Grouping and summaries can miss relevant details, so the index keeps the original chunk IDs and cited excerpts. Measure input and output tokens as well as request counts to compare the cost of indexing the same corpus. [Microsoft GraphRAG indexing methods](https://microsoft.github.io/graphrag/index/methods/)
59
+
60
+ ## Integrate with hybrid retrieval
61
+
62
+ The built-in search ranks enriched summary embeddings by cosine similarity and returns topics with their original chunk IDs. A chat application can show the topic titles as selectable search scopes. Selecting a topic supplies its chunk IDs as an allowlist for the application's passage search, within the user's existing access permissions.
63
+
64
+ A host application can also index topic summaries as the first stage of a hybrid search. Apply metadata and access filters, search by meaning and with BM25, fuse the scores, and rerank the summary candidates. A second query variant and a starting fusion weight of 70% vector and 30% BM25 are configurable choices for that host. Expand the selected summaries to their chunk IDs, then retrieve and rank the original passages for the answer and citations.
65
+
66
+ A compact summary index can narrow the candidate set. LLMs can make mistakes, and embedding-based clustering can put passages in the wrong group. That's why you should test the groups and tune similarity thresholds on real documents. To calibrate the minimum cosine score (`min_score`), use questions with known supporting chunks and compare evidence recall, answer quality and query latency against direct chunk retrieval.
67
+
68
+ ## Development
69
+
70
+ ```sh
71
+ python -m pip install -e .
72
+ python -m unittest discover -s tests -v
73
+ ```
74
+
75
+ ## License
76
+
77
+ [MIT](LICENSE)
@@ -0,0 +1,51 @@
1
+ {
2
+ "document": {
3
+ "document_id": "report-42",
4
+ "source_language": "English",
5
+ "output_language": "English",
6
+ "document_category": "test report"
7
+ },
8
+ "settings": {
9
+ "max_topics": 5,
10
+ "keyword_limit": 5,
11
+ "chunks_per_keyword": 3,
12
+ "max_attempts": 3,
13
+ "context_window": 8192,
14
+ "max_output_tokens": 768,
15
+ "embedding_context_window": 4096
16
+ },
17
+ "passages": [
18
+ {
19
+ "chunk_id": "test-method",
20
+ "text": "The samples underwent 40 cycles.",
21
+ "embedding": [
22
+ 1,
23
+ 0.02
24
+ ]
25
+ },
26
+ {
27
+ "chunk_id": "test-results",
28
+ "text": "All samples completed the cycles.",
29
+ "embedding": [
30
+ 0.98,
31
+ 0.08
32
+ ]
33
+ },
34
+ {
35
+ "chunk_id": "billing-period",
36
+ "text": "The invoice covers April.",
37
+ "embedding": [
38
+ 0.02,
39
+ 1
40
+ ]
41
+ },
42
+ {
43
+ "chunk_id": "billing-total",
44
+ "text": "The invoice total includes VAT.",
45
+ "embedding": [
46
+ 0.1,
47
+ 0.96
48
+ ]
49
+ }
50
+ ]
51
+ }
@@ -0,0 +1,9 @@
1
+ {
2
+ "max_topics": 3,
3
+ "passages": [
4
+ {"chunk_id": "test-method", "text": "The samples underwent 40 cycles.", "embedding": [1.0, 0.02]},
5
+ {"chunk_id": "billing-period", "text": "The invoice covers April.", "embedding": [0.02, 1.0]},
6
+ {"chunk_id": "test-results", "text": "All samples completed the cycles.", "embedding": [0.98, 0.08]},
7
+ {"chunk_id": "billing-total", "text": "The invoice total includes VAT.", "embedding": [0.10, 0.96]}
8
+ ]
9
+ }
@@ -0,0 +1,17 @@
1
+ {
2
+ "generation": {
3
+ "model": "generation-model",
4
+ "url": "http://127.0.0.1:8000/v1/chat/completions",
5
+ "tokenize_url": "http://127.0.0.1:8000/tokenize"
6
+ },
7
+ "verification": {
8
+ "model": "verification-model",
9
+ "url": "http://127.0.0.1:8001/v1/chat/completions",
10
+ "tokenize_url": "http://127.0.0.1:8001/tokenize"
11
+ },
12
+ "embeddings": {
13
+ "model": "embedding-model",
14
+ "url": "http://127.0.0.1:8002/v1/embeddings",
15
+ "tokenize_url": "http://127.0.0.1:8002/tokenize"
16
+ }
17
+ }
@@ -0,0 +1,30 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "gramscii-semantic-chapters"
7
+ version = "0.3.0"
8
+ description = "Group document passages and search verified summaries with source traceability."
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [{name = "Gramscii"}]
14
+ dependencies = ["filelock>=3.13", "numpy>=1.26", "pydantic>=2.7,<3", "scipy>=1.11"]
15
+
16
+ [project.urls]
17
+ Repository = "https://github.com/Gramscii-Git/semantic-chapters"
18
+ Issues = "https://github.com/Gramscii-Git/semantic-chapters/issues"
19
+
20
+ [project.scripts]
21
+ semantic-chapters = "semantic_chapters.__main__:main"
22
+
23
+ [tool.setuptools.packages.find]
24
+ where = ["src"]
25
+
26
+ [tool.setuptools.package-data]
27
+ semantic_chapters = ["prompts/*.md"]
28
+
29
+ [tool.ruff.lint.isort]
30
+ known-first-party = ["semantic_chapters"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,94 @@
1
+ Metadata-Version: 2.4
2
+ Name: gramscii-semantic-chapters
3
+ Version: 0.3.0
4
+ Summary: Group document passages and search verified summaries with source traceability.
5
+ Author: Gramscii
6
+ License-Expression: MIT
7
+ Project-URL: Repository, https://github.com/Gramscii-Git/semantic-chapters
8
+ Project-URL: Issues, https://github.com/Gramscii-Git/semantic-chapters/issues
9
+ Requires-Python: >=3.11
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Requires-Dist: filelock>=3.13
13
+ Requires-Dist: numpy>=1.26
14
+ Requires-Dist: pydantic<3,>=2.7
15
+ Requires-Dist: scipy>=1.11
16
+ Dynamic: license-file
17
+
18
+ # Semantic Chapters
19
+
20
+ Semantic Chapters groups document passages by embedding similarity, verifies summaries against quoted source passages, and builds an index for finding the original chunk IDs. Groups represent topics. Related passages can come from different pages.
21
+
22
+ ## Install
23
+
24
+ ```sh
25
+ python -m pip install .
26
+ semantic-chapters group examples/passages.json
27
+ ```
28
+
29
+ The grouping command uses prepared embeddings and runs locally. It evaluates feasible topic counts up to `max_topics` using cosine silhouette. It prefers the smaller count on ties. The single-topic and all-singleton partitions have a neutral score of zero. The optional `min_size` and `max_size` constrain sizes and report each changed chunk assignment. The score describes the partition before rebalancing. Grouping uses quadratic memory in the number of passages.
30
+
31
+ ## Build and search from the terminal
32
+
33
+ Prepare a JSON file with the document metadata, settings, chunk IDs, passage text, and embeddings. Use [the sample build input](examples/build.json) for the shape. Configure the generation, verification, and embedding endpoints with [the sample runtime file](examples/runtime.json). The CLI uses vLLM-compatible chat completions with JSON schema, embeddings, and tokenization endpoints. Set the model names and endpoints for your deployment. If an endpoint requires authentication, set `token_env` to the name of the environment variable containing its bearer credential.
34
+
35
+ ```sh
36
+ semantic-chapters build examples/build.json --runtime runtime.json \
37
+ --checkpoint report.sqlite --output report-topics.json
38
+ semantic-chapters search report-topics.json "Did the sample complete the test?" \
39
+ --runtime runtime.json --limit 3 --min-score 0.4
40
+ ```
41
+
42
+ Use the same embedding space for input passages and search queries. Search ranks vectors that contain the section title, its verified claims, and its keyword text. A keyword retains only its text and nearest source chunk IDs. Its temporary vector is used during indexing to locate those chunks.
43
+
44
+ The pipeline counts input tokens and reserves completion tokens before every generation request. Set the shared context window no higher than the smaller chat model context. Verification batching reserves room for both the candidate and the verdict. A large topic is summarized in multiple source batches. A chunk that cannot fit on its own produces an explicit error and should be split before indexing. The build checks that each cited quote occurs verbatim in its source chunk and sends the title and claims to a separate verification call. The verifier checks whether the evidence supports the claims in context. Verification is model-assisted and its accuracy depends on the models and documents.
45
+
46
+ Each successful verified summary, keyword extraction, section, and topic is persisted in the checkpoint database. Rerun with the same input, settings, model identifiers and checkpoint to continue. The build rejects a checkpoint for a different configuration. Model responses that violate the schema or grounding checks get up to the configured `max_attempts`. A fenced JSON response is accepted when its contents match the schema. Exhausted retries report the failed step. The final index is written atomically after all topics complete.
47
+
48
+ ## Python API
49
+
50
+ ```python
51
+ from pathlib import Path
52
+
53
+ from semantic_chapters import TopicIndex, build_index
54
+
55
+ index = build_index(
56
+ passages, document=document, settings=settings, runtime=runtime,
57
+ checkpoint=Path("report.sqlite"),
58
+ )
59
+ Path("report-topics.json").write_text(index.model_dump_json(), encoding="utf-8")
60
+
61
+ index = TopicIndex.model_validate_json(Path("report-topics.json").read_bytes())
62
+ query_vector = runtime.embed(["Did the sample complete the test?"])[0]
63
+ for match in index.search_summaries(
64
+ query_vector, embedding_model=runtime.embedding_model, limit=3, min_score=0.4,
65
+ ):
66
+ print(match.topic.title, match.topic.summary, match.topic.chunk_ids)
67
+ ```
68
+
69
+ The `Runtime` contract accepts generation, embedding and token counting functions. Generation receives the JSON schema and output token allowance in `GenerationRequest`. Input token counting includes the request's model-specific chat template and schema handling. Fetch and cite original passages using the returned chunk IDs.
70
+
71
+ ## Indexing cost
72
+
73
+ Clustering uses cosine similarity over the embeddings already computed for the chunks. The language model runs on the resulting topic sections. Each section typically takes three generative requests. One produces the title and claims, one verifies them against excerpts, and one extracts keywords. Long topics can span several sections, and verification batches or retries can add requests. Embedding and token counting have their own cost. For example, 1,000 chunks grouped into 20 single-section topics would take 60 generative requests if every stage fits and succeeds on the first attempt.
74
+
75
+ The standard Microsoft GraphRAG indexing pipeline uses an LLM to extract entities and relationships from each text unit, then summarizes graph descriptions and communities. FastGraphRAG uses linguistic methods for extraction and still generates community reports. Semantic Chapters produces a topic index for passage retrieval. Grouping and summaries can miss relevant details, so the index keeps the original chunk IDs and cited excerpts. Measure input and output tokens as well as request counts to compare the cost of indexing the same corpus. [Microsoft GraphRAG indexing methods](https://microsoft.github.io/graphrag/index/methods/)
76
+
77
+ ## Integrate with hybrid retrieval
78
+
79
+ The built-in search ranks enriched summary embeddings by cosine similarity and returns topics with their original chunk IDs. A chat application can show the topic titles as selectable search scopes. Selecting a topic supplies its chunk IDs as an allowlist for the application's passage search, within the user's existing access permissions.
80
+
81
+ A host application can also index topic summaries as the first stage of a hybrid search. Apply metadata and access filters, search by meaning and with BM25, fuse the scores, and rerank the summary candidates. A second query variant and a starting fusion weight of 70% vector and 30% BM25 are configurable choices for that host. Expand the selected summaries to their chunk IDs, then retrieve and rank the original passages for the answer and citations.
82
+
83
+ A compact summary index can narrow the candidate set. LLMs can make mistakes, and embedding-based clustering can put passages in the wrong group. That's why you should test the groups and tune similarity thresholds on real documents. To calibrate the minimum cosine score (`min_score`), use questions with known supporting chunks and compare evidence recall, answer quality and query latency against direct chunk retrieval.
84
+
85
+ ## Development
86
+
87
+ ```sh
88
+ python -m pip install -e .
89
+ python -m unittest discover -s tests -v
90
+ ```
91
+
92
+ ## License
93
+
94
+ [MIT](LICENSE)
@@ -0,0 +1,27 @@
1
+ LICENSE
2
+ MANIFEST.in
3
+ README.md
4
+ pyproject.toml
5
+ examples/build.json
6
+ examples/passages.json
7
+ examples/runtime.json
8
+ src/gramscii_semantic_chapters.egg-info/PKG-INFO
9
+ src/gramscii_semantic_chapters.egg-info/SOURCES.txt
10
+ src/gramscii_semantic_chapters.egg-info/dependency_links.txt
11
+ src/gramscii_semantic_chapters.egg-info/entry_points.txt
12
+ src/gramscii_semantic_chapters.egg-info/requires.txt
13
+ src/gramscii_semantic_chapters.egg-info/top_level.txt
14
+ src/semantic_chapters/__init__.py
15
+ src/semantic_chapters/__main__.py
16
+ src/semantic_chapters/build.py
17
+ src/semantic_chapters/checkpoint.py
18
+ src/semantic_chapters/clustering.py
19
+ src/semantic_chapters/generation.py
20
+ src/semantic_chapters/index.py
21
+ src/semantic_chapters/vllm.py
22
+ src/semantic_chapters/prompts/chapter_keywords.md
23
+ src/semantic_chapters/prompts/chapter_summary.md
24
+ src/semantic_chapters/prompts/verify_summary.md
25
+ tests/test_cli.py
26
+ tests/test_clustering.py
27
+ tests/test_index.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ semantic-chapters = semantic_chapters.__main__:main
@@ -0,0 +1,4 @@
1
+ filelock>=3.13
2
+ numpy>=1.26
3
+ pydantic<3,>=2.7
4
+ scipy>=1.11
@@ -0,0 +1,11 @@
1
+ """Group, summarize, verify, and search document topics."""
2
+
3
+ from .build import build_index
4
+ from .clustering import group_passages
5
+ from .generation import GenerationRequest, Runtime
6
+ from .index import Document, IndexSettings, Passage, TopicIndex
7
+
8
+ __all__ = [
9
+ "Document", "GenerationRequest", "IndexSettings", "Passage", "Runtime", "TopicIndex",
10
+ "build_index", "group_passages",
11
+ ]
@@ -0,0 +1,111 @@
1
+ """Group passages, build a verified topic index, or search a saved index."""
2
+
3
+ import argparse
4
+ import json
5
+ import os
6
+ from pathlib import Path
7
+ from tempfile import NamedTemporaryFile
8
+ from typing import Annotated
9
+
10
+ from filelock import Timeout
11
+ from pydantic import Field
12
+
13
+ from .build import build_index
14
+ from .clustering import group_passages, unit_vectors
15
+ from .index import Document, IndexSettings, Passage, Record, TopicIndex
16
+ from .vllm import VllmSettings, vllm_runtime
17
+
18
+
19
+ class BuildInput(Record):
20
+ document: Document
21
+ settings: IndexSettings
22
+ passages: Annotated[tuple[Passage, ...], Field(min_length=1)]
23
+
24
+
25
+ def _write_index(output: Path, index: TopicIndex) -> None:
26
+ with NamedTemporaryFile(mode="w", encoding="utf-8", dir=output.parent, delete=False) as handle:
27
+ temporary = Path(handle.name)
28
+ try:
29
+ handle.write(index.model_dump_json())
30
+ handle.flush()
31
+ os.fsync(handle.fileno())
32
+ handle.close()
33
+ os.replace(temporary, output)
34
+ finally:
35
+ temporary.unlink(missing_ok=True)
36
+
37
+
38
+ def main() -> None:
39
+ parser = argparse.ArgumentParser(description=__doc__)
40
+ commands = parser.add_subparsers(dest="command", required=True)
41
+ grouping = commands.add_parser("group", help="group precomputed passage embeddings")
42
+ grouping.add_argument("input", type=Path)
43
+ build = commands.add_parser("build", help="build and save a verified topic index")
44
+ build.add_argument("input", type=Path)
45
+ build.add_argument("--runtime", type=Path, required=True)
46
+ build.add_argument("--checkpoint", type=Path, required=True)
47
+ build.add_argument("--output", type=Path, required=True)
48
+ search = commands.add_parser("search", help="search topic summaries and return source IDs")
49
+ search.add_argument("index", type=Path)
50
+ search.add_argument("query")
51
+ search.add_argument("--runtime", type=Path, required=True)
52
+ search.add_argument("--limit", type=int, required=True)
53
+ search.add_argument("--min-score", type=float, required=True)
54
+ args = parser.parse_args()
55
+ try:
56
+ if args.command == "group":
57
+ _group(args.input)
58
+ elif args.command == "build":
59
+ _build(args)
60
+ else:
61
+ _search(args)
62
+ except (OSError, KeyError, TypeError, ValueError, Timeout) as error:
63
+ parser.exit(2, f"{parser.prog}: {error}\n")
64
+
65
+
66
+ def _group(path: Path) -> None:
67
+ payload = json.loads(path.read_text(encoding="utf-8"))
68
+ passages = payload["passages"]
69
+ result = group_passages(
70
+ [item["chunk_id"] for item in passages], [item["embedding"] for item in passages],
71
+ max_topics=payload["max_topics"], min_size=payload.get("min_size"), max_size=payload.get("max_size"),
72
+ )
73
+ print(json.dumps({"topics": result.groups, "silhouette": result.silhouette, "reassignments": result.reassignments}))
74
+
75
+
76
+ def _build(args) -> None:
77
+ paths = {getattr(args, name).resolve() for name in ("input", "runtime", "checkpoint", "output")}
78
+ if len(paths) != 4:
79
+ raise ValueError("input, runtime, checkpoint, and output must use distinct paths")
80
+ request = BuildInput.model_validate_json(args.input.read_bytes())
81
+ runtime = vllm_runtime(
82
+ VllmSettings.model_validate_json(args.runtime.read_bytes()),
83
+ context_window=request.settings.context_window,
84
+ embedding_context_window=request.settings.embedding_context_window,
85
+ )
86
+ index = build_index(
87
+ request.passages, document=request.document, settings=request.settings, runtime=runtime,
88
+ checkpoint=args.checkpoint,
89
+ )
90
+ _write_index(args.output, index)
91
+ print(json.dumps({"index": str(args.output), "topics": len(index.topics),
92
+ "reassignments": len(index.reassignments)}))
93
+
94
+
95
+ def _search(args) -> None:
96
+ runtime = vllm_runtime(VllmSettings.model_validate_json(args.runtime.read_bytes()))
97
+ index = TopicIndex.model_validate_json(args.index.read_bytes())
98
+ if runtime.embedding_model != index.embedding_model:
99
+ raise ValueError("runtime and index must use the same embedding model")
100
+ runtime.count_embedding_tokens(args.query)
101
+ query = tuple(unit_vectors(runtime.embed([args.query]), 1)[0])
102
+ for match in index.search_summaries(
103
+ query, embedding_model=runtime.embedding_model, limit=args.limit, min_score=args.min_score,
104
+ ):
105
+ result = match.model_dump(mode="json", exclude={"topic": {"sections": {"__all__": {"embedding"}}}})
106
+ result["topic"]["summary"] = match.topic.summary
107
+ print(json.dumps(result, ensure_ascii=False))
108
+
109
+
110
+ if __name__ == "__main__":
111
+ main()