Files

589 lines
17 KiB
C#

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
{
/// <summary>
/// Splits Long Texts into Overlapping Chunks using a Hierarchical Strategy:
/// Paragraphs -> Sentences -> Words -> Hard Cut ...
/// </summary>
public class XTextChunker : IXTextChunker
{
/// <summary>
/// Default Options which used when no Options Provided ...
/// </summary>
private readonly XAiApiConfiguration configuration;
/// <summary>
/// Matches Paragraph Boundaries (two or more Line Breaks) ...
/// </summary>
private static readonly Regex ParagraphSplitter = new(
@"\n\s*\n+",
RegexOptions.Compiled
);
/// <summary>
/// Matches Sentence Boundaries, Supports Latin, Persian and CJK Terminators ...
/// </summary>
private static readonly Regex SentenceSplitter = new(
@"(?<=[\.\!\?؟。!?])\s+|(?<=\n)",
RegexOptions.Compiled
);
/// <summary>
/// Matches Repeated Horizontal Whitespaces ...
/// </summary>
private static readonly Regex HorizontalWhitespace = new(
@"[ \t\f\v\u00A0]{2,}",
RegexOptions.Compiled
);
/// <summary>
/// Matches Three or more Line Breaks ...
/// </summary>
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;
}
/// <summary>
/// Split Text into Chunks ...
/// </summary>
/// <param name="text"></param>
/// <param name="source"></param>
/// <returns></returns>
public IList<XTextChunk> Chunk(
string text,
string source = null
)
{
//
var result = new List<XTextChunk>();
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;
}
/// <summary>
/// Split Text into Chunks and Return only Texts ...
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public IList<string> ChunkTexts(string text)
{
//
var result = Chunk(text, null)
.Select(c => c.Text)
.ToList();
//
return result;
}
//
#region Private ...
/// <summary>
/// Internal Text Unit with its Offset in Normalized Source ...
/// </summary>
private readonly struct Unit
{
public Unit(string text, int offset)
{
Text = text;
Offset = offset;
}
public string Text { get; }
public int Offset { get; }
}
/// <summary>
/// Normalize Line Endings and Whitespaces ...
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
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;
}
/// <summary>
/// Create Chunk Model ...
/// </summary>
/// <param name="text"></param>
/// <param name="offset"></param>
/// <param name="index"></param>
/// <param name="source"></param>
/// <returns></returns>
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;
}
/// <summary>
/// Split Text into Atomic Units; each Unit Guaranteed to fit in ChunkSize ...
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
private List<Unit> BuildUnits(string text)
{
//
var result = new List<Unit>();
//
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;
}
/// <summary>
/// Split Text by Regex while Tracking Offsets, Skipping Empty Parts ...
/// </summary>
/// <param name="text"></param>
/// <param name="splitter"></param>
/// <param name="baseOffset"></param>
/// <returns></returns>
private IEnumerable<Unit> 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;
}
}
}
/// <summary>
/// Trim Unit Text while Adjusting its Offset ...
/// </summary>
/// <param name="text"></param>
/// <param name="offset"></param>
/// <returns></returns>
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;
}
/// <summary>
/// Cut a Unit into Pieces no Longer than Max Size, Preferring Whitespace Boundaries ...
/// </summary>
/// <param name="unit"></param>
/// <param name="maxSize"></param>
/// <returns></returns>
private IEnumerable<Unit> 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++;
}
}
}
/// <summary>
/// Accumulate Units into Chunks up to ChunkSize, Carrying Overlap to Next Chunk ...
/// </summary>
/// <param name="units"></param>
/// <returns></returns>
private List<Unit> Accumulate(List<Unit> units)
{
//
var result = new List<Unit>();
if (!units.HasChild())
{
return result;
}
//
var buffer = new StringBuilder();
var buffered = new List<Unit>();
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;
}
/// <summary>
/// Map Trailing Overlap Length of Buffered Units back to Source Offset ...
/// Units Joined by Single Space Separator in Buffer ...
/// </summary>
/// <param name="buffered"></param>
/// <param name="overlapLength"></param>
/// <returns></returns>
private int ComputeOverlapOffset(
List<Unit> 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;
}
/// <summary>
/// Take Trailing Overlap from Text, Aligned to Word Boundary ...
/// </summary>
/// <param name="text"></param>
/// <param name="overlap"></param>
/// <returns></returns>
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();
}
/// <summary>
/// Merge Chunks Smaller than MinChunkSize into their Predecessor ...
/// </summary>
/// <param name="chunks"></param>
/// <returns></returns>
private List<Unit> MergeSmallChunks(List<Unit> chunks)
{
//
if (configuration.TextChunker.MinChunkSize <= 0 || chunks.Count < 2)
{
return chunks;
}
//
var result = new List<Unit>();
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;
}
/// <summary>
/// Characters Considered as Word Boundaries ...
/// </summary>
private readonly char[] WordBoundaries = [' ', '\n', '\t'];
#endregion
}
}