Files
Sprachmittler/Packages/SprachmittlerKit/Sources/SprachmittlerText/Chunker.swift
T
schihei 2a601058f4 feat(capture): translate long selections in parts
The capture gate and the chunk size were the same number, so a selection above one chunk was rejected before the pipeline could split it; the Settings sliders moved both thresholds together. Add maximumPartsPerSelection (1-8, default 1, so existing behaviour is unchanged). The capture limit is now part size x parts and travels on TranslationSessionRequest, so the watcher, CapturePolicy and TranslationSession agree for that capture. TranslationStreaming gained an optional per-part callback; the session emits chunkStarted and the panel shows 'Part 2 of 4' while streaming and '2 parts' when finished. textTooLong now points at Settings and offers an Open Settings button. Lower the dense-script part-size maximum to 4000 because 5000 dense characters plus a 4096-token output can overflow the 8192-token context. Tests cover capture limits, watcher limits, pipeline part callbacks, session events and limits, panel progress, settings clamping and migration. Docs updated: ADR-011, TRANSLATION_OUTPUT, SELECTION_AND_CLIPBOARD, ARCHITECTURE, LANGUAGES and README. Verified: make verify green; live 4355-character German text showed Part 1 of 2, Part 2 of 2 and '2 parts'; with one part the panel showed the too-long message and Open Settings.
2026-11-27 20:21:30 +01:00

