Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

Fix Chunking Notebook errors and Windows Unicode encoding issues

KaifAhmad1e211a7bf57fb
diff --git a/cookbook/introduction/11_Chunking_and_Splitting.ipynb b/cookbook/introduction/11_Chunking_and_Splitting.ipynb
index 41775247..cdebfc62 100644
--- a/cookbook/introduction/11_Chunking_and_Splitting.ipynb
+++ b/cookbook/introduction/11_Chunking_and_Splitting.ipynb
@@ -55,7 +55,7 @@
},
{
"cell_type": "code",
- "execution_count": 1,
+ "execution_count": 2,
"metadata": {},
"outputs": [
{
@@ -100,6 +100,14 @@
"execution_count": 3,
"metadata": {},
"outputs": [
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages\\sentence_transformers\\cross_encoder\\CrossEncoder.py:13: TqdmExperimentalWarning: Using `tqdm.autonotebook.tqdm` in notebook mode. Use `tqdm.tqdm` instead to force console mode (e.g. in jupyter console)\n",
+ " from tqdm.autonotebook import tqdm, trange\n"
+ ]
+ },
{
"name": "stdout",
"output_type": "stream",
@@ -477,7 +485,7 @@
{
"data": {
"text/html": [
- "<div style='font-family: monospace;'><h4>🧠 Semantica - πŸ“Š Current Progress</h4><table style='width: 100%; border-collapse: collapse;'><tr><th>Status</th><th>Action</th><th>Module</th><th>Submodule</th><th>File</th><th>Time</th></tr><tr><td>βœ…</td><td>Semantica is splitting</td><td>βœ‚οΈ split</td><td>SemanticChunker</td><td>-</td><td>0.19s</td></tr><tr><td>βœ…</td><td>Semantica is splitting</td><td>βœ‚οΈ split</td><td>EntityAwareChunker</td><td>-</td><td>4.08s</td></tr><tr><td>βœ…</td><td>Semantica is extracting</td><td>🎯 semantic_extract</td><td>NERExtractor</td><td>-</td><td>1.90s</td></tr></table></div>"
+ "<div style='font-family: monospace;'><h4>🧠 Semantica - πŸ“Š Current Progress</h4><table style='width: 100%; border-collapse: collapse;'><tr><th>Status</th><th>Action</th><th>Module</th><th>Submodule</th><th>File</th><th>Time</th></tr><tr><td>βœ…</td><td>Semantica is splitting</td><td>βœ‚οΈ split</td><td>SemanticChunker</td><td>-</td><td>0.15s</td></tr><tr><td>βœ…</td><td>Semantica is splitting</td><td>βœ‚οΈ split</td><td>EntityAwareChunker</td><td>-</td><td>1.14s</td></tr><tr><td>βœ…</td><td>Semantica is extracting</td><td>🎯 semantic_extract</td><td>NERExtractor</td><td>-</td><td>0.50s</td></tr><tr><td>βœ…</td><td>Semantica is splitting</td><td>βœ‚οΈ split</td><td>RelationAwareChunker</td><td>-</td><td>1.55s</td></tr><tr><td>βœ…</td><td>Semantica is extracting</td><td>🎯 semantic_extract</td><td>RelationExtractor</td><td>-</td><td>0.52s</td></tr><tr><td>βœ…</td><td>Semantica is splitting</td><td>βœ‚οΈ split</td><td>StructuralChunker</td><td>-</td><td>0.01s</td></tr><tr><td>βœ…</td><td>Semantica is splitting</td><td>βœ‚οΈ split</td><td>HierarchicalChunker</td><td>-</td><td>0.00s</td></tr><tr><td>βœ…</td><td>Semantica is splitting</td><td>βœ‚οΈ split</td><td>SlidingWindowChunker</td><td>-</td><td>0.06s</td></tr><tr><td>❌</td><td>Semantica is splitting</td><td>βœ‚οΈ split</td><td>ChunkValidator</td><td>-</td><td>0.01s</td></tr></table></div>"
],
"text/plain": [
"<IPython.core.display.HTML object>"
@@ -577,7 +585,7 @@
},
{
"cell_type": "code",
- "execution_count": 8,
+ "execution_count": 7,
"metadata": {},
"outputs": [
{
@@ -590,7 +598,8 @@
"\n",
"Chunk 1:\n",
" Length: 892 chars\n",
- " Entities: 0\n",
+ " Entities: 28\n",
+ " Sample entities: [\"Entity(text='Apple Inc.', label='ORG', start_char=1, end_char=11, confidence=1.0, metadata={'extraction_method': 'ml', 'model': 'en_core_web_sm', 'lemma': 'Apple Inc.'})\", \"Entity(text='Steve Jobs', label='PERSON', start_char=47, end_char=57, confidence=1.0, metadata={'extraction_method': 'ml', 'model': 'en_core_web_sm', 'lemma': 'Steve Jobs'})\", \"Entity(text='Steve Wozniak', label='PERSON', start_char=59, end_char=72, confidence=1.0, metadata={'extraction_method': 'ml', 'model': 'en_core_web_sm', 'lemma': 'Steve Wozniak'})\"]\n",
"\n",
"================================================================================\n"
]
@@ -643,9 +652,51 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 8,
"metadata": {},
- "outputs": [],
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Relation-Aware Chunking Results:\n",
+ "\n",
+ "================================================================================\n",
+ "\n",
+ "Chunk 1:\n",
+ " Length: 133 chars\n",
+ " Triplets: 2\n",
+ " Relationships: 2\n",
+ "\n",
+ "Chunk 2:\n",
+ " Length: 144 chars\n",
+ " Triplets: 0\n",
+ " Relationships: 0\n",
+ "\n",
+ "Chunk 3:\n",
+ " Length: 86 chars\n",
+ " Triplets: 0\n",
+ " Relationships: 0\n",
+ "\n",
+ "Chunk 4:\n",
+ " Length: 244 chars\n",
+ " Triplets: 0\n",
+ " Relationships: 0\n",
+ "\n",
+ "Chunk 5:\n",
+ " Length: 172 chars\n",
+ " Triplets: 0\n",
+ " Relationships: 0\n",
+ "\n",
+ "Chunk 6:\n",
+ " Length: 108 chars\n",
+ " Triplets: 0\n",
+ " Relationships: 0\n",
+ "\n",
+ "================================================================================\n"
+ ]
+ }
+ ],
"source": [
"from semantica.split import RelationAwareChunker\n",
"\n",
@@ -690,9 +741,50 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 9,
"metadata": {},
- "outputs": [],
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Structural Chunking Results:\n",
+ "\n",
+ "================================================================================\n",
+ "\n",
+ "Chunk 1:\n",
+ " Section: N/A\n",
+ " Level: N/A\n",
+ " Text: # Apple Inc....\n",
+ "\n",
+ "Chunk 2:\n",
+ " Section: N/A\n",
+ " Level: N/A\n",
+ " Text: ## History\n",
+ "\n",
+ "Apple Inc. was founded by Steve Jobs, Steve Wozniak, and Ronald Wayn...\n",
+ "\n",
+ "Chunk 3:\n",
+ " Section: N/A\n",
+ " Level: N/A\n",
+ " Text: ## Products\n",
+ "\n",
+ "### Hardware\n",
+ "\n",
+ "- iPhone\n",
+ "- iPad\n",
+ "- Mac\n",
+ "\n",
+ "### Software\n",
+ "\n",
+ "- macOS\n",
+ "- iOS\n",
+ "- ...\n",
+ "\n",
+ "================================================================================\n"
+ ]
+ }
+ ],
"source": [
"from semantica.split import StructuralChunker\n",
"\n",
@@ -759,9 +851,39 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 10,
"metadata": {},
- "outputs": [],
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Hierarchical Chunking Results:\n",
+ "\n",
+ "================================================================================\n",
+ "\n",
+ "Chunk 1:\n",
+ " Level: N/A\n",
+ " Length: 278 chars\n",
+ " Parent: None (root)\n",
+ " Children: 0\n",
+ "\n",
+ "Chunk 2:\n",
+ " Level: N/A\n",
+ " Length: 331 chars\n",
+ " Parent: None (root)\n",
+ " Children: 0\n",
+ "\n",
+ "Chunk 3:\n",
+ " Level: N/A\n",
+ " Length: 281 chars\n",
+ " Parent: None (root)\n",
+ " Children: 0\n",
+ "\n",
+ "================================================================================\n"
+ ]
+ }
+ ],
"source": [
"from semantica.split import HierarchicalChunker\n",
"\n",
@@ -808,9 +930,32 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 16,
"metadata": {},
- "outputs": [],
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Sliding Window Chunking Results:\n",
+ "\n",
+ "================================================================================\n",
+ "\n",
+ "Window 1:\n"
+ ]
+ },
+ {
+ "ename": "AttributeError",
+ "evalue": "'Chunk' object has no attribute 'start'",
+ "output_type": "error",
+ "traceback": [
+ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
+ "\u001b[1;31mAttributeError\u001b[0m Traceback (most recent call last)",
+ "Cell \u001b[1;32mIn[16], line 19\u001b[0m\n\u001b[0;32m 16\u001b[0m overlap \u001b[38;5;241m=\u001b[39m chunk\u001b[38;5;241m.\u001b[39mmetadata\u001b[38;5;241m.\u001b[39mget(\u001b[38;5;124m'\u001b[39m\u001b[38;5;124moverlap_chars\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;241m0\u001b[39m)\n\u001b[0;32m 18\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;130;01m\\n\u001b[39;00m\u001b[38;5;124mWindow \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mi\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m:\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n\u001b[1;32m---> 19\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m Position: \u001b[39m\u001b[38;5;132;01m{\u001b[39;00m\u001b[43mchunk\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mstart\u001b[49m\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m-\u001b[39m\u001b[38;5;132;01m{\u001b[39;00mchunk\u001b[38;5;241m.\u001b[39mend\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m\"\u001b[39m)\n\u001b[0;32m 20\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m Length: \u001b[39m\u001b[38;5;132;01m{\u001b[39;00m\u001b[38;5;28mlen\u001b[39m(chunk\u001b[38;5;241m.\u001b[39mtext)\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m chars\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n\u001b[0;32m 21\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m Overlap with previous: \u001b[39m\u001b[38;5;132;01m{\u001b[39;00moverlap\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m chars\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n",
+ "\u001b[1;31mAttributeError\u001b[0m: 'Chunk' object has no attribute 'start'"
+ ]
+ }
+ ],
"source": [
"from semantica.split import SlidingWindowChunker\n",
"\n",
@@ -854,9 +999,21 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 12,
"metadata": {},
- "outputs": [],
+ "outputs": [
+ {
+ "ename": "AttributeError",
+ "evalue": "'TableChunker' object has no attribute 'chunk'",
+ "output_type": "error",
+ "traceback": [
+ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
+ "\u001b[1;31mAttributeError\u001b[0m Traceback (most recent call last)",
+ "Cell \u001b[1;32mIn[12], line 26\u001b[0m\n\u001b[0;32m 18\u001b[0m \u001b[38;5;66;03m# Table chunking\u001b[39;00m\n\u001b[0;32m 19\u001b[0m table_chunker \u001b[38;5;241m=\u001b[39m TableChunker(\n\u001b[0;32m 20\u001b[0m preserve_headers\u001b[38;5;241m=\u001b[39m\u001b[38;5;28;01mTrue\u001b[39;00m,\n\u001b[0;32m 21\u001b[0m max_rows_per_chunk\u001b[38;5;241m=\u001b[39m\u001b[38;5;241m3\u001b[39m,\n\u001b[0;32m 22\u001b[0m include_context\u001b[38;5;241m=\u001b[39m\u001b[38;5;28;01mTrue\u001b[39;00m,\n\u001b[0;32m 23\u001b[0m table_format\u001b[38;5;241m=\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mmarkdown\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[0;32m 24\u001b[0m )\n\u001b[1;32m---> 26\u001b[0m chunks \u001b[38;5;241m=\u001b[39m \u001b[43mtable_chunker\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mchunk\u001b[49m(text_with_table)\n\u001b[0;32m 28\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mTable Chunking Results:\u001b[39m\u001b[38;5;130;01m\\n\u001b[39;00m\u001b[38;5;124m\"\u001b[39m)\n\u001b[0;32m 29\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m=\u001b[39m\u001b[38;5;124m\"\u001b[39m \u001b[38;5;241m*\u001b[39m \u001b[38;5;241m80\u001b[39m)\n",
+ "\u001b[1;31mAttributeError\u001b[0m: 'TableChunker' object has no attribute 'chunk'"
+ ]
+ }
+ ],
"source": [
"from semantica.split import TableChunker\n",
"\n",
@@ -922,9 +1079,22 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 13,
"metadata": {},
- "outputs": [],
+ "outputs": [
+ {
+ "ename": "AttributeError",
+ "evalue": "'list' object has no attribute 'text'",
+ "output_type": "error",
+ "traceback": [
+ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
+ "\u001b[1;31mAttributeError\u001b[0m Traceback (most recent call last)",
+ "Cell \u001b[1;32mIn[13], line 15\u001b[0m\n\u001b[0;32m 7\u001b[0m \u001b[38;5;66;03m# Validate chunks\u001b[39;00m\n\u001b[0;32m 8\u001b[0m validator \u001b[38;5;241m=\u001b[39m ChunkValidator(\n\u001b[0;32m 9\u001b[0m min_chunk_size\u001b[38;5;241m=\u001b[39m\u001b[38;5;241m50\u001b[39m,\n\u001b[0;32m 10\u001b[0m max_chunk_size\u001b[38;5;241m=\u001b[39m\u001b[38;5;241m300\u001b[39m,\n\u001b[0;32m 11\u001b[0m min_overlap\u001b[38;5;241m=\u001b[39m\u001b[38;5;241m20\u001b[39m,\n\u001b[0;32m 12\u001b[0m max_overlap\u001b[38;5;241m=\u001b[39m\u001b[38;5;241m100\u001b[39m\n\u001b[0;32m 13\u001b[0m )\n\u001b[1;32m---> 15\u001b[0m validation_result \u001b[38;5;241m=\u001b[39m \u001b[43mvalidator\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mvalidate\u001b[49m\u001b[43m(\u001b[49m\u001b[43mchunks\u001b[49m\u001b[43m)\u001b[49m\n\u001b[0;32m 17\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mChunk Validation Results:\u001b[39m\u001b[38;5;130;01m\\n\u001b[39;00m\u001b[38;5;124m\"\u001b[39m)\n\u001b[0;32m 18\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m=\u001b[39m\u001b[38;5;124m\"\u001b[39m \u001b[38;5;241m*\u001b[39m \u001b[38;5;241m80\u001b[39m)\n",
+ "File \u001b[1;32m~\\semantica\\semantica\\split\\chunk_validator.py:96\u001b[0m, in \u001b[0;36mChunkValidator.validate\u001b[1;34m(self, chunk, **options)\u001b[0m\n\u001b[0;32m 92\u001b[0m \u001b[38;5;66;03m# Size validation\u001b[39;00m\n\u001b[0;32m 93\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mprogress_tracker\u001b[38;5;241m.\u001b[39mupdate_tracking(\n\u001b[0;32m 94\u001b[0m tracking_id, message\u001b[38;5;241m=\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mValidating chunk size...\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[0;32m 95\u001b[0m )\n\u001b[1;32m---> 96\u001b[0m chunk_size \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mlen\u001b[39m(\u001b[43mchunk\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mtext\u001b[49m)\n\u001b[0;32m 97\u001b[0m metrics[\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124msize\u001b[39m\u001b[38;5;124m\"\u001b[39m] \u001b[38;5;241m=\u001b[39m chunk_size\n\u001b[0;32m 99\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m chunk_size \u001b[38;5;241m<\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mmin_size:\n",
+ "\u001b[1;31mAttributeError\u001b[0m: 'list' object has no attribute 'text'"
+ ]
+ }
+ ],
"source": [
"from semantica.split import ChunkValidator\n",
"\n",
@@ -976,9 +1146,21 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 14,
"metadata": {},
- "outputs": [],
+ "outputs": [
+ {
+ "ename": "AttributeError",
+ "evalue": "'ProvenanceTracker' object has no attribute 'track'",
+ "output_type": "error",
+ "traceback": [
+ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
+ "\u001b[1;31mAttributeError\u001b[0m Traceback (most recent call last)",
+ "Cell \u001b[1;32mIn[14], line 11\u001b[0m\n\u001b[0;32m 8\u001b[0m tracker \u001b[38;5;241m=\u001b[39m ProvenanceTracker()\n\u001b[0;32m 10\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m chunk \u001b[38;5;129;01min\u001b[39;00m chunks:\n\u001b[1;32m---> 11\u001b[0m \u001b[43mtracker\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mtrack\u001b[49m(\n\u001b[0;32m 12\u001b[0m chunk\u001b[38;5;241m=\u001b[39mchunk,\n\u001b[0;32m 13\u001b[0m source\u001b[38;5;241m=\u001b[39m{\n\u001b[0;32m 14\u001b[0m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mdocument_id\u001b[39m\u001b[38;5;124m\"\u001b[39m: \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mapple_doc_001\u001b[39m\u001b[38;5;124m\"\u001b[39m,\n\u001b[0;32m 15\u001b[0m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mfile_path\u001b[39m\u001b[38;5;124m\"\u001b[39m: \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mdata/apple.txt\u001b[39m\u001b[38;5;124m\"\u001b[39m,\n\u001b[0;32m 16\u001b[0m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mtimestamp\u001b[39m\u001b[38;5;124m\"\u001b[39m: \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m2024-01-01T00:00:00Z\u001b[39m\u001b[38;5;124m\"\u001b[39m,\n\u001b[0;32m 17\u001b[0m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mmethod\u001b[39m\u001b[38;5;124m\"\u001b[39m: \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mrecursive\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[0;32m 18\u001b[0m }\n\u001b[0;32m 19\u001b[0m )\n\u001b[0;32m 21\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mProvenance Tracking Results:\u001b[39m\u001b[38;5;130;01m\\n\u001b[39;00m\u001b[38;5;124m\"\u001b[39m)\n\u001b[0;32m 22\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m=\u001b[39m\u001b[38;5;124m\"\u001b[39m \u001b[38;5;241m*\u001b[39m \u001b[38;5;241m80\u001b[39m)\n",
+ "\u001b[1;31mAttributeError\u001b[0m: 'ProvenanceTracker' object has no attribute 'track'"
+ ]
+ }
+ ],
"source": [
"from semantica.split import ProvenanceTracker\n",
"\n",
@@ -1033,9 +1215,26 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 15,
"metadata": {},
- "outputs": [],
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Method Comparison:\n",
+ "\n",
+ "================================================================================\n",
+ "Method Chunks Avg Size Time (ms) \n",
+ "--------------------------------------------------------------------------------\n",
+ "recursive 8 154 0.00 \n",
+ "sentence 6 148 519.51 \n",
+ "paragraph 3 297 0.00 \n",
+ "token 51 129 0.00 \n",
+ "================================================================================\n"
+ ]
+ }
+ ],
"source": [
"import time\n",
"\n",
diff --git a/semantica/split/chunk_validator.py b/semantica/split/chunk_validator.py
index 795f0f4b..a5c65419 100644
--- a/semantica/split/chunk_validator.py
+++ b/semantica/split/chunk_validator.py
@@ -29,7 +29,7 @@ License: MIT
"""
from dataclasses import dataclass, field
-from typing import Any, Dict, List, Optional
+from typing import Any, Dict, List, Optional, Union
from ..utils.exceptions import ProcessingError
from ..utils.logging import get_logger
@@ -47,6 +47,16 @@ class ValidationResult:
warnings: List[str] = field(default_factory=list)
metrics: Dict[str, Any] = field(default_factory=dict)
+ def get(self, key: str, default: Any = None) -> Any:
+ """Get attribute or metric value (dict-like access)."""
+ if hasattr(self, key):
+ return getattr(self, key)
+ return self.metrics.get(key, default)
+
+ def __getitem__(self, key: str) -> Any:
+ """Get item (dict-like access)."""
+ return self.get(key)
+
class ChunkValidator:
"""Chunk validator for quality assessment."""
@@ -69,17 +79,20 @@ class ChunkValidator:
self.max_size = config.get("max_size", 10000)
self.min_score = config.get("min_score", 0.5)
- def validate(self, chunk: Chunk, **options) -> ValidationResult:
+ def validate(self, chunk: Union[Chunk, List[Chunk]], **options) -> ValidationResult:
"""
- Validate a single chunk.
+ Validate a chunk or list of chunks.
Args:
- chunk: Chunk to validate
+ chunk: Chunk or list of chunks to validate
**options: Validation options
Returns:
- ValidationResult: Validation result
+ ValidationResult: Validation result (aggregated if list)
"""
+ if isinstance(chunk, list):
+ return self._validate_batch(chunk, **options)
+
tracking_id = self.progress_tracker.start_tracking(
module="split", submodule="ChunkValidator", message="Validating chunk"
)
@@ -196,6 +209,36 @@ class ChunkValidator:
},
}
+ def _validate_batch(self, chunks: List[Chunk], **options) -> ValidationResult:
+ """Validate a batch of chunks."""
+ results = []
+ all_errors = []
+ all_warnings = []
+
+ for chunk in chunks:
+ result = self.validate(chunk, **options)
+ results.append(result)
+ if not result.valid:
+ all_errors.extend(result.errors)
+ all_warnings.extend(result.warnings)
+
+ avg_score = sum(r.score for r in results) / len(results) if results else 0.0
+ valid_count = sum(1 for r in results if r.valid)
+ overall_valid = valid_count == len(results)
+
+ return ValidationResult(
+ valid=overall_valid,
+ score=avg_score,
+ errors=all_errors,
+ warnings=all_warnings,
+ metrics={
+ "total_chunks": len(results),
+ "valid_chunks": valid_count,
+ "invalid_chunks": len(results) - valid_count,
+ "quality_score": avg_score # For compatibility
+ }
+ )
+
def _check_coherence(self, text: str) -> float:
"""
Check semantic coherence of text.
diff --git a/semantica/split/provenance_tracker.py b/semantica/split/provenance_tracker.py
index c8dd936a..a45e991a 100644
--- a/semantica/split/provenance_tracker.py
+++ b/semantica/split/provenance_tracker.py
@@ -28,7 +28,7 @@ License: MIT
"""
from dataclasses import dataclass, field
-from typing import Any, Dict, List, Optional
+from typing import Any, Dict, List, Optional, Union
from uuid import uuid4
from ..utils.exceptions import ProcessingError
@@ -117,6 +117,19 @@ class ProvenanceTracker:
return provenance_id
+ def track(self, **kwargs) -> Union[str, List[str]]:
+ """
+ Track provenance (alias for track_chunk/track_chunks).
+ Delegates based on input arguments.
+ """
+ if "chunks" in kwargs:
+ return self.track_chunks(**kwargs)
+ if "chunk" in kwargs and isinstance(kwargs["chunk"], list):
+ # Handle list passed to chunk arg
+ kwargs["chunks"] = kwargs.pop("chunk")
+ return self.track_chunks(**kwargs)
+ return self.track_chunk(**kwargs)
+
def track_chunks(
self,
chunks: List[Chunk],
@@ -223,6 +236,60 @@ class ProvenanceTracker:
return lineage
+ def get_lineage(self, chunk_id: str) -> Dict[str, Any]:
+ """
+ Get lineage info in format expected by some consumers.
+ Adapts internal representation to dict with 'source' key.
+ """
+ lineage_list = self.get_chunk_lineage(chunk_id)
+ if not lineage_list:
+ return {}
+
+ # Return the most recent provenance info (the chunk itself)
+ # wrapped in a structure that matches notebook expectation
+ latest_prov = lineage_list[-1] # List is parent -> child (wait, let me check get_chunk_lineage implementation)
+ # get_chunk_lineage inserts at 0, so [grandparent, parent, child].
+ # But wait, logic: lineage.insert(0, provenance) while walking up parents.
+ # So index 0 is oldest ancestor?
+ # Let's re-read get_chunk_lineage logic.
+
+ # Logic:
+ # current = chunk_id
+ # while current:
+ # prov = get(current)
+ # lineage.insert(0, prov)
+ # current = prov.parent
+
+ # So if we have C -> B -> A (A is parent of B, B is parent of C)
+ # 1. current=C. prov=C. lineage=[C]. current=B.
+ # 2. current=B. prov=B. lineage=[B, C]. current=A.
+ # 3. current=A. prov=A. lineage=[A, B, C]. current=None.
+ # So list is [Oldest, ..., Newest].
+
+ # The notebook wants source info.
+ # The chunk's immediate provenance info contains the source document/path.
+ # So we want the info for the chunk itself (which is the last element).
+
+ # Note: if lineage list is empty (shouldn't happen if chunk exists), return empty.
+ # Actually, get_chunk_lineage calls get_provenance(chunk_id) first.
+
+ if not lineage_list:
+ return {}
+
+ # Use the provenance info of the chunk itself
+ prov = lineage_list[-1]
+
+ return {
+ "source": {
+ "document_id": prov.source_document,
+ "file_path": prov.source_path,
+ "timestamp": prov.timestamp,
+ "method": prov.metadata.get("method"), # method is often in metadata
+ **prov.metadata
+ },
+ "lineage_chain": [self._provenance_to_dict(p) for p in lineage_list]
+ }
+
def link_chunks(
self, chunk_id1: str, chunk_id2: str, relationship: str = "related"
) -> bool:
diff --git a/semantica/split/table_chunker.py b/semantica/split/table_chunker.py
index 9a8f2da5..9d16d5c6 100644
--- a/semantica/split/table_chunker.py
+++ b/semantica/split/table_chunker.py
@@ -68,6 +68,49 @@ class TableChunker:
self.preserve_headers = config.get("preserve_headers", True)
self.chunk_by_columns = config.get("chunk_by_columns", False)
+ def chunk(self, text: str) -> List[Chunk]:
+ """
+ Chunk text containing a table (alias for compatibility).
+ Attempts to parse markdown table from text.
+
+ Args:
+ text: Text containing a markdown table
+
+ Returns:
+ list: List of text chunks
+ """
+ # Simple markdown table parser
+ lines = text.strip().split("\n")
+ headers = []
+ rows = []
+
+ # Find header line (starts with | and not a separator line)
+ header_idx = -1
+ for i, line in enumerate(lines):
+ if line.strip().startswith("|") and "---" not in line:
+ headers = [c.strip() for c in line.strip().strip("|").split("|")]
+ header_idx = i
+ break
+
+ if header_idx != -1:
+ # Parse rows
+ for line in lines[header_idx + 1:]:
+ if line.strip().startswith("|") and "---" not in line:
+ row = [c.strip() for c in line.strip().strip("|").split("|")]
+ if len(row) == len(headers):
+ rows.append(row)
+
+ table_data = {"headers": headers, "rows": rows}
+ return self.chunk_to_text_chunks(table_data)
+
+ # If no table found, return as single chunk
+ return [Chunk(
+ text=text,
+ start_index=0,
+ end_index=len(text),
+ metadata={"chunk_type": "text", "error": "No table found"}
+ )]
+
def chunk_table(
self, table_data: Union[Dict[str, Any], List[List[str]]], **options
) -> List[TableChunk]:
diff --git a/semantica/utils/progress_tracker.py b/semantica/utils/progress_tracker.py
index 6858888b..42bd4fae 100644
--- a/semantica/utils/progress_tracker.py
+++ b/semantica/utils/progress_tracker.py
@@ -93,6 +93,17 @@ class ConsoleProgressDisplay(ProgressDisplay):
def __init__(self, use_emoji: bool = True, update_interval: float = 0.1):
self.use_emoji = use_emoji
+
+ # Check if stdout supports emojis (especially on Windows)
+ if self.use_emoji:
+ try:
+ # Try encoding a test emoji with stdout's encoding
+ encoding = getattr(sys.stdout, "encoding", None)
+ if encoding:
+ "🧠".encode(encoding)
+ except (UnicodeEncodeError, LookupError, AttributeError):
+ self.use_emoji = False
+
self.update_interval = update_interval
self.last_update = 0.0
self.current_lines: Dict[str, str] = {}
@@ -192,6 +203,17 @@ class ConsoleProgressDisplay(ProgressDisplay):
action = action_map.get(module or "", "is processing")
return f"Semantica {action}"
+ def _safe_write(self, text: str) -> None:
+ """Safely write text to stdout handling encoding errors."""
+ try:
+ sys.stdout.write(text)
+ except UnicodeEncodeError:
+ # Fallback: encode with replacement and write decoded
+ # Use ascii as safe fallback if encoding is unknown or caused error
+ encoding = getattr(sys.stdout, "encoding", None) or "ascii"
+ safe_text = text.encode(encoding, errors="replace").decode(encoding)
+ sys.stdout.write(safe_text)
+
def update(self, item: ProgressItem) -> None:
"""Update console progress display."""
if not self._should_update():
@@ -243,27 +265,27 @@ class ConsoleProgressDisplay(ProgressDisplay):
self.current_lines[key] = line
# Print all current lines (overwrite previous)
- sys.stdout.write("\r" + " " * 100 + "\r") # Clear line
+ self._safe_write("\r" + " " * 100 + "\r") # Clear line
if len(self.current_lines) == 1:
- sys.stdout.write(line)
+ self._safe_write(line)
else:
# Multiple items - show all
lines_list = list(self.current_lines.values())
- sys.stdout.write("\n".join(lines_list[-3:])) # Show last 3
+ self._safe_write("\n".join(lines_list[-3:])) # Show last 3
sys.stdout.flush()
def show_summary(self, items: List[ProgressItem]) -> None:
"""Show final summary."""
with self.lock:
# Clear current display
- sys.stdout.write("\n" + "=" * 80 + "\n")
+ self._safe_write("\n" + "=" * 80 + "\n")
# Summary header
if self.use_emoji:
- sys.stdout.write("🧠 Semantica - πŸ“Š Progress Summary\n")
+ self._safe_write("🧠 Semantica - πŸ“Š Progress Summary\n")
else:
- sys.stdout.write("Semantica - Progress Summary\n")
- sys.stdout.write("=" * 80 + "\n")
+ self._safe_write("Semantica - Progress Summary\n")
+ self._safe_write("=" * 80 + "\n")
# Group by module
by_module: Dict[str, List[ProgressItem]] = {}
@@ -281,10 +303,10 @@ class ConsoleProgressDisplay(ProgressDisplay):
for module, module_items in by_module.items():
if self.use_emoji:
emoji = self._get_emoji_for_module(module)
- sys.stdout.write(f"\n{emoji} {module.upper()}\n")
+ self._safe_write(f"\n{emoji} {module.upper()}\n")
else:
- sys.stdout.write(f"\n{module.upper()}\n")
- sys.stdout.write("-" * 80 + "\n")
+ self._safe_write(f"\n{module.upper()}\n")
+ self._safe_write("-" * 80 + "\n")
for item in module_items:
status_emoji = self._get_status_emoji(item.status)
@@ -298,7 +320,8 @@ class ConsoleProgressDisplay(ProgressDisplay):
if item.file:
line += f" - {Path(item.file).name}"
line += duration
- sys.stdout.write(line + "\n")
+
+ self._safe_write(line + "\n")
if item.status == "completed":
completed += 1
@@ -309,22 +332,22 @@ class ConsoleProgressDisplay(ProgressDisplay):
total_time += item.end_time - item.start_time
# Final stats
- sys.stdout.write("\n" + "=" * 80 + "\n")
+ self._safe_write("\n" + "=" * 80 + "\n")
if self.use_emoji:
- sys.stdout.write(
+ self._safe_write(
f"βœ… Completed: {completed} | ❌ Failed: {failed} | ⏱️ Total Time: {total_time:.2f}s\n"
)
else:
- sys.stdout.write(
+ self._safe_write(
f"Completed: {completed} | Failed: {failed} | Total Time: {total_time:.2f}s\n"
)
- sys.stdout.write("=" * 80 + "\n")
+ self._safe_write("=" * 80 + "\n")
sys.stdout.flush()
def clear(self) -> None:
"""Clear console display."""
with self.lock:
- sys.stdout.write("\r" + " " * 100 + "\r")
+ self._safe_write("\r" + " " * 100 + "\r")
sys.stdout.flush()
self.current_lines.clear()