forked from HKUDS/DeepCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdocument_segmentation_server.py
More file actions
1937 lines (1650 loc) · 70.7 KB
/
document_segmentation_server.py
File metadata and controls
1937 lines (1650 loc) · 70.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Document Segmentation MCP Server
This MCP server provides intelligent document segmentation and retrieval functions for handling
large research papers and technical documents that exceed LLM token limits.
==== CORE FUNCTIONALITY ====
1. Analyze document structure and type using semantic content analysis
2. Create intelligent segments based on content semantics, not just structure
3. Provide query-aware segment retrieval with relevance scoring
4. Support both structured (papers with headers) and unstructured documents
5. Configurable segmentation strategies based on document complexity
==== MCP TOOLS PROVIDED ====
📄 analyze_and_segment_document(paper_dir: str, force_refresh: bool = False)
Purpose: Analyzes document structure and creates intelligent segments
- Detects document type (research paper, technical doc, algorithm-focused, etc.)
- Selects optimal segmentation strategy based on content analysis
- Creates semantic segments preserving algorithm and concept integrity
- Stores segmentation index for efficient retrieval
- Returns: JSON with segmentation status, strategy used, and segment count
📖 read_document_segments(paper_dir: str, query_type: str, keywords: List[str] = None,
max_segments: int = 3, max_total_chars: int = None)
Purpose: Intelligently retrieves relevant document segments based on query context
- query_type: "concept_analysis", "algorithm_extraction", or "code_planning"
- Uses semantic relevance scoring to rank segments
- Applies query-specific filtering and keyword matching
- Dynamically calculates optimal character limits based on content complexity
- Returns: JSON with selected segments optimized for the specific query type
📋 get_document_overview(paper_dir: str)
Purpose: Provides high-level overview of document structure and available segments
- Shows document type and segmentation strategy used
- Lists all segments with titles, content types, and relevance scores
- Displays segment statistics (character counts, keyword summaries)
- Returns: JSON with complete document analysis metadata
==== SEGMENTATION STRATEGIES ====
- semantic_research_focused: For academic papers with complex algorithmic content
- algorithm_preserve_integrity: Maintains algorithm blocks and formula chains intact
- concept_implementation_hybrid: Merges related concepts with implementation details
- semantic_chunking_enhanced: Advanced boundary detection for long documents
- content_aware_segmentation: Adaptive chunking based on content density
==== INTELLIGENT FEATURES ====
- Semantic boundary detection (not just structural)
- Algorithm block identification and preservation
- Formula chain recognition and grouping
- Concept-implementation relationship mapping
- Multi-level relevance scoring (content type, importance, keyword matching)
- Backward compatibility with existing document indexes
- Configurable via mcp_agent.config.yaml (enabled/disabled, size thresholds)
Usage:
python tools/document_segmentation_server.py
"""
import os
import re
import json
import sys
import io
from typing import Dict, List, Tuple
import hashlib
import logging
from datetime import datetime
from dataclasses import dataclass, asdict
# Set standard output encoding to UTF-8
if sys.stdout.encoding != "utf-8":
try:
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8")
sys.stderr.reconfigure(encoding="utf-8")
else:
sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding="utf-8")
sys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding="utf-8")
except Exception as e:
print(f"Warning: Could not set UTF-8 encoding: {e}")
# Import MCP related modules
from mcp.server.fastmcp import FastMCP
# Setup logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Create FastMCP server instance
mcp = FastMCP("document-segmentation-server")
@dataclass
class DocumentSegment:
"""Represents a document segment with metadata"""
id: str
title: str
content: str
content_type: str # "introduction", "methodology", "algorithm", "results", etc.
keywords: List[str]
char_start: int
char_end: int
char_count: int
relevance_scores: Dict[str, float] # Scores for different query types
section_path: str # e.g., "3.2.1" for nested sections
@dataclass
class DocumentIndex:
"""Document index containing all segments and metadata"""
document_path: str
document_type: str # "academic_paper", "technical_doc", "code_doc", "general"
segmentation_strategy: str
total_segments: int
total_chars: int
segments: List[DocumentSegment]
created_at: str
class DocumentAnalyzer:
"""Enhanced document analyzer using semantic content analysis instead of mechanical structure detection"""
# More precise semantic indicators, weighted by importance
ALGORITHM_INDICATORS = {
"high": [
"algorithm",
"procedure",
"method",
"approach",
"technique",
"framework",
],
"medium": ["step", "process", "implementation", "computation", "calculation"],
"low": ["example", "illustration", "demonstration"],
}
TECHNICAL_CONCEPT_INDICATORS = {
"high": ["formula", "equation", "theorem", "lemma", "proof", "definition"],
"medium": ["parameter", "variable", "function", "model", "architecture"],
"low": ["notation", "symbol", "term"],
}
IMPLEMENTATION_INDICATORS = {
"high": ["code", "implementation", "programming", "software", "system"],
"medium": ["design", "structure", "module", "component", "interface"],
"low": ["tool", "library", "package"],
}
# Semantic features of document types (not just based on titles)
RESEARCH_PAPER_PATTERNS = [
r"(?i)\babstract\b.*?\n.*?(introduction|motivation|background)",
r"(?i)(methodology|method).*?(experiment|evaluation|result)",
r"(?i)(conclusion|future work|limitation).*?(reference|bibliography)",
r"(?i)(related work|literature review|prior art)",
]
TECHNICAL_DOC_PATTERNS = [
r"(?i)(getting started|installation|setup).*?(usage|example)",
r"(?i)(api|interface|specification).*?(parameter|endpoint)",
r"(?i)(tutorial|guide|walkthrough).*?(step|instruction)",
r"(?i)(troubleshooting|faq|common issues)",
]
def analyze_document_type(self, content: str) -> Tuple[str, float]:
"""
Enhanced document type analysis based on semantic content patterns
Returns:
Tuple[str, float]: (document_type, confidence_score)
"""
content_lower = content.lower()
# Calculate weighted semantic indicator scores
algorithm_score = self._calculate_weighted_score(
content_lower, self.ALGORITHM_INDICATORS
)
concept_score = self._calculate_weighted_score(
content_lower, self.TECHNICAL_CONCEPT_INDICATORS
)
implementation_score = self._calculate_weighted_score(
content_lower, self.IMPLEMENTATION_INDICATORS
)
# Detect semantic patterns of document types
research_pattern_score = self._detect_pattern_score(
content, self.RESEARCH_PAPER_PATTERNS
)
technical_pattern_score = self._detect_pattern_score(
content, self.TECHNICAL_DOC_PATTERNS
)
# Comprehensive evaluation of document type
total_research_score = (
algorithm_score + concept_score + research_pattern_score * 2
)
total_technical_score = implementation_score + technical_pattern_score * 2
# Determine document type based on content density and pattern matching
if research_pattern_score > 0.5 and total_research_score > 3.0:
return "research_paper", min(0.95, 0.6 + research_pattern_score * 0.35)
elif algorithm_score > 2.0 and concept_score > 1.5:
return "algorithm_focused", 0.85
elif total_technical_score > 2.5:
return "technical_doc", 0.8
elif implementation_score > 1.5:
return "implementation_guide", 0.75
else:
return "general_document", 0.5
def _calculate_weighted_score(
self, content: str, indicators: Dict[str, List[str]]
) -> float:
"""Calculate weighted semantic indicator scores"""
score = 0.0
for weight_level, terms in indicators.items():
weight = {"high": 3.0, "medium": 2.0, "low": 1.0}[weight_level]
for term in terms:
if term in content:
score += weight * (
content.count(term) * 0.5 + 1
) # Consider term frequency
return score
def _detect_pattern_score(self, content: str, patterns: List[str]) -> float:
"""Detect semantic pattern matching scores"""
matches = 0
for pattern in patterns:
if re.search(pattern, content, re.DOTALL):
matches += 1
return matches / len(patterns)
def detect_segmentation_strategy(self, content: str, doc_type: str) -> str:
"""
Intelligently determine the best segmentation strategy based on content semantics rather than mechanical structure
"""
# Analyze content characteristics
algorithm_density = self._calculate_algorithm_density(content)
concept_complexity = self._calculate_concept_complexity(content)
implementation_detail_level = self._calculate_implementation_detail_level(
content
)
# Select strategy based on document type and content characteristics
if doc_type == "research_paper" and algorithm_density > 0.3:
return "semantic_research_focused"
elif doc_type == "algorithm_focused" or algorithm_density > 0.5:
return "algorithm_preserve_integrity"
elif concept_complexity > 0.4 and implementation_detail_level > 0.3:
return "concept_implementation_hybrid"
elif len(content) > 15000: # Long documents
return "semantic_chunking_enhanced"
else:
return "content_aware_segmentation"
def _calculate_algorithm_density(self, content: str) -> float:
"""Calculate algorithm content density"""
total_chars = len(content)
algorithm_chars = 0
# Identify algorithm blocks
algorithm_patterns = [
r"(?i)(algorithm\s+\d+|procedure\s+\d+)",
r"(?i)(step\s+\d+|phase\s+\d+)",
r"(?i)(input:|output:|return:|initialize:)",
r"(?i)(for\s+each|while|if.*then|else)",
r"(?i)(function|method|procedure).*\(",
]
for pattern in algorithm_patterns:
matches = re.finditer(pattern, content)
for match in matches:
# Estimate algorithm block size (expand forward and backward from match point)
start = max(0, match.start() - 200)
end = min(len(content), match.end() + 800)
algorithm_chars += end - start
return min(1.0, algorithm_chars / total_chars)
def _calculate_concept_complexity(self, content: str) -> float:
"""Calculate concept complexity"""
concept_indicators = self.TECHNICAL_CONCEPT_INDICATORS
complexity_score = 0.0
for level, terms in concept_indicators.items():
weight = {"high": 3.0, "medium": 2.0, "low": 1.0}[level]
for term in terms:
complexity_score += content.lower().count(term) * weight
# Normalize to 0-1 range
return min(1.0, complexity_score / 100)
def _calculate_implementation_detail_level(self, content: str) -> float:
"""Calculate implementation detail level"""
implementation_patterns = [
r"(?i)(code|implementation|programming)",
r"(?i)(class|function|method|variable)",
r"(?i)(import|include|library)",
r"(?i)(parameter|argument|return)",
r"(?i)(example|demo|tutorial)",
]
detail_score = 0
for pattern in implementation_patterns:
detail_score += len(re.findall(pattern, content))
return min(1.0, detail_score / 50)
class DocumentSegmenter:
"""Creates intelligent segments from documents"""
def __init__(self):
self.analyzer = DocumentAnalyzer()
def segment_document(self, content: str, strategy: str) -> List[DocumentSegment]:
"""
Perform intelligent segmentation using the specified strategy
"""
if strategy == "semantic_research_focused":
return self._segment_research_paper_semantically(content)
elif strategy == "algorithm_preserve_integrity":
return self._segment_preserve_algorithm_integrity(content)
elif strategy == "concept_implementation_hybrid":
return self._segment_concept_implementation_hybrid(content)
elif strategy == "semantic_chunking_enhanced":
return self._segment_by_enhanced_semantic_chunks(content)
elif strategy == "content_aware_segmentation":
return self._segment_content_aware(content)
else:
# Compatibility with legacy strategies
return self._segment_by_enhanced_semantic_chunks(content)
def _segment_by_headers(self, content: str) -> List[DocumentSegment]:
"""Segment document based on markdown headers"""
segments = []
lines = content.split("\n")
current_segment = []
current_header = None
char_pos = 0
for line in lines:
line_with_newline = line + "\n"
# Check if line is a header
header_match = re.match(r"^(#{1,6})\s+(.+)$", line)
if header_match:
# Save previous segment if exists
if current_segment and current_header:
segment_content = "\n".join(current_segment).strip()
if segment_content:
# Analyze content type and importance
content_type = self._classify_content_type(
current_header, segment_content
)
importance_score = (
0.8 if content_type in ["algorithm", "formula"] else 0.7
)
segment = self._create_enhanced_segment(
segment_content,
current_header,
char_pos - len(segment_content.encode("utf-8")),
char_pos,
importance_score,
content_type,
)
segments.append(segment)
# Start new segment
current_header = header_match.group(2).strip()
current_segment = [line]
else:
if current_segment is not None:
current_segment.append(line)
char_pos += len(line_with_newline.encode("utf-8"))
# Add final segment
if current_segment and current_header:
segment_content = "\n".join(current_segment).strip()
if segment_content:
# Analyze content type and importance
content_type = self._classify_content_type(
current_header, segment_content
)
importance_score = (
0.8 if content_type in ["algorithm", "formula"] else 0.7
)
segment = self._create_enhanced_segment(
segment_content,
current_header,
char_pos - len(segment_content.encode("utf-8")),
char_pos,
importance_score,
content_type,
)
segments.append(segment)
return segments
def _segment_preserve_algorithm_integrity(
self, content: str
) -> List[DocumentSegment]:
"""Smart segmentation strategy that preserves algorithm integrity"""
segments = []
# 1. Identify algorithm blocks and related descriptions
algorithm_blocks = self._identify_algorithm_blocks(content)
# 2. Identify concept definition groups
concept_groups = self._identify_concept_groups(content)
# 3. Identify formula derivation chains
formula_chains = self._identify_formula_chains(content)
# 4. Merge related content blocks to ensure integrity
content_blocks = self._merge_related_content_blocks(
algorithm_blocks, concept_groups, formula_chains, content
)
# 5. Convert to DocumentSegment
for i, block in enumerate(content_blocks):
segment = self._create_enhanced_segment(
block["content"],
block["title"],
block["start_pos"],
block["end_pos"],
block["importance_score"],
block["content_type"],
)
segments.append(segment)
return segments
def _segment_research_paper_semantically(
self, content: str
) -> List[DocumentSegment]:
"""Semantic segmentation specifically for research papers"""
segments = []
# Identify semantic structure of research papers
paper_sections = self._identify_research_paper_sections(content)
for section in paper_sections:
# Ensure each section contains sufficient context
enhanced_content = self._enhance_section_with_context(section, content)
segment = self._create_enhanced_segment(
enhanced_content["content"],
enhanced_content["title"],
enhanced_content["start_pos"],
enhanced_content["end_pos"],
enhanced_content["importance_score"],
enhanced_content["content_type"],
)
segments.append(segment)
return segments
def _segment_concept_implementation_hybrid(
self, content: str
) -> List[DocumentSegment]:
"""Intelligent segmentation combining concepts and implementation"""
segments = []
# Identify concept-implementation correspondence
concept_impl_pairs = self._identify_concept_implementation_pairs(content)
for pair in concept_impl_pairs:
# Merge related concepts and implementations into one segment
merged_content = self._merge_concept_with_implementation(pair, content)
segment = self._create_enhanced_segment(
merged_content["content"],
merged_content["title"],
merged_content["start_pos"],
merged_content["end_pos"],
merged_content["importance_score"],
merged_content["content_type"],
)
segments.append(segment)
return segments
def _segment_by_enhanced_semantic_chunks(
self, content: str
) -> List[DocumentSegment]:
"""Enhanced semantic chunk segmentation"""
segments = []
# Use improved semantic boundary detection
semantic_boundaries = self._detect_semantic_boundaries(content)
current_start = 0
for i, boundary in enumerate(semantic_boundaries):
chunk_content = content[current_start : boundary["position"]]
if len(chunk_content.strip()) > 200: # Minimum content threshold
segment = self._create_enhanced_segment(
chunk_content,
boundary["suggested_title"],
current_start,
boundary["position"],
boundary["importance_score"],
boundary["content_type"],
)
segments.append(segment)
current_start = boundary["position"]
# Handle the final segment
if current_start < len(content):
final_content = content[current_start:]
if len(final_content.strip()) > 200:
segment = self._create_enhanced_segment(
final_content,
"Final Section",
current_start,
len(content),
0.7,
"general",
)
segments.append(segment)
return segments
def _segment_content_aware(self, content: str) -> List[DocumentSegment]:
"""Content-aware intelligent segmentation"""
segments = []
# Adaptive segmentation size
optimal_chunk_size = self._calculate_optimal_chunk_size(content)
# Segment based on content density
content_chunks = self._create_content_aware_chunks(content, optimal_chunk_size)
for chunk in content_chunks:
segment = self._create_enhanced_segment(
chunk["content"],
chunk["title"],
chunk["start_pos"],
chunk["end_pos"],
chunk["importance_score"],
chunk["content_type"],
)
segments.append(segment)
return segments
def _segment_academic_paper(self, content: str) -> List[DocumentSegment]:
"""Segment academic paper using semantic understanding"""
# First try header-based segmentation
headers = re.findall(r"^(#{1,6})\s+(.+)$", content, re.MULTILINE)
if len(headers) >= 2:
return self._segment_by_headers(content)
# Fallback to semantic detection of academic sections
sections = self._detect_academic_sections(content)
segments = []
for section in sections:
# Determine importance based on section type
section_type = section.get("type", "general")
content_type = (
section_type
if section_type
in ["algorithm", "formula", "introduction", "conclusion"]
else "general"
)
importance_score = {
"algorithm": 0.95,
"formula": 0.9,
"introduction": 0.85,
"conclusion": 0.8,
}.get(content_type, 0.7)
segment = self._create_enhanced_segment(
section["content"],
section["title"],
section["start_pos"],
section["end_pos"],
importance_score,
content_type,
)
segments.append(segment)
return segments
def _detect_academic_sections(self, content: str) -> List[Dict]:
"""Detect academic paper sections even without clear headers"""
sections = []
# Common academic section patterns
section_patterns = [
(r"(?i)(abstract|摘要)", "introduction"),
(r"(?i)(introduction|引言|简介)", "introduction"),
(r"(?i)(related work|相关工作|背景)", "background"),
(r"(?i)(method|methodology|approach|方法)", "methodology"),
(r"(?i)(algorithm|算法)", "algorithm"),
(r"(?i)(experiment|实验|evaluation|评估)", "experiment"),
(r"(?i)(result|结果|finding)", "results"),
(r"(?i)(conclusion|结论|总结)", "conclusion"),
(r"(?i)(reference|参考文献|bibliography)", "references"),
]
current_pos = 0
for i, (pattern, section_type) in enumerate(section_patterns):
match = re.search(pattern, content[current_pos:], re.IGNORECASE)
if match:
start_pos = current_pos + match.start()
# Find end position (next section or end of document)
next_pos = len(content)
for next_pattern, _ in section_patterns[i + 1 :]:
next_match = re.search(
next_pattern, content[start_pos + 100 :], re.IGNORECASE
)
if next_match:
next_pos = start_pos + 100 + next_match.start()
break
section_content = content[start_pos:next_pos].strip()
if len(section_content) > 50: # Minimum content length
# Calculate importance score and content type
importance_score = self._calculate_paragraph_importance(
section_content, section_type
)
content_type = self._classify_content_type(
match.group(1), section_content
)
sections.append(
{
"title": match.group(1),
"content": section_content,
"start_pos": start_pos,
"end_pos": next_pos,
"type": section_type,
"importance_score": importance_score,
"content_type": content_type,
}
)
current_pos = next_pos
return sections
def _segment_by_semantic_chunks(self, content: str) -> List[DocumentSegment]:
"""Segment long documents into semantic chunks"""
# Split into paragraphs first
paragraphs = [p.strip() for p in content.split("\n\n") if p.strip()]
segments = []
current_chunk = []
current_chunk_size = 0
chunk_size_limit = 3000 # characters
overlap_size = 200
char_pos = 0
for para in paragraphs:
para_size = len(para)
# If adding this paragraph exceeds limit, create a segment
if current_chunk_size + para_size > chunk_size_limit and current_chunk:
chunk_content = "\n\n".join(current_chunk)
# Analyze semantic chunk content type
content_type = self._classify_paragraph_type(chunk_content)
importance_score = self._calculate_paragraph_importance(
chunk_content, content_type
)
segment = self._create_enhanced_segment(
chunk_content,
f"Section {len(segments) + 1}",
char_pos - len(chunk_content.encode("utf-8")),
char_pos,
importance_score,
content_type,
)
segments.append(segment)
# Keep last part for overlap
overlap_content = (
chunk_content[-overlap_size:]
if len(chunk_content) > overlap_size
else ""
)
current_chunk = [overlap_content, para] if overlap_content else [para]
current_chunk_size = len(overlap_content) + para_size
else:
current_chunk.append(para)
current_chunk_size += para_size
char_pos += para_size + 2 # +2 for \n\n
# Add final chunk
if current_chunk:
chunk_content = "\n\n".join(current_chunk)
# Analyze final chunk content type
content_type = self._classify_paragraph_type(chunk_content)
importance_score = self._calculate_paragraph_importance(
chunk_content, content_type
)
segment = self._create_enhanced_segment(
chunk_content,
f"Section {len(segments) + 1}",
char_pos - len(chunk_content.encode("utf-8")),
char_pos,
importance_score,
content_type,
)
segments.append(segment)
return segments
def _segment_by_paragraphs(self, content: str) -> List[DocumentSegment]:
"""Simple paragraph-based segmentation for short documents"""
paragraphs = [p.strip() for p in content.split("\n\n") if p.strip()]
segments = []
char_pos = 0
for i, para in enumerate(paragraphs):
if len(para) > 100: # Only include substantial paragraphs
# Analyze paragraph type and importance
content_type = self._classify_paragraph_type(para)
importance_score = self._calculate_paragraph_importance(
para, content_type
)
segment = self._create_enhanced_segment(
para,
f"Paragraph {i + 1}",
char_pos,
char_pos + len(para.encode("utf-8")),
importance_score,
content_type,
)
segments.append(segment)
char_pos += len(para.encode("utf-8")) + 2
return segments
# =============== Enhanced intelligent segmentation helper methods ===============
def _identify_algorithm_blocks(self, content: str) -> List[Dict]:
"""Identify algorithm blocks and related descriptions"""
algorithm_blocks = []
# Algorithm block identification patterns
algorithm_patterns = [
r"(?i)(algorithm\s+\d+|procedure\s+\d+|method\s+\d+).*?(?=algorithm\s+\d+|procedure\s+\d+|method\s+\d+|$)",
r"(?i)(input:|output:|returns?:|require:|ensure:).*?(?=\n\s*\n|\n\s*(?:input:|output:|returns?:|require:|ensure:)|$)",
r"(?i)(for\s+each|while|if.*then|repeat.*until).*?(?=\n\s*\n|$)",
r"(?i)(step\s+\d+|phase\s+\d+).*?(?=step\s+\d+|phase\s+\d+|\n\s*\n|$)",
]
for pattern in algorithm_patterns:
matches = re.finditer(pattern, content, re.DOTALL)
for match in matches:
# Expand context to include complete descriptions
start = max(0, match.start() - 300)
end = min(len(content), match.end() + 500)
# Find natural boundaries
while start > 0 and content[start] not in "\n.!?":
start -= 1
while end < len(content) and content[end] not in "\n.!?":
end += 1
algorithm_blocks.append(
{
"start_pos": start,
"end_pos": end,
"content": content[start:end].strip(),
"title": self._extract_algorithm_title(
content[match.start() : match.end()]
),
"importance_score": 0.95, # High importance for algorithm blocks
"content_type": "algorithm",
}
)
return algorithm_blocks
def _identify_concept_groups(self, content: str) -> List[Dict]:
"""Identify concept definition groups"""
concept_groups = []
# Concept definition patterns
concept_patterns = [
r"(?i)(definition|define|let|denote|given).*?(?=\n\s*\n|definition|define|let|denote|$)",
r"(?i)(theorem|lemma|proposition|corollary).*?(?=\n\s*\n|theorem|lemma|proposition|corollary|$)",
r"(?i)(notation|symbol|parameter).*?(?=\n\s*\n|notation|symbol|parameter|$)",
]
for pattern in concept_patterns:
matches = re.finditer(pattern, content, re.DOTALL)
for match in matches:
# Expand context
start = max(0, match.start() - 200)
end = min(len(content), match.end() + 300)
concept_groups.append(
{
"start_pos": start,
"end_pos": end,
"content": content[start:end].strip(),
"title": self._extract_concept_title(
content[match.start() : match.end()]
),
"importance_score": 0.85,
"content_type": "concept",
}
)
return concept_groups
def _identify_formula_chains(self, content: str) -> List[Dict]:
"""Identify formula derivation chains"""
formula_chains = []
# Formula patterns
formula_patterns = [
r"\$\$.*?\$\$", # Block-level mathematical formulas
r"\$[^$]+\$", # Inline mathematical formulas
r"(?i)(equation|formula).*?(?=\n\s*\n|equation|formula|$)",
r"(?i)(where|such that|given that).*?(?=\n\s*\n|where|such that|given that|$)",
]
# Find dense formula regions
formula_positions = []
for pattern in formula_patterns:
matches = re.finditer(pattern, content, re.DOTALL)
for match in matches:
formula_positions.append((match.start(), match.end()))
# Merge nearby formulas into formula chains
formula_positions.sort()
if formula_positions:
current_chain_start = formula_positions[0][0]
current_chain_end = formula_positions[0][1]
for start, end in formula_positions[1:]:
if (
start - current_chain_end < 500
): # Merge formulas within 500 characters
current_chain_end = end
else:
# Save current chain
formula_chains.append(
{
"start_pos": max(0, current_chain_start - 200),
"end_pos": min(len(content), current_chain_end + 200),
"content": content[
max(0, current_chain_start - 200) : min(
len(content), current_chain_end + 200
)
].strip(),
"title": "Mathematical Formulation",
"importance_score": 0.9,
"content_type": "formula",
}
)
current_chain_start = start
current_chain_end = end
# Add the last chain
formula_chains.append(
{
"start_pos": max(0, current_chain_start - 200),
"end_pos": min(len(content), current_chain_end + 200),
"content": content[
max(0, current_chain_start - 200) : min(
len(content), current_chain_end + 200
)
].strip(),
"title": "Mathematical Formulation",
"importance_score": 0.9,
"content_type": "formula",
}
)
return formula_chains
def _merge_related_content_blocks(
self,
algorithm_blocks: List[Dict],
concept_groups: List[Dict],
formula_chains: List[Dict],
content: str,
) -> List[Dict]:
"""Merge related content blocks to ensure integrity"""
all_blocks = algorithm_blocks + concept_groups + formula_chains
all_blocks.sort(key=lambda x: x["start_pos"])
merged_blocks = []
i = 0
while i < len(all_blocks):
current_block = all_blocks[i]
# Check if can merge with the next block
while i + 1 < len(all_blocks):
next_block = all_blocks[i + 1]
# If blocks are close or content related, merge them
if next_block["start_pos"] - current_block[
"end_pos"
] < 300 or self._are_blocks_related(current_block, next_block):
# Merge blocks
merged_content = content[
current_block["start_pos"] : next_block["end_pos"]
]
current_block = {
"start_pos": current_block["start_pos"],
"end_pos": next_block["end_pos"],
"content": merged_content.strip(),
"title": f"{current_block['title']} & {next_block['title']}",
"importance_score": max(
current_block["importance_score"],
next_block["importance_score"],
),
"content_type": "merged",
}
i += 1
else:
break
merged_blocks.append(current_block)
i += 1
return merged_blocks
def _are_blocks_related(self, block1: Dict, block2: Dict) -> bool:
"""Determine if two content blocks are related"""
# Check content type associations
related_types = [
("algorithm", "formula"),
("concept", "algorithm"),
("formula", "concept"),
]
for type1, type2 in related_types:
if (
block1["content_type"] == type1 and block2["content_type"] == type2
) or (block1["content_type"] == type2 and block2["content_type"] == type1):
return True
return False
def _extract_algorithm_title(self, text: str) -> str:
"""Extract title from algorithm text"""
lines = text.split("\n")[:3] # First 3 lines
for line in lines:
line = line.strip()
if line and len(line) < 100: # Reasonable title length
# Clean title
title = re.sub(r"[^\w\s-]", "", line)
if title:
return title[:50] # Limit title length
return "Algorithm Block"
def _extract_concept_title(self, text: str) -> str:
"""Extract title from concept text"""
lines = text.split("\n")[:2]
for line in lines:
line = line.strip()
if line and len(line) < 80:
title = re.sub(r"[^\w\s-]", "", line)
if title:
return title[:50]
return "Concept Definition"
def _create_enhanced_segment(
self,
content: str,
title: str,
start_pos: int,
end_pos: int,
importance_score: float,
content_type: str,
) -> DocumentSegment:
"""Create enhanced document segment"""
# Generate unique ID
segment_id = hashlib.md5(
f"{title}_{start_pos}_{end_pos}_{importance_score}".encode()
).hexdigest()[:8]
# Extract keywords
keywords = self._extract_enhanced_keywords(content, content_type)
# Calculate enhanced relevance scores