244 lines
8.3 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import Foundation
/// Splits text at paragraph, sentence, word and grapheme boundaries with script-aware limits.
///
/// Joining `chunks(for:)` with `reassemble(_:)` always returns the input exactly. The chunker does
/// not trim, normalise or invent separators; call `TextNormalization.normalizeInput` first.
public struct Chunker: Sendable, Equatable {
/// The limit for Latin, Cyrillic and Greek text.
public let latinLimit: Int
/// The limit for CJK, Arabic, Thai, Indic and other dense scripts.
public let denseLimit: Int
/// Creates a chunker.
public init(latinLimit: Int = 4000, denseLimit: Int = 2000) {
self.latinLimit = latinLimit
self.denseLimit = denseLimit
}
/// The character limit that applies to `text`.
public func limit(for text: String) -> Int {
TextScript.isDense(text) ? denseLimit : latinLimit
}
/// Splits `text` into chunks of at most the script-aware limit.
public func chunks(for text: String) -> [TextChunk] {
guard !text.isEmpty else { return [] }
let limit = max(1, limit(for: text))
var pieces: [(text: String, separator: String)] = []
for unit in paragraphUnits(text) {
split(unit.text, trailing: unit.separator, limit: limit, into: &pieces)
}
return pack(mergingLeadingEmpty(pieces), limit: limit)
}
/// Reassembles chunks into the original text.
public static func reassemble(_ chunks: [TextChunk]) -> String {
chunks.sorted { $0.index < $1.index }.reduce(into: "") { result, chunk in
result += chunk.text
result += chunk.separatorAfter
}
}
// MARK: - Splitting
private func split(
_ text: String,
trailing: String,
limit: Int,
into pieces: inout [(text: String, separator: String)]
) {
if text.count <= limit {
pieces.append((text, trailing))
return
}
let sentences = sentenceUnits(text)
if sentences.count > 1 {
splitSubunits(sentences, trailing: trailing, limit: limit, into: &pieces)
return
}
let words = wordUnits(text)
if words.count > 1 {
splitSubunits(words, trailing: trailing, limit: limit, into: &pieces)
return
}
splitGraphemes(text, trailing: trailing, into: &pieces)
}
private func splitSubunits(
_ units: [(text: String, separator: String)],
trailing: String,
limit: Int,
into pieces: inout [(text: String, separator: String)]
) {
for (offset, unit) in units.enumerated() {
let separator = offset == units.count - 1 ? unit.separator + trailing : unit.separator
split(unit.text, trailing: separator, limit: limit, into: &pieces)
}
}
private func splitGraphemes(
_ text: String,
trailing: String,
into pieces: inout [(text: String, separator: String)]
) {
let characters = Array(text)
for (offset, character) in characters.enumerated() {
let separator = offset == characters.count - 1 ? trailing : ""
pieces.append((String(character), separator))
}
}
// MARK: - Units
private func paragraphUnits(_ text: String) -> [(text: String, separator: String)] {
guard let regex = try? NSRegularExpression(pattern: "\\n[ \\t]*\\n(?:[ \\t]*\\n)*") else {
return [(text, "")]
}
let nsText = text as NSString
let matches = regex.matches(in: text, range: NSRange(location: 0, length: nsText.length))
guard !matches.isEmpty else { return [(text, "")] }
var units: [(String, String)] = []
var cursor = 0
for match in matches {
let body = nsText.substring(with: NSRange(location: cursor, length: match.range.location - cursor))
let separator = nsText.substring(with: match.range)
units.append((body, separator))
cursor = match.range.location + match.range.length
}
let tail = nsText.substring(from: cursor)
units.append((tail, ""))
return units
}
private func sentenceUnits(_ text: String) -> [(text: String, separator: String)] {
let terminators: Set<Character> = [".", "!", "?", "。", "!", "?", "…"]
let closers: Set<Character> = ["\"", "'", "”", "’", ")", "]", "}"]
let characters = Array(text)
var units: [(String, String)] = []
var start = 0
var index = 0
while index < characters.count {
guard terminators.contains(characters[index]) else {
index += 1
continue
}
var end = index + 1
while end < characters.count, terminators.contains(characters[end]) {
end += 1
}
while end < characters.count, closers.contains(characters[end]) {
end += 1
}
guard end < characters.count, characters[end].isWhitespace else {
index = end
continue
}
var separatorEnd = end
while separatorEnd < characters.count, characters[separatorEnd].isWhitespace {
separatorEnd += 1
}
let body = String(characters[start ..< end])
let separator = String(characters[end ..< separatorEnd])
units.append((body, separator))
start = separatorEnd
index = separatorEnd
}
if start < characters.count {
units.append((String(characters[start...]), ""))
}
return units.isEmpty ? [(text, "")] : units
}
private func wordUnits(_ text: String) -> [(text: String, separator: String)] {
let characters = Array(text)
var units: [(String, String)] = []
var start = 0
var index = 0
while index < characters.count {
guard characters[index].isWhitespace else {
index += 1
continue
}
let body = String(characters[start ..< index])
var end = index
while end < characters.count, characters[end].isWhitespace {
end += 1
}
let separator = String(characters[index ..< end])
units.append((body, separator))
start = end
index = end
}
if start < characters.count {
units.append((String(characters[start...]), ""))
}
return units.isEmpty ? [(text, "")] : units
}
// MARK: - Packing
/// Keeps a leading empty body's separator (for example a text starting with `\n\n` or a long
/// over-limit text starting with whitespace) by attaching it to the first non-empty piece.
private func mergingLeadingEmpty(
_ pieces: [(text: String, separator: String)]
) -> [(text: String, separator: String)] {
var result = pieces
var prefix = ""
while let first = result.first, first.text.isEmpty {
prefix += first.separator
result.removeFirst()
}
guard !result.isEmpty else {
return prefix.isEmpty ? [] : [(prefix, "")]
}
var first = result[0]
first.text = prefix + first.text
result[0] = first
return result
}
private func pack(
_ pieces: [(text: String, separator: String)],
limit: Int
) -> [TextChunk] {
var chunks: [TextChunk] = []
var current = ""
var trailing = ""
var lastSeparator = ""
var index = 0
func emit() {
guard !current.isEmpty else { return }
chunks.append(TextChunk(index: index, text: current, separatorAfter: trailing))
index += 1
current = ""
trailing = ""
lastSeparator = ""
}
for piece in pieces {
if current.isEmpty {
current = piece.text
} else if current.count + lastSeparator.count + piece.text.count <= limit {
current += lastSeparator + piece.text
} else {
emit()
current = piece.text
}
trailing = piece.separator
lastSeparator = piece.separator
}
emit()
return chunks
}
}