using System.Linq; using System.Text; using xAiApi.Models; using xAiApi.Interfaces; using xAiApi.Extensions; using xCommons.Extensions; using xAiApi.Configurations; using xExceptions.Constants; using System.Collections.Generic; using System.Text.RegularExpressions; namespace xAiApi.Providers { /// /// Splits Long Texts into Overlapping Chunks using a Hierarchical Strategy: /// Paragraphs -> Sentences -> Words -> Hard Cut ... /// public class XTextChunker : IXTextChunker { /// /// Default Options which used when no Options Provided ... /// private readonly XAiApiConfiguration configuration; /// /// Matches Paragraph Boundaries (two or more Line Breaks) ... /// private static readonly Regex ParagraphSplitter = new( @"\n\s*\n+", RegexOptions.Compiled ); /// /// Matches Sentence Boundaries, Supports Latin, Persian and CJK Terminators ... /// private static readonly Regex SentenceSplitter = new( @"(?<=[\.\!\?؟。!?])\s+|(?<=\n)", RegexOptions.Compiled ); /// /// Matches Repeated Horizontal Whitespaces ... /// private static readonly Regex HorizontalWhitespace = new( @"[ \t\f\v\u00A0]{2,}", RegexOptions.Compiled ); /// /// Matches Three or more Line Breaks ... /// private static readonly Regex ExcessiveLineBreaks = new( @"\n{3,}", RegexOptions.Compiled ); public XTextChunker( XAiApiConfiguration configuration ) { // // Validate Configuration ... if ( !configuration.IsValid() || !configuration.TextChunker.IsValid() ) { XException.InvalidConfiguration.Throw(); } // this.configuration = configuration; } /// /// Split Text into Chunks ... /// /// /// /// public IList Chunk( string text, string source = null ) { // var result = new List(); if (text.IsNullOrEmpty() || string.IsNullOrWhiteSpace(text)) { return result; } // // Normalize ... var normalized = configuration.TextChunker.NormalizeWhitespace ? Normalize(text) : text; // // Short Circuit for Small Texts ... if (normalized.Length <= configuration.TextChunker.ChunkSize) { // result.Add(CreateChunk(normalized, 0, 0, source)); return result; } // // Build Atomic Units (never larger than ChunkSize) ... var units = BuildUnits(normalized); // // Accumulate Units into Chunks with Overlap ... var chunks = Accumulate(units); // // Merge too Small Tail Chunks ... chunks = MergeSmallChunks(chunks); // for (var i = 0; i < chunks.Count; i++) { result.Add(CreateChunk(chunks[i].Text, chunks[i].Offset, i, source)); } // return result; } /// /// Split Text into Chunks and Return only Texts ... /// /// /// public IList ChunkTexts(string text) { // var result = Chunk(text, null) .Select(c => c.Text) .ToList(); // return result; } // #region Private ... /// /// Internal Text Unit with its Offset in Normalized Source ... /// private readonly struct Unit { public Unit(string text, int offset) { Text = text; Offset = offset; } public string Text { get; } public int Offset { get; } } /// /// Normalize Line Endings and Whitespaces ... /// /// /// private string Normalize(string text) { // var result = text .Replace("\r\n", "\n") .Replace('\r', '\n'); // result = HorizontalWhitespace.Replace(result, " "); result = ExcessiveLineBreaks.Replace(result, "\n\n"); // result = result.Trim(); // return result; } /// /// Create Chunk Model ... /// /// /// /// /// /// private XTextChunk CreateChunk( string text, int offset, int index, string source ) { // var identifier = source.IsNullOrEmpty() ? index.ToString() : $"{source}{configuration.TextChunker.ChunkIdentifierSeparator}{index}"; // var result = new XTextChunk { Text = text, Index = index, Source = source, StartOffset = offset, Identifier = identifier }; // return result; } /// /// Split Text into Atomic Units; each Unit Guaranteed to fit in ChunkSize ... /// /// /// private List BuildUnits(string text) { // var result = new List(); // foreach (var paragraph in SplitWithOffsets(text, ParagraphSplitter, 0)) { // if (paragraph.Text.Length <= configuration.TextChunker.ChunkSize) { // result.Add(paragraph); continue; } // // Paragraph too Long -> Sentences ... foreach (var sentence in SplitWithOffsets(paragraph.Text, SentenceSplitter, paragraph.Offset)) { // if (sentence.Text.Length <= configuration.TextChunker.ChunkSize) { // result.Add(sentence); continue; } // // Sentence too Long -> Word Boundary Hard Cut ... result.AddRange(HardSplit(sentence, configuration.TextChunker.ChunkSize)); } } // return result; } /// /// Split Text by Regex while Tracking Offsets, Skipping Empty Parts ... /// /// /// /// /// private IEnumerable SplitWithOffsets( string text, Regex splitter, int baseOffset ) { // var position = 0; foreach (Match match in splitter.Matches(text)) { // var part = text.Substring(position, match.Index - position); var unit = TrimUnit(part, baseOffset + position); if (!unit.Text.IsNullOrEmpty()) { yield return unit; } // position = match.Index + match.Length; } // if (position < text.Length) { // var tail = TrimUnit(text.Substring(position), baseOffset + position); if (!tail.Text.IsNullOrEmpty()) { yield return tail; } } } /// /// Trim Unit Text while Adjusting its Offset ... /// /// /// /// private Unit TrimUnit( string text, int offset ) { // var start = 0; while (start < text.Length && char.IsWhiteSpace(text[start])) { start++; } // var end = text.Length; while (end > start && char.IsWhiteSpace(text[end - 1])) { end--; } // var result = new Unit(text.Substring(start, end - start), offset + start); // return result; } /// /// Cut a Unit into Pieces no Longer than Max Size, Preferring Whitespace Boundaries ... /// /// /// /// private IEnumerable HardSplit( Unit unit, int maxSize ) { // var text = unit.Text; var position = 0; // while (position < text.Length) { // var remaining = text.Length - position; if (remaining <= maxSize) { // yield return TrimUnit(text.Substring(position), unit.Offset + position); yield break; } // // Find Last Whitespace within Window ... var cut = text.LastIndexOfAny(WordBoundaries, position + maxSize - 1, maxSize); if (cut <= position) { // // No Whitespace -> Hard Cut ... cut = position + maxSize; } // var piece = TrimUnit(text.Substring(position, cut - position), unit.Offset + position); if (!piece.Text.IsNullOrEmpty()) { yield return piece; } // position = cut; while (position < text.Length && char.IsWhiteSpace(text[position])) { position++; } } } /// /// Accumulate Units into Chunks up to ChunkSize, Carrying Overlap to Next Chunk ... /// /// /// private List Accumulate(List units) { // var result = new List(); if (!units.HasChild()) { return result; } // var buffer = new StringBuilder(); var buffered = new List(); var bufferOffset = -1; // foreach (var unit in units) { // var separator = buffer.Length > 0 ? " " : string.Empty; var projected = buffer.Length + separator.Length + unit.Text.Length; // if (projected > configuration.TextChunker.ChunkSize && buffer.Length > 0) { // // Close Current Chunk ... var closed = buffer.ToString(); result.Add(new Unit(closed, bufferOffset)); // // Seed Next Chunk with Overlap Tail (only if Unit still Fits) ... var overlap = TakeOverlap(closed, configuration.TextChunker.ChunkOverlap); var fits = overlap.Length + 1 + unit.Text.Length <= configuration.TextChunker.ChunkSize; // buffer.Clear(); if (!overlap.IsNullOrEmpty() && fits) { // bufferOffset = ComputeOverlapOffset(buffered, overlap.Length); buffer.Append(overlap); separator = " "; } else { // bufferOffset = -1; separator = string.Empty; } // buffered.Clear(); } // if (bufferOffset < 0) { bufferOffset = unit.Offset; } // buffer.Append(separator).Append(unit.Text); buffered.Add(unit); } // if (buffer.Length > 0) { result.Add(new Unit(buffer.ToString(), bufferOffset)); } // return result; } /// /// Map Trailing Overlap Length of Buffered Units back to Source Offset ... /// Units Joined by Single Space Separator in Buffer ... /// /// /// /// private int ComputeOverlapOffset( List buffered, int overlapLength ) { // var result = 0; var remaining = overlapLength; for (var i = buffered.Count - 1; i >= 0; i--) { // var unit = buffered[i]; if (remaining <= unit.Text.Length) { // result = unit.Offset + unit.Text.Length - remaining; return result; } // // Consume Unit and its Leading Separator ... remaining -= unit.Text.Length + 1; if (remaining <= 0) { // result = unit.Offset; return result; } } // result = buffered.Count > 0 ? buffered[0].Offset : 0; // return result; } /// /// Take Trailing Overlap from Text, Aligned to Word Boundary ... /// /// /// /// private string TakeOverlap( string text, int overlap ) { // if (overlap <= 0 || text.Length <= overlap) { return string.Empty; } // var start = text.Length - overlap; var boundary = text.IndexOfAny(WordBoundaries, start); if (boundary < 0 || boundary >= text.Length - 1) { // // No Boundary inside Window -> Skip Overlap ... return string.Empty; } // return text.Substring(boundary + 1).Trim(); } /// /// Merge Chunks Smaller than MinChunkSize into their Predecessor ... /// /// /// private List MergeSmallChunks(List chunks) { // if (configuration.TextChunker.MinChunkSize <= 0 || chunks.Count < 2) { return chunks; } // var result = new List(); foreach (var chunk in chunks) { // if (chunk.Text.Length < configuration.TextChunker.MinChunkSize && result.Count > 0) { // var previous = result[result.Count - 1]; var merged = $"{previous.Text} {chunk.Text}"; if (merged.Length <= configuration.TextChunker.ChunkSize) { result[result.Count - 1] = new Unit(merged, previous.Offset); continue; } } // result.Add(chunk); } // return result; } /// /// Characters Considered as Word Boundaries ... /// private readonly char[] WordBoundaries = [' ', '\n', '\t']; #endregion } }