Repository Public License
1//2// ORIX Audio3// File: ORIXAudio/Services/ExportService.swift4// Description: Builds shareable files: audio encodings, transcripts, notes, analysis reports, PDFs and visualization images.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8//9import CoreText10import Foundation11import ORIXAudioCore12import UIKit1314enum ReportFormat: String, CaseIterable, Identifiable {15 case pdf, markdown, csv, json16 var id: String { rawValue }17 var fileExtension: String { self == .markdown ? "md" : rawValue }18 var displayName: String { switch self { case .pdf: "PDF"; case .markdown: "Markdown"; case .csv: "CSV"; case .json: "JSON" } }19}2021enum ExportError: Error, LocalizedError {22 case missing(String)23 var errorDescription: String? { switch self { case .missing(let what): String(localized: "Nothing to export yet: \(what).") } }24}2526enum ExportService {27 // MARK: Audio2829 /// Encodes the recording (or a time range of it) to `format`. Runs off the main thread.30 static func audio(sourceURL: URL, title: String, duration: Double, format: AudioExportFormat, range: ClosedRange<Double>? = nil,31 progress: (@Sendable (Double) -> Void)? = nil) async throws -> URL {32 let out = LibraryFiles.exportURL(name: title, ext: format.fileExtension)33 try await Task.detached(priority: .userInitiated) {34 var document = EditDocument(sourceName: sourceURL.lastPathComponent, duration: duration)35 if let range { document.crop(to: range) }36 let renderer = try EditRenderer(document: document, sourceURLs: [sourceURL])37 try renderer.export(to: out, format: format, aacBitRate: 128_000 * renderer.channels, progress: progress, isCancelled: { Task.isCancelled })38 }.value39 return out40 }4142 // MARK: Text4344 static func transcript(_ transcript: Transcript, title: String, format: TranscriptFileFormat) throws -> URL {45 let url = LibraryFiles.exportURL(name: title, ext: format.fileExtension)46 let data: Data = switch format {47 case .txt: Data(TranscriptExport.plainText(transcript).utf8)48 case .markdown: Data(TranscriptExport.markdown(transcript, title: title).utf8)49 case .srt: Data(TranscriptExport.srt(transcript).utf8)50 case .vtt: Data(TranscriptExport.vtt(transcript).utf8)51 case .csv: Data(TranscriptExport.csv(transcript).utf8)52 case .json: try TranscriptExport.json(transcript)53 case .pdf: TextPDF.render(title: title, subtitle: String(localized: "Transcript · \(transcript.engine)"), markdownLike: TranscriptExport.plainText(transcript))54 }55 try data.write(to: url, options: .atomic)56 return url57 }5859 static func notes(_ notes: MeetingNotes, transcript: Transcript?, title: String, format: ReportFormat) throws -> URL {60 let markdown = NotesExport.markdown(notes, transcript: transcript)61 let url = LibraryFiles.exportURL(name: "\(title) – Notes", ext: format == .pdf ? "pdf" : format == .json ? "json" : "md")62 let data: Data = switch format {63 case .pdf: TextPDF.render(title: notes.title, subtitle: String(localized: "AI-generated on-device from the transcript"), markdownLike: markdown)64 case .json: try JSONEncoder().encode(notes)65 default: Data(markdown.utf8)66 }67 try data.write(to: url, options: .atomic)68 return url69 }7071 static func report(_ report: AnalysisReport, title: String, format: ReportFormat) throws -> URL {72 let url = LibraryFiles.exportURL(name: "\(title) – Analysis", ext: format.fileExtension)73 let data: Data = switch format {74 case .pdf: TextPDF.render(title: title, subtitle: String(localized: "Audio analysis report"), markdownLike: AnalysisExport.markdown(report, title: title))75 case .markdown: Data(AnalysisExport.markdown(report, title: title).utf8)76 case .csv: Data(AnalysisExport.csv(report).utf8)77 case .json: try AnalysisExport.json(report)78 }79 try data.write(to: url, options: .atomic)80 return url81 }8283 static func image(_ image: CGImage, title: String, suffix: String) throws -> URL {84 let url = LibraryFiles.exportURL(name: "\(title) – \(suffix)", ext: "png")85 guard let data = UIImage(cgImage: image).pngData() else { throw ExportError.missing("image") }86 try data.write(to: url, options: .atomic)87 return url88 }89}9091/// Minimal paginated text PDF (US Letter / A4 by locale), enough for transcripts and reports. Understands "# ", "## ", "- " and "| " lines.92enum TextPDF {93 static func render(title: String, subtitle: String, markdownLike body: String) -> Data {94 let usesLetter = Locale.current.measurementSystem == .us || Locale.current.region?.identifier == "CA"95 let page = usesLetter ? CGRect(x: 0, y: 0, width: 612, height: 792) : CGRect(x: 0, y: 0, width: 595, height: 842)96 let margin: CGFloat = 5497 let text = NSMutableAttributedString()98 let paragraph = NSMutableParagraphStyle(); paragraph.paragraphSpacing = 6; paragraph.lineSpacing = 299 func add(_ s: String, _ font: UIFont, _ color: UIColor = .black) {100 text.append(NSAttributedString(string: s + "\n", attributes: [.font: font, .foregroundColor: color, .paragraphStyle: paragraph]))101 }102 add(title, .systemFont(ofSize: 22, weight: .bold))103 add(subtitle + " · ORIX Audio · " + Date.now.formatted(date: .abbreviated, time: .shortened), .systemFont(ofSize: 10), .darkGray)104 add("", .systemFont(ofSize: 6))105 for raw in body.components(separatedBy: "\n") {106 let line = raw.replacingOccurrences(of: "**", with: "").replacingOccurrences(of: "*", with: "")107 if line.hasPrefix("# ") { continue }108 if line.hasPrefix("## ") { add(String(line.dropFirst(3)), .systemFont(ofSize: 15, weight: .semibold)) }109 else if line.hasPrefix("|---") { continue }110 else if line.hasPrefix("| ") {111 let cells = line.split(separator: "|").map { $0.trimmingCharacters(in: .whitespaces) }112 add(cells.joined(separator: " "), .monospacedDigitSystemFont(ofSize: 10, weight: .regular))113 }114 else if line.hasPrefix("- ") { add("• " + line.dropFirst(2), .systemFont(ofSize: 11)) }115 else { add(line, .systemFont(ofSize: 11)) }116 }117 let framesetter = CTFramesetterCreateWithAttributedString(text)118 let renderer = UIGraphicsPDFRenderer(bounds: page)119 return renderer.pdfData { context in120 var location = 0121 var pageNumber = 1122 repeat {123 context.beginPage()124 let cg = context.cgContext125 cg.saveGState()126 cg.translateBy(x: 0, y: page.height); cg.scaleBy(x: 1, y: -1)127 let path = CGPath(rect: page.insetBy(dx: margin, dy: margin), transform: nil)128 let frame = CTFramesetterCreateFrame(framesetter, CFRange(location: location, length: 0), path, nil)129 CTFrameDraw(frame, cg)130 cg.restoreGState()131 let visible = CTFrameGetVisibleStringRange(frame)132 location += max(1, visible.length)133 let footer = "\(pageNumber)" as NSString134 footer.draw(at: CGPoint(x: page.midX - 4, y: page.height - 34), withAttributes: [.font: UIFont.systemFont(ofSize: 9), .foregroundColor: UIColor.gray])135 pageNumber += 1136 } while location < text.length && pageNumber < 2000137 }138 }139}140