// photo2csv: a table photo to CSV on a Mac (macOS 26 or later). Free, and it uploads nothing.
// Build: swiftc -O photo2csv.swift -o photo2csv    Run: ./photo2csv table.jpg > table.csv
import CoreImage
import Foundation
import Vision

let url = URL(fileURLWithPath: CommandLine.arguments[1])
var image = CIImage(contentsOf: url)!

// 1. Straighten: find the page and pull its 4 corners flat, as a scanner app does.
//    Only when Vision is sure (a flat scan gives a low score and a wrong page shape).
let page = VNDetectDocumentSegmentationRequest()
try VNImageRequestHandler(url: url).perform([page])
if let p = page.results?.first, p.confidence >= 0.95 {
    let size = image.extent.size
    let pt = { (q: CGPoint) in CIVector(x: q.x * size.width, y: q.y * size.height) }
    image = image.applyingFilter("CIPerspectiveCorrection", parameters: [
        "inputTopLeft": pt(p.topLeft), "inputTopRight": pt(p.topRight),
        "inputBottomLeft": pt(p.bottomLeft), "inputBottomRight": pt(p.bottomRight),
    ])
}
let flat = CIContext().createCGImage(image, from: image.extent)!

// 2. Read the tables, cell by cell, and print them as CSV (a blank line between tables).
let doc = try await RecognizeDocumentsRequest().perform(on: flat)
let csv = { (s: String) in "\"" + s.replacingOccurrences(of: "\"", with: "\"\"") + "\"" }
for table in doc.flatMap({ $0.document.tables }) {
    for row in table.rows {
        print(row.map { csv($0.content.text.transcript.split(whereSeparator: \.isWhitespace).joined(separator: " ")) }
            .joined(separator: ","))
    }
    print()
}
