Class: SemanticTextChunker::BoundaryDetector
- Inherits:
-
Object
- Object
- SemanticTextChunker::BoundaryDetector
- Defined in:
- lib/semantic_text_chunker/boundary_detector.rb
Instance Method Summary collapse
-
#boundaries ⇒ Object
Returns array of sentence indices where chunks end.
-
#initialize(sentences:, embeddings:, threshold:, max_tokens:, embedder:, forced: []) ⇒ BoundaryDetector
constructor
A new instance of BoundaryDetector.
Constructor Details
#initialize(sentences:, embeddings:, threshold:, max_tokens:, embedder:, forced: []) ⇒ BoundaryDetector
Returns a new instance of BoundaryDetector.
5 6 7 8 9 10 11 12 |
# File 'lib/semantic_text_chunker/boundary_detector.rb', line 5 def initialize(sentences:, embeddings:, threshold:, max_tokens:, embedder:, forced: []) @sentences = sentences @embeddings = @threshold = threshold @max_tokens = max_tokens @embedder = @forced = forced.to_set end |
Instance Method Details
#boundaries ⇒ Object
Returns array of sentence indices where chunks end
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 |
# File 'lib/semantic_text_chunker/boundary_detector.rb', line 15 def boundaries return [] if @sentences.size <= 1 boundaries = [] chunk_start = 0 @sentences.each_with_index do |sentence, i| next if i == 0 # Hard structural boundary: the previous sentence ended a block, so the # chunk must end there regardless of similarity or token count. if @forced.include?(i - 1) boundaries << (i - 1) unless boundaries.last == (i - 1) chunk_start = i next end current_text = @sentences[chunk_start..i - 1].join(" ") next_text = current_text + " " + sentence # Force boundary if adding this sentence exceeds token limit if tokens(next_text) > @max_tokens boundaries << i - 1 chunk_start = i next end # Compute similarity between accumulated chunk and next sentence = (@embeddings[chunk_start..i - 1]) = @embeddings[i] similarity = @embedder.cosine_similarity(, ) if similarity < @threshold boundaries << i - 1 chunk_start = i end end boundaries end |