SPB Git

Repository Public MIT

TextTools.swift 19.8 KB 387 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Astra9// File             : Packages/AstraAgents/Sources/TextTools.swift10// Module           : Packages11// Repository       : https://git.spboucher.ai/orix-astra12// Created          : 2026-11-2113// Last Modified    : 2026-11-2114//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author           : Simon-Pierre Boucher20// Position         : Professor of Finance21// Institution      : Université du Québec en Outaouais (UQO)22// Department       : Département des sciences administratives23// Organization     : SP Boucher24//25// Website          : https://spboucher.ai26// Git              : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General          : info@spboucher.ai33// Professional     : contact@spboucher.ai34// Direct           : simon@spboucher.ai35// Research         : research@spboucher.ai36// Development      : dev@spboucher.ai37// Support          : support@spboucher.ai38// Security/Admin   : admin@spboucher.ai39// Notifications    : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification   : Public66// Distribution     : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License          : Proprietary, all rights reserved (see license file)80// License File     : LICENSE81// Maintainer       : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import Foundation89import AstraCore9091public struct TextStatistics: Sendable, Hashable {92    public var characters: Int93    public var charactersWithoutSpaces: Int94    public var words: Int95    public var lines: Int96    public var sentences: Int97    public var paragraphs: Int98    public var bytes: Int99100    public init(_ text: String) {101        characters = text.count102        charactersWithoutSpaces = text.reduce(0) { $0 + ($1.isWhitespace ? 0 : 1) }103        words = text.split(whereSeparator: { $0.isWhitespace }).filter { $0.contains { $0.isLetter || $0.isNumber } }.count104        let allLines = text.split(omittingEmptySubsequences: false, whereSeparator: { $0.isNewline })105        // A final line break ends the last line; it does not start a new one.106        lines = text.isEmpty ? 0 : allLines.count - (text.last?.isNewline == true ? 1 : 0)107        var paragraphCount = 0, inParagraph = false108        for line in allLines {109            let blank = line.allSatisfy(\.isWhitespace)110            if !blank, !inParagraph { paragraphCount += 1 }111            inParagraph = !blank112        }113        paragraphs = paragraphCount114        var sentenceCount = 0, pending = false, inTerminator = false115        for c in text {116            if c == "." || c == "!" || c == "?" || c == "…" {117                if pending, !inTerminator { sentenceCount += 1 }118                inTerminator = true; pending = false119            } else {120                inTerminator = false121                if c.isLetter || c.isNumber { pending = true }122            }123        }124        sentences = sentenceCount + (pending ? 1 : 0)125        bytes = text.utf8.count126    }127}128129public struct TextStatsTool: AgentTool {130    public let risk: ToolRisk = .safe131    public let definition = ToolDefinition(132        name: "text_stats",133        summary: "Counts characters, words, lines, sentences, paragraphs and UTF-8 bytes of a text, exactly. Use it instead of estimating lengths.",134        parameters: ["type": "object", "properties": ["text": ["type": "string"]], "required": ["text"], "additionalProperties": false])135    public init() {}136137    public func run(_ arguments: JSONValue, context: ToolContext) async throws -> ToolOutput {138        let text = arguments["text"]?.stringValue ?? ""139        guard text.utf8.count <= 2_000_000 else { throw ToolError("The text is larger than 2 MB.") }140        let s = TextStatistics(text)141        return ToolOutput([142            "characters: \(s.characters)", "characters_without_spaces: \(s.charactersWithoutSpaces)", "words: \(s.words)", "lines: \(s.lines)",143            "sentences: \(s.sentences) (approximate)", "paragraphs: \(s.paragraphs)", "utf8_bytes: \(s.bytes)",144        ].joined(separator: "\n"))145    }146}147148/// Regular-expression matching that cannot hang the app: bounded pattern and input sizes, refusal of the classic149/// nested-quantifier shapes, and a wall-clock limit enforced from inside the match through progress callbacks.150public enum BoundedRegex {151    public static let maxPatternLength = 500152    public static let maxInputCharacters = 200_000153    public static let defaultTimeLimit: TimeInterval = 0.5154155    public struct Match: Sendable, Hashable {156        public var text: String157        public var groups: [String?]158        public var location: Int159    }160161    /// True for patterns such as `(a+)+`, `(a*)*`, `(\w+\s?)+` or `(a|aa)+` nested under an unbounded repeat with an inner repeat:162    /// a quantified group that itself contains an unbounded quantifier. Conservative on purpose: some harmless patterns are refused too.163    public static func looksCatastrophic(_ pattern: String) -> Bool {164        let chars = Array(pattern)165        var stack: [Bool] = []          // per open group: does it contain an unbounded quantifier?166        var i = 0, inClass = false167        func unbounded(at k: Int) -> Bool {168            guard k < chars.count else { return false }169            if chars[k] == "+" || chars[k] == "*" { return true }170            if chars[k] == "{" {171                guard let close = chars[k...].firstIndex(of: "}") else { return false }172                let body = String(chars[(k + 1)..<close])173                if body.hasSuffix(",") { return true }174                if let top = body.split(separator: ",").last.flatMap({ Int($0) }) { return top > 16 }175            }176            return false177        }178        while i < chars.count {179            let c = chars[i]180            if c == "\\" { i += 2; if !inClass, unbounded(at: i), !stack.isEmpty { stack[stack.count - 1] = true }; continue }181            if inClass { if c == "]" { inClass = false; if unbounded(at: i + 1), !stack.isEmpty { stack[stack.count - 1] = true } }; i += 1; continue }182            switch c {183            case "[": inClass = true184            case "(": stack.append(false)185            case ")":186                let inner = stack.popLast() ?? false187                if inner, unbounded(at: i + 1) { return true }188                if !stack.isEmpty, inner || unbounded(at: i + 1) { stack[stack.count - 1] = true }189            default:190                if unbounded(at: i + 1), !stack.isEmpty { stack[stack.count - 1] = true }191            }192            i += 1193        }194        return false195    }196197    public static func matches(pattern: String, in text: String, caseInsensitive: Bool = false, maxMatches: Int = 50,198                               timeLimit: TimeInterval = defaultTimeLimit, refuseRiskyPatterns: Bool = true) throws -> [Match] {199        guard !pattern.isEmpty, pattern.count <= maxPatternLength else { throw ToolError("The pattern must have between 1 and \(maxPatternLength) characters.") }200        guard text.count <= maxInputCharacters else {201            throw ToolError("The text has \(text.count) characters; regular expressions are limited to \(maxInputCharacters). Work on a part of it.")202        }203        if refuseRiskyPatterns, looksCatastrophic(pattern) {204            throw ToolError("This pattern nests a repeat inside a repeated group (like (a+)+), which can take exponential time. Rewrite it without the nested repeat.")205        }206        let regex: NSRegularExpression207        do { regex = try NSRegularExpression(pattern: pattern, options: caseInsensitive ? [.caseInsensitive] : []) }208        catch { throw ToolError("The pattern is not a valid regular expression (ICU syntax): \(String(pattern.prefix(80)))") }209210        let deadline = Date().addingTimeInterval(timeLimit)211        var found: [Match] = []212        var timedOut = false213        regex.enumerateMatches(in: text, options: [.reportProgress], range: NSRange(text.startIndex..., in: text)) { result, _, stop in214            if Date() > deadline { timedOut = true; stop.pointee = true; return }215            guard let result, let whole = Range(result.range, in: text) else { return }216            let groups: [String?] = (0..<result.numberOfRanges).map { Range(result.range(at: $0), in: text).map { String(text[$0]) } }217            found.append(Match(text: String(text[whole]), groups: groups, location: result.range.location))218            if found.count >= maxMatches { stop.pointee = true }219        }220        if timedOut {221            throw ToolError("The pattern took longer than \(Int(timeLimit * 1000)) ms and was stopped\(found.isEmpty ? "" : " after \(found.count) match(es)"). Simplify it or shorten the text.")222        }223        return found224    }225}226227public struct RegexExtractTool: AgentTool {228    public let risk: ToolRisk = .safe229    let timeLimit: TimeInterval230    public init(timeLimit: TimeInterval = BoundedRegex.defaultTimeLimit) { self.timeLimit = timeLimit }231232    public let definition = ToolDefinition(233        name: "regex_extract",234        summary: "Finds every match of a regular expression (ICU syntax) in a text and returns the matches, or one capture group of each. "235            + "Bounded: limited text size, limited time, patterns with nested repeats are refused.",236        parameters: [237            "type": "object",238            "properties": [239                "text": ["type": "string"],240                "pattern": ["type": "string", "minLength": 1, "maxLength": .number(Double(BoundedRegex.maxPatternLength))],241                "group": ["type": "integer", "minimum": 0, "maximum": 20, "description": "Capture group to return. Default 0: the whole match."],242                "case_insensitive": ["type": "boolean"],243                "max_matches": ["type": "integer", "minimum": 1, "maximum": 200, "description": "Default 50."],244            ],245            "required": ["text", "pattern"],246            "additionalProperties": false,247        ])248249    public func run(_ arguments: JSONValue, context: ToolContext) async throws -> ToolOutput {250        let limit = arguments["max_matches"]?.exactInt ?? 50251        let group = arguments["group"]?.exactInt ?? 0252        let matches = try BoundedRegex.matches(pattern: arguments["pattern"]?.stringValue ?? "", in: arguments["text"]?.stringValue ?? "",253                                               caseInsensitive: arguments["case_insensitive"]?.boolValue ?? false, maxMatches: limit, timeLimit: timeLimit)254        guard !matches.isEmpty else { return ToolOutput("No match.") }255        if let first = matches.first, group >= first.groups.count {256            throw ToolError("The pattern has \(first.groups.count - 1) capture group(s); group \(group) does not exist.")257        }258        var lines = ["matches: \(matches.count)\(matches.count >= limit ? " (stopped at the limit)" : "")"]259        for (i, match) in matches.enumerated() { lines.append("\(i + 1). \(match.groups[group] ?? "(group did not participate)")") }260        return ToolOutput(lines.joined(separator: "\n"))261    }262}263264/// Unit conversion from fixed tables. Volumes are US customary; data sizes distinguish decimal (kB, MB) from binary (KiB, MiB).265public enum UnitConverter {266    public enum Category: String, Sendable, CaseIterable { case length, mass, temperature, volume, data, time }267268    struct Unit { var category: Category; var symbol: String; var factor: Double }269270    // Factor = how many base units (m, kg, L, byte, s) one unit is.271    private static let table: [(Category, String, Double, [String])] = [272        (.length, "mm", 0.001, ["millimeter", "millimetre", "millimeters", "millimetres"]),273        (.length, "cm", 0.01, ["centimeter", "centimetre", "centimeters", "centimetres"]),274        (.length, "m", 1, ["meter", "metre", "meters", "metres"]),275        (.length, "km", 1000, ["kilometer", "kilometre", "kilometers", "kilometres"]),276        (.length, "in", 0.0254, ["inch", "inches", "\""]),277        (.length, "ft", 0.3048, ["foot", "feet", "'"]),278        (.length, "yd", 0.9144, ["yard", "yards"]),279        (.length, "mi", 1609.344, ["mile", "miles"]),280        (.length, "nmi", 1852, ["nautical mile", "nautical miles"]),281        (.mass, "mg", 0.000_001, ["milligram", "milligrams"]),282        (.mass, "g", 0.001, ["gram", "grams"]),283        (.mass, "kg", 1, ["kilogram", "kilograms", "kilo", "kilos"]),284        (.mass, "t", 1000, ["tonne", "tonnes", "metric ton", "metric tons"]),285        (.mass, "oz", 0.028_349_523_125, ["ounce", "ounces"]),286        (.mass, "lb", 0.453_592_37, ["lbs", "pound", "pounds"]),287        (.mass, "st", 6.350_293_18, ["stone", "stones"]),288        (.volume, "ml", 0.001, ["milliliter", "millilitre", "milliliters", "millilitres"]),289        (.volume, "l", 1, ["liter", "litre", "liters", "litres"]),290        (.volume, "m3", 1000, ["cubic meter", "cubic metre", "cubic meters", "cubic metres", "m^3", "m³"]),291        (.volume, "tsp", 0.004_928_921_593_75, ["teaspoon", "teaspoons"]),292        (.volume, "tbsp", 0.014_786_764_781_25, ["tablespoon", "tablespoons"]),293        (.volume, "floz", 0.029_573_529_562_5, ["fl oz", "fluid ounce", "fluid ounces"]),294        (.volume, "cup", 0.236_588_236_5, ["cups"]),295        (.volume, "pt", 0.473_176_473, ["pint", "pints"]),296        (.volume, "qt", 0.946_352_946, ["quart", "quarts"]),297        (.volume, "gal", 3.785_411_784, ["gallon", "gallons"]),298        (.data, "bit", 0.125, ["bits"]),299        (.data, "B", 1, ["byte", "bytes"]),300        (.data, "kB", 1e3, ["kilobyte", "kilobytes"]),301        (.data, "MB", 1e6, ["megabyte", "megabytes"]),302        (.data, "GB", 1e9, ["gigabyte", "gigabytes"]),303        (.data, "TB", 1e12, ["terabyte", "terabytes"]),304        (.data, "KiB", 1024, ["kibibyte", "kibibytes"]),305        (.data, "MiB", 1_048_576, ["mebibyte", "mebibytes"]),306        (.data, "GiB", 1_073_741_824, ["gibibyte", "gibibytes"]),307        (.data, "TiB", 1_099_511_627_776, ["tebibyte", "tebibytes"]),308        (.time, "ms", 0.001, ["millisecond", "milliseconds"]),309        (.time, "s", 1, ["sec", "secs", "second", "seconds"]),310        (.time, "min", 60, ["mins", "minute", "minutes"]),311        (.time, "h", 3600, ["hr", "hrs", "hour", "hours"]),312        (.time, "d", 86_400, ["day", "days"]),313        (.time, "wk", 604_800, ["week", "weeks"]),314        (.time, "yr", 31_557_600, ["year", "years"]),315        (.temperature, "C", 1, ["°c", "celsius", "centigrade"]),316        (.temperature, "F", 1, ["°f", "fahrenheit"]),317        (.temperature, "K", 1, ["kelvin", "kelvins"]),318    ]319320    private static let lookup: (exact: [String: Unit], folded: [String: Unit]) = {321        var exact: [String: Unit] = [:], folded: [String: Unit] = [:]322        for (category, symbol, factor, aliases) in table {323            let unit = Unit(category: category, symbol: symbol, factor: factor)324            exact[symbol] = unit325            for name in [symbol.lowercased()] + aliases where folded[name] == nil { folded[name] = unit }326        }327        return (exact, folded)328    }()329330    public static var supportedUnits: String {331        Category.allCases.map { c in "\(c.rawValue): " + table.filter { $0.0 == c }.map(\.1).joined(separator: " ") }.joined(separator: "; ")332    }333334    static func unit(_ name: String) throws -> Unit {335        let trimmed = name.trimmingCharacters(in: .whitespaces)336        if let unit = lookup.exact[trimmed] ?? lookup.folded[trimmed.lowercased()] { return unit }337        throw ToolError("Unknown unit “\(String(trimmed.prefix(30)))”. Supported units: \(supportedUnits).")338    }339340    public static func convert(_ value: Double, from: String, to: String) throws -> Double {341        let source = try unit(from), target = try unit(to)342        guard source.category == target.category else {343            throw ToolError("\(source.symbol) is a unit of \(source.category.rawValue) and \(target.symbol) is a unit of \(target.category.rawValue); they cannot be converted.")344        }345        guard value.isFinite else { throw ToolError("The value is not a finite number.") }346        if source.category == .temperature {347            let kelvin: Double = switch source.symbol { case "C": value + 273.15; case "F": (value - 32) * 5 / 9 + 273.15; default: value }348            guard kelvin >= -1e-9 else { throw ToolError("That temperature is below absolute zero.") }349            return switch target.symbol { case "C": kelvin - 273.15; case "F": (kelvin - 273.15) * 9 / 5 + 32; default: kelvin }350        }351        return value * source.factor / target.factor352    }353354    /// Twelve significant digits: enough for any table factor, and free of binary noise such as 37.77777777777778.355    public static func format(_ value: Double) -> String {356        if value == 0 { return "0" }357        let rounded = Double(String(format: "%.12g", value)) ?? value358        return Calculator.format(.real(rounded))359    }360}361362public struct UnitConvertTool: AgentTool {363    public let risk: ToolRisk = .safe364    public let definition = ToolDefinition(365        name: "unit_convert",366        summary: "Converts a value between units of length, mass, temperature, volume (US customary), data size and time. Units: " + UnitConverter.supportedUnits + ".",367        parameters: [368            "type": "object",369            "properties": [370                "value": ["type": "number"],371                "from": ["type": "string", "minLength": 1, "maxLength": 30],372                "to": ["type": "string", "minLength": 1, "maxLength": 30],373            ],374            "required": ["value", "from", "to"],375            "additionalProperties": false,376        ])377    public init() {}378379    public func run(_ arguments: JSONValue, context: ToolContext) async throws -> ToolOutput {380        let value = arguments["value"]?.number ?? .nan381        let from = arguments["from"]?.stringValue ?? "", to = arguments["to"]?.stringValue ?? ""382        let result = try UnitConverter.convert(value, from: from, to: to)383        let source = try UnitConverter.unit(from), target = try UnitConverter.unit(to)384        return ToolOutput("\(UnitConverter.format(value)) \(source.symbol) = \(UnitConverter.format(result)) \(target.symbol)")385    }386}387
Files main
Menu

Theme