new features
This commit is contained in:
+95
-6
@@ -1,6 +1,9 @@
|
||||
import Foundation
|
||||
import PDFKit
|
||||
import NaturalLanguage
|
||||
import Vision
|
||||
import ImageIO
|
||||
import UniformTypeIdentifiers
|
||||
|
||||
struct LibraryDocument: Identifiable, Equatable {
|
||||
let id: UUID
|
||||
@@ -24,11 +27,7 @@ enum LibraryImport {
|
||||
let text: String
|
||||
switch url.pathExtension.lowercased() {
|
||||
case "pdf":
|
||||
guard let document = PDFDocument(url: url), !document.isLocked,
|
||||
document.pageCount <= 500 else {
|
||||
throw StudioError("Choose an unlocked PDF with up to 500 pages.")
|
||||
}
|
||||
text = document.string ?? ""
|
||||
text = try openPDF(url).string ?? ""
|
||||
case "txt", "md", "markdown", "csv":
|
||||
text = try String(contentsOf: url, encoding: .utf8)
|
||||
default:
|
||||
@@ -37,6 +36,17 @@ enum LibraryImport {
|
||||
return try chunks(text)
|
||||
}
|
||||
|
||||
// Callers keep security-scoped access open while reading pages.
|
||||
fileprivate static func openPDF(_ url: URL) throws -> PDFDocument {
|
||||
guard let document = PDFDocument(url: url) else {
|
||||
throw StudioError("This PDF could not be opened.")
|
||||
}
|
||||
guard !document.isLocked else { throw StudioError("Unlock this PDF before opening it.") }
|
||||
guard document.pageCount > 0 else { throw StudioError("This PDF contains no pages.") }
|
||||
guard document.pageCount <= 500 else { throw StudioError("Choose a PDF with up to 500 pages.") }
|
||||
return document
|
||||
}
|
||||
|
||||
static func chunks(_ text: String) throws -> [String] {
|
||||
let words = text.split(whereSeparator: \.isWhitespace)
|
||||
guard !words.isEmpty else { throw StudioError("The document contains no extractable text.") }
|
||||
@@ -914,6 +924,8 @@ struct ChatFilePreview: Identifiable, Sendable {
|
||||
let id = UUID()
|
||||
let name: String
|
||||
let text: String
|
||||
var isPDF = false
|
||||
var imagePNG: Data? = nil
|
||||
|
||||
static func read(_ url: URL) throws -> Self {
|
||||
let scoped = url.startAccessingSecurityScopedResource()
|
||||
@@ -928,13 +940,90 @@ struct ChatFilePreview: Identifiable, Sendable {
|
||||
(names.isEmpty ? "(Empty)" : names.joined(separator: "\n")) +
|
||||
(entries.count > 75 ? "\n[Listing limited to 75 entries]" : "")
|
||||
} else if url.pathExtension.lowercased() == "pdf" {
|
||||
text = try LibraryImport.chunks(at: url).prefix(5).joined(separator: "\n\n")
|
||||
return Self(name: url.lastPathComponent, text: try pdfText(at: url), isPDF: true)
|
||||
} else if UTType(filenameExtension: url.pathExtension)?.conforms(to: .image) == true {
|
||||
return try imagePreview(at: url)
|
||||
} else {
|
||||
text = try LocalFilePreview.read(url, limit: 7500)
|
||||
}
|
||||
let bounded = text.count > 8000 ? String(text.prefix(7960)) + "\n[Preview truncated]" : text
|
||||
return Self(name: url.lastPathComponent, text: bounded)
|
||||
}
|
||||
|
||||
private static func imagePreview(at url: URL) throws -> Self {
|
||||
let values = try url.resourceValues(forKeys: [.isRegularFileKey, .fileSizeKey])
|
||||
guard values.isRegularFile == true, let size = values.fileSize, size <= 20_000_000 else {
|
||||
throw StudioError("Choose an image file up to 20 MB.")
|
||||
}
|
||||
guard let source = CGImageSourceCreateWithURL(url as CFURL, nil),
|
||||
let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any],
|
||||
let width = properties[kCGImagePropertyPixelWidth] as? Int,
|
||||
let height = properties[kCGImagePropertyPixelHeight] as? Int, width > 0, height > 0 else {
|
||||
throw StudioError("This image could not be opened.")
|
||||
}
|
||||
guard CGImageSourceGetCount(source) == 1 else {
|
||||
throw StudioError("Choose a single-frame image.")
|
||||
}
|
||||
guard width <= 40_000_000 / height else {
|
||||
throw StudioError("Choose an image up to 40 megapixels.")
|
||||
}
|
||||
// Apply EXIF orientation at the original pixel dimensions.
|
||||
let options: [CFString: Any] = [
|
||||
kCGImageSourceCreateThumbnailFromImageAlways: true,
|
||||
kCGImageSourceCreateThumbnailWithTransform: true,
|
||||
kCGImageSourceThumbnailMaxPixelSize: max(width, height)
|
||||
]
|
||||
let png = NSMutableData()
|
||||
guard let image = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary),
|
||||
let destination = CGImageDestinationCreateWithData(png, UTType.png.identifier as CFString, 1, nil) else {
|
||||
throw StudioError("This image could not be decoded.")
|
||||
}
|
||||
CGImageDestinationAddImage(destination, image, nil)
|
||||
guard CGImageDestinationFinalize(destination), png.length <= 20_000_000 else {
|
||||
throw StudioError("The image exceeds 20 MB when converted to PNG.")
|
||||
}
|
||||
let text = (try? recognizeText(in: image)) ?? ""
|
||||
return Self(name: url.lastPathComponent, text: text, imagePNG: png as Data)
|
||||
}
|
||||
|
||||
private static func pdfText(at url: URL) throws -> String {
|
||||
let values = try url.resourceValues(forKeys: [.isRegularFileKey, .fileSizeKey])
|
||||
guard values.isRegularFile == true else { throw StudioError("Select a regular PDF file.") }
|
||||
guard let bytes = values.fileSize, bytes <= 20_000_000 else {
|
||||
throw StudioError("Choose a PDF up to 20 MB.")
|
||||
}
|
||||
let document = try LibraryImport.openPDF(url)
|
||||
var pages: [String] = []
|
||||
for index in 0..<document.pageCount {
|
||||
guard let page = document.page(at: index) else {
|
||||
throw StudioError("Page \(index + 1) of this PDF could not be opened.")
|
||||
}
|
||||
let embedded = page.string?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
|
||||
let text = embedded.isEmpty ? try recognizeText(on: page) : embedded
|
||||
guard !text.isEmpty else { continue }
|
||||
pages.append("Page \(index + 1)\n\(text)")
|
||||
}
|
||||
guard !pages.isEmpty else { throw StudioError("No readable text was found in this PDF.") }
|
||||
return pages.joined(separator: "\n\n")
|
||||
}
|
||||
|
||||
private static func recognizeText(on page: PDFPage) throws -> String {
|
||||
try autoreleasepool {
|
||||
let thumbnail = page.thumbnail(of: CGSize(width: 1800, height: 1800), for: .cropBox)
|
||||
guard let image = thumbnail.cgImage(forProposedRect: nil, context: nil, hints: nil) else {
|
||||
throw StudioError("A scanned PDF page could not be rendered.")
|
||||
}
|
||||
return try recognizeText(in: image)
|
||||
}
|
||||
}
|
||||
|
||||
private static func recognizeText(in image: CGImage) throws -> String {
|
||||
let request = VNRecognizeTextRequest()
|
||||
request.recognitionLevel = .accurate
|
||||
request.automaticallyDetectsLanguage = true
|
||||
try VNImageRequestHandler(cgImage: image).perform([request])
|
||||
return (request.results ?? []).compactMap { $0.topCandidates(1).first?.string }.joined(separator: "\n")
|
||||
}
|
||||
}
|
||||
|
||||
private final class RSSSearch: NSObject, XMLParserDelegate {
|
||||
|
||||
Reference in New Issue
Block a user