feat(m2-m3): adapter, text pipeline, double-copy capture and Services (T2.1-T2.7, T3.1-T3.4)
M2: TranslationAdapter/AdapterRegistry with documented Hy-MT3 prompts and publisher sampling; all 102 languages with BCP-47 variants, RTL and dense-script flags; normalisation, NLLanguage detection, content classification and exact-join script-aware chunking; protected-token scanning and output validation; prompt policy with one documented fallback; shared TranslationPipeline with Core error mapping. The CLI now reports sourceLanguage and warning codes. M3: pure DoubleCopyDetector, 120 ms PasteboardWatcher with 750 ms own-write suppression, SystemPasteboard snapshot/restore and markers, CapturePolicy for the 4000/2000 limits, ServicesProvider and the menu-bar action. T3.5 (10-app manual matrix) remains intentionally open. Docs: ARCHITECTURE, TRANSLATION_OUTPUT, HYMT3_MODEL (§7 spike), SELECTION_AND_CLIPBOARD, PROGRESS; ADR-016 superseded by ADR-017/018. Verified: make verify green (format, strict lint, scripts, privacy, Debug+Release signatures, package tests); live 7B CLI en→de/de→en/Markdown/JSON/placeholders; empty input exits 2 and unreachable exits 3.
This commit is contained in:
1 parent
26b493e7e5
commit
64078e2f04
80 files changed
+4090
-325
No files matched your search
@@ -0,0 +1,243 @@
|
||||
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 {
|
||||
/// 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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
/// The source-content classes from `docs/ARCHITECTURE.md` §9.1.
|
||||
public enum ContentClass: String, Sendable, Equatable, CaseIterable {
|
||||
/// Ordinary prose.
|
||||
case plain
|
||||
/// Markdown, including headings, lists, tables and fenced code.
|
||||
case markdown
|
||||
/// JSON data.
|
||||
case json
|
||||
/// HTML markup.
|
||||
case html
|
||||
/// Code without Markdown prose.
|
||||
case code
|
||||
/// Many placeholders, URLs or delimiters.
|
||||
case delimited
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import Foundation
|
||||
|
||||
/// A simple content classifier used only to choose a documented prompt fallback.
|
||||
public struct ContentClassifier: Sendable {
|
||||
private let scanner: ProtectedTokenScanner
|
||||
private static let tagRegex = try? NSRegularExpression(pattern: "</?[A-Za-z][^>]*>")
|
||||
|
||||
/// Creates a classifier.
|
||||
public init(scanner: ProtectedTokenScanner = ProtectedTokenScanner()) {
|
||||
self.scanner = scanner
|
||||
}
|
||||
|
||||
/// Classifies `text` as plain, Markdown, JSON, HTML, code or delimiter-heavy.
|
||||
public func classify(_ text: String) -> ContentClass {
|
||||
let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard !trimmed.isEmpty else { return .plain }
|
||||
|
||||
if isJSON(trimmed) {
|
||||
return .json
|
||||
}
|
||||
if isHTML(trimmed) {
|
||||
return .html
|
||||
}
|
||||
|
||||
let fenced = trimmed.components(separatedBy: "```").count > 1
|
||||
let markdownMarkers = trimmed.components(separatedBy: "\n").filter { line in
|
||||
let trimmedLine = line.trimmingCharacters(in: .whitespaces)
|
||||
return trimmedLine.hasPrefix("#") || trimmedLine.hasPrefix("- ") || trimmedLine.hasPrefix("* ")
|
||||
|| trimmedLine.hasPrefix("> ") || trimmedLine.hasPrefix("|") || trimmedLine.hasPrefix("[")
|
||||
|| trimmedLine.hasPrefix("![")
|
||||
}.count
|
||||
if markdownMarkers >= 1 || fenced {
|
||||
return fenced && markdownMarkers == 0 ? .code : .markdown
|
||||
}
|
||||
|
||||
let tokens = scanner.scan(trimmed)
|
||||
if tokens.count >= 3 {
|
||||
return .delimited
|
||||
}
|
||||
return .plain
|
||||
}
|
||||
|
||||
private func isJSON(_ text: String) -> Bool {
|
||||
guard text.hasPrefix("{") || text.hasPrefix("["), let data = text.data(using: .utf8) else { return false }
|
||||
return (try? JSONSerialization.jsonObject(with: data)) != nil
|
||||
}
|
||||
|
||||
private func isHTML(_ text: String) -> Bool {
|
||||
guard let tagRegex = Self.tagRegex else { return false }
|
||||
let range = NSRange(location: 0, length: (text as NSString).length)
|
||||
return tagRegex.numberOfMatches(in: text, range: range) >= 2
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import Foundation
|
||||
import NaturalLanguage
|
||||
|
||||
/// One language hypothesis from `NLLanguageRecognizer`.
|
||||
public struct LanguageDetection: Sendable, Equatable {
|
||||
/// The dominant BCP-47 language code, e.g. `en` or `de`.
|
||||
public let code: String
|
||||
/// The recogniser confidence in `code`, from 0 to 1.
|
||||
public let confidence: Double
|
||||
/// Candidate codes ordered by confidence, including `code` first.
|
||||
public let alternatives: [String]
|
||||
|
||||
/// Creates a detection value.
|
||||
public init(code: String, confidence: Double, alternatives: [String]) {
|
||||
self.code = code
|
||||
self.confidence = confidence
|
||||
self.alternatives = alternatives
|
||||
}
|
||||
}
|
||||
|
||||
/// Source-language detection. Advisory only: it never blocks translation.
|
||||
public protocol LanguageDetecting: Sendable {
|
||||
/// Detects the dominant language of `text`, or returns nil for empty/undecidable text.
|
||||
func detect(_ text: String) -> LanguageDetection?
|
||||
}
|
||||
|
||||
/// `NLLanguageRecognizer`-backed detection (`docs/TRANSLATION_OUTPUT.md` §8).
|
||||
public struct NaturalLanguageDetector: LanguageDetecting {
|
||||
/// Creates a detector.
|
||||
public init() {}
|
||||
|
||||
/// Detects the dominant language. Short or mixed text usually reports low confidence.
|
||||
public func detect(_ text: String) -> LanguageDetection? {
|
||||
let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard !trimmed.isEmpty else { return nil }
|
||||
|
||||
let recognizer = NLLanguageRecognizer()
|
||||
recognizer.processString(trimmed)
|
||||
guard let dominant = recognizer.dominantLanguage else { return nil }
|
||||
let hypotheses = recognizer.languageHypotheses(withMaximum: 3)
|
||||
let ordered = hypotheses.sorted { lhs, rhs in
|
||||
lhs.value == rhs.value ? lhs.key.rawValue < rhs.key.rawValue : lhs.value > rhs.value
|
||||
}.map(\.key.rawValue)
|
||||
let alternatives = ordered.isEmpty ? [dominant.rawValue] : ordered
|
||||
return LanguageDetection(
|
||||
code: dominant.rawValue,
|
||||
confidence: Double(hypotheses[dominant] ?? 0),
|
||||
alternatives: alternatives
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import Foundation
|
||||
|
||||
/// A protected token that must survive translation (`docs/TRANSLATION_OUTPUT.md` §4).
|
||||
public struct ProtectedToken: Sendable, Equatable, Hashable {
|
||||
/// The token kind.
|
||||
public let kind: ProtectedTokenKind
|
||||
/// The exact text that must appear in the translation.
|
||||
public let value: String
|
||||
|
||||
/// Creates a protected token.
|
||||
public init(kind: ProtectedTokenKind, value: String) {
|
||||
self.kind = kind
|
||||
self.value = value
|
||||
}
|
||||
}
|
||||
|
||||
/// The protected-token kinds from `docs/TRANSLATION_OUTPUT.md` §4.
|
||||
public enum ProtectedTokenKind: String, Sendable, Equatable, CaseIterable {
|
||||
/// `https://…`, `http://…`, `www.…`
|
||||
case url
|
||||
/// `name@example.com`
|
||||
case email
|
||||
/// `{{name}}`, `{{ name }}`
|
||||
case mustache
|
||||
/// `${name}`
|
||||
case templateLiteral
|
||||
/// `%s`, `%d`, `%1$@`, `%02d`
|
||||
case printf
|
||||
/// `` `code` ``
|
||||
case codeSpan
|
||||
/// A fenced code block.
|
||||
case fencedCode
|
||||
/// `<a href="…">`, `</div>`
|
||||
case htmlTag
|
||||
/// A quoted JSON key followed by `:`.
|
||||
case jsonKey
|
||||
/// `/Users/…`, `C:\…`
|
||||
case filePath
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import Foundation
|
||||
|
||||
/// Finds URLs, e-mail addresses, placeholders, code spans, HTML tags, JSON keys and paths that
|
||||
/// must survive translation (`docs/TRANSLATION_OUTPUT.md` §4).
|
||||
public struct ProtectedTokenScanner: Sendable {
|
||||
private struct Rule {
|
||||
let kind: ProtectedTokenKind
|
||||
let regex: NSRegularExpression
|
||||
let group: Int
|
||||
}
|
||||
|
||||
private static let rules: [Rule] = {
|
||||
func rule(
|
||||
_ kind: ProtectedTokenKind,
|
||||
_ pattern: String,
|
||||
group: Int = 0,
|
||||
options: NSRegularExpression.Options = []
|
||||
) -> Rule? {
|
||||
guard let regex = try? NSRegularExpression(pattern: pattern, options: options) else {
|
||||
return nil
|
||||
}
|
||||
return Rule(kind: kind, regex: regex, group: group)
|
||||
}
|
||||
let rules: [Rule?] = [
|
||||
rule(.fencedCode, "```[\\s\\S]*?```"),
|
||||
rule(.codeSpan, "`[^`\\n]+`"),
|
||||
rule(.htmlTag, "</?[A-Za-z][^>\\n]*>"),
|
||||
rule(.url, "(?:https?://|www\\.)[^\\s<>\"']+"),
|
||||
rule(.email, "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"),
|
||||
rule(.mustache, "\\{\\{\\s*[^{}\\n]+\\s*\\}\\}"),
|
||||
rule(.templateLiteral, "\\$\\{[^{}\\n]+\\}"),
|
||||
rule(.printf, "%(?:\\d+\\$)?[-+0#]*\\d*(?:\\.\\d+)?[sd@]"),
|
||||
rule(.jsonKey, "(\"(?:[^\"\\\\]|\\\\.)*\")\\s*:", group: 1),
|
||||
rule(.filePath, "(?:/(?:Users|home|var|usr|opt|tmp)/[^\\s,;:\"'<>]+|[A-Za-z]:\\\\[^\\s,;:\"'<>]+)"),
|
||||
]
|
||||
return rules.compactMap(\.self)
|
||||
}()
|
||||
|
||||
/// Creates a scanner.
|
||||
public init() {}
|
||||
|
||||
/// Scans `text` and returns the protected tokens in source order, without duplicates.
|
||||
public func scan(_ text: String) -> [ProtectedToken] {
|
||||
let nsText = text as NSString
|
||||
let fullRange = NSRange(location: 0, length: nsText.length)
|
||||
var occupied: [NSRange] = []
|
||||
var tokens: [(range: NSRange, token: ProtectedToken)] = []
|
||||
|
||||
for rule in Self.rules {
|
||||
for match in rule.regex.matches(in: text, options: [], range: fullRange) {
|
||||
let range = match.range(at: rule.group)
|
||||
guard range.location != NSNotFound else { continue }
|
||||
if occupied.contains(where: { NSIntersectionRange($0, range).length > 0 }) {
|
||||
continue
|
||||
}
|
||||
var value = nsText.substring(with: range)
|
||||
if rule.kind == .url {
|
||||
value = trimURLTail(value)
|
||||
if value.count < 4 {
|
||||
continue
|
||||
}
|
||||
}
|
||||
let token = ProtectedToken(kind: rule.kind, value: value)
|
||||
if tokens.contains(where: { $0.token == token }) {
|
||||
continue
|
||||
}
|
||||
tokens.append((range, token))
|
||||
occupied.append(range)
|
||||
}
|
||||
}
|
||||
|
||||
return tokens.sorted { $0.range.location < $1.range.location }.map(\.token)
|
||||
}
|
||||
|
||||
/// Removes sentence punctuation that a URL pattern may have swallowed. A balanced closing
|
||||
/// parenthesis is kept, so Wikipedia-style URLs remain intact.
|
||||
private func trimURLTail(_ value: String) -> String {
|
||||
var result = value
|
||||
while let last = result.last, ".,;:!?".contains(last) {
|
||||
result.removeLast()
|
||||
}
|
||||
while let last = result.last, ")]}".contains(last) {
|
||||
let open: Character = last == ")" ? "(" : (last == "]" ? "[" : "{")
|
||||
let opens = result.filter { $0 == open }.count
|
||||
let closes = result.filter { $0 == last }.count
|
||||
guard closes > opens else { break }
|
||||
result.removeLast()
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
/// One chunk of a translation, with the separator that followed it in the source.
|
||||
public struct TextChunk: Sendable, Equatable {
|
||||
/// The zero-based chunk index.
|
||||
public let index: Int
|
||||
/// The chunk text.
|
||||
public let text: String
|
||||
/// The source separator after this chunk (`"\n\n"`, `" "` or `""`).
|
||||
public let separatorAfter: String
|
||||
|
||||
/// Creates a chunk.
|
||||
public init(index: Int, text: String, separatorAfter: String) {
|
||||
self.index = index
|
||||
self.text = text
|
||||
self.separatorAfter = separatorAfter
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import Foundation
|
||||
|
||||
/// Input and output normalisation from `docs/TRANSLATION_OUTPUT.md` §2 and §5.
|
||||
public enum TextNormalization {
|
||||
/// N1–N3: line endings to `\n`, strip BOM/NUL/C0 controls (except tab and newline),
|
||||
/// strip U+200B, keep ZWJ/ZWNJ, NFC, then trim outer whitespace (N2).
|
||||
public static func normalizeInput(_ text: String) -> String {
|
||||
let unified = unifyLineEndings(text)
|
||||
let filtered = unified.unicodeScalars.filter { scalar in
|
||||
switch scalar.value {
|
||||
case 0, 0xFEFF, 0x200B:
|
||||
return false
|
||||
default:
|
||||
break
|
||||
}
|
||||
if scalar.properties.generalCategory == .control {
|
||||
return scalar.value == 0x09 || scalar.value == 0x0A
|
||||
}
|
||||
return true
|
||||
}
|
||||
let cleaned = String(String.UnicodeScalarView(filtered))
|
||||
return cleaned.precomposedStringWithCanonicalMapping.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
}
|
||||
|
||||
/// T1: strip NUL, normalise line endings, trim outer whitespace. Internal text is untouched.
|
||||
public static func normalizeOutput(_ text: String) -> String {
|
||||
unifyLineEndings(text)
|
||||
.replacingOccurrences(of: "\0", with: "")
|
||||
.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
}
|
||||
|
||||
/// Comparison normalisation for the double-copy rule: line endings and outer trimming only.
|
||||
/// Internal whitespace is deliberately preserved.
|
||||
public static func normalizeForComparison(_ text: String) -> String {
|
||||
unifyLineEndings(text).trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
}
|
||||
|
||||
private static func unifyLineEndings(_ text: String) -> String {
|
||||
text
|
||||
.replacingOccurrences(of: "\r\n", with: "\n")
|
||||
.replacingOccurrences(of: "\r", with: "\n")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
/// Dense-script detection for the chunk limit (`docs/TRANSLATION_OUTPUT.md` §3).
|
||||
///
|
||||
/// The limit is script-based, not language-based: one CJK, Arabic, Thai or Indic character is
|
||||
/// enough to select the smaller limit. Latin, Cyrillic and Greek stay on the larger limit.
|
||||
public enum TextScript {
|
||||
private static let denseRanges: [ClosedRange<UInt32>] = [
|
||||
0x0590 ... 0x05FF, // Hebrew
|
||||
0x0600 ... 0x06FF, // Arabic
|
||||
0x0750 ... 0x077F, // Arabic Supplement
|
||||
0x0900 ... 0x097F, // Devanagari
|
||||
0x0980 ... 0x09FF, // Bengali
|
||||
0x0A00 ... 0x0A7F, // Gurmukhi
|
||||
0x0A80 ... 0x0AFF, // Gujarati
|
||||
0x0B00 ... 0x0B7F, // Oriya
|
||||
0x0B80 ... 0x0BFF, // Tamil
|
||||
0x0C00 ... 0x0C7F, // Telugu
|
||||
0x0C80 ... 0x0CFF, // Kannada
|
||||
0x0D00 ... 0x0D7F, // Malayalam
|
||||
0x0D80 ... 0x0DFF, // Sinhala
|
||||
0x0E00 ... 0x0E7F, // Thai
|
||||
0x0E80 ... 0x0EFF, // Lao
|
||||
0x0F00 ... 0x0FFF, // Tibetan
|
||||
0x1000 ... 0x109F, // Myanmar
|
||||
0x1200 ... 0x137F, // Ethiopic
|
||||
0x1780 ... 0x17FF, // Khmer
|
||||
0x1800 ... 0x18AF, // Mongolian
|
||||
0x2E80 ... 0x9FFF, // CJK, Hiragana, Katakana and Hangul compatibility
|
||||
0xA960 ... 0xA97F, // Hangul Jamo Extended-A
|
||||
0xAC00 ... 0xD7AF, // Hangul syllables
|
||||
0xF900 ... 0xFAFF, // CJK compatibility ideographs
|
||||
0xFE30 ... 0xFE4F, // CJK compatibility forms
|
||||
0xFF66 ... 0xFFDC, // Half-width Katakana and Hangul
|
||||
]
|
||||
|
||||
/// True when `text` contains at least one dense-script scalar.
|
||||
public static func isDense(_ text: String) -> Bool {
|
||||
text.unicodeScalars.contains { scalar in
|
||||
denseRanges.contains { $0.contains(scalar.value) }
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user