~ knotless Search/
↑↓ move↵ open⇧↵ all results

geesawra.industries/old-fella

Old people's social media app

0
1
main
107 lines · 4.4 KB Raw History
import AVFoundation
import FoundationModels
import PhotosUI
import SwiftUI
import UIKit
import UniformTypeIdentifiers

extension ComposeView {
    @MainActor
    func startAltTextGeneration(for attachment: ImageAttachment) {
        guard !generatingAltText else { return }
        let requestID = UUID()
        altTextRequestID = requestID
        generatingAltText = true
        altTextTask = Task { await generateAltText(for: attachment, requestID: requestID) }
    }

    @MainActor
    func cancelAltTextGeneration() {
        altTextRequestID = nil
        altTextTask?.cancel()
        altTextTask = nil
        generatingAltText = false
    }

    @MainActor
    func generateAltText(for attachment: ImageAttachment, requestID: UUID) async {
        defer {
            if altTextRequestID == requestID {
                altTextRequestID = nil
                altTextTask = nil
                generatingAltText = false
            }
        }
        #if DEBUG
            if await generateTestAltText(for: attachment, requestID: requestID) { return }
        #endif
        guard SystemLanguageModel.default.isAvailable else {
            altTextError = "Apple Intelligence is not available. You can add alt text yourself."
            return
        }
        guard let image = UIImage(data: attachment.data) else {
            altTextError = "The image could not be read. You can add alt text yourself."
            return
        }
        do {
            let session = LanguageModelSession(model: SystemLanguageModel.default)
            let response = try await session.respond {
                """
                Write alt text for this image for someone who cannot see it.

                Describe the important visual content and how it relates to the image's message. If the image \
                contains readable text that matters, include the words as written, in a natural reading order. Do \
                not correct or invent text.

                If the image is a meme or joke, describe the visual setup and explain the apparent joke when it is \
                clear. Do not guess at a meme's name, a person's identity, or meaning that the image does not \
                support.

                Keep the description concise, but do not leave out text or context needed to understand the image. \
                Return only the alt text.
                """
                Attachment(image)
            }
            guard !Task.isCancelled, altTextRequestID == requestID else { return }
            guard !response.content.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
                altTextError = "No description was generated. You can add alt text yourself."
                return
            }
            guard attachments.contains(where: { $0.id == attachment.id && $0.altText == attachment.altText }) else {
                return
            }
            if altTextReview?.id == attachment.id { altTextReview?.draft = response.content }
        } catch {
            guard !Task.isCancelled, altTextRequestID == requestID else { return }
            altTextError = "The description could not be generated. Try again or add alt text yourself."
        }
    }

    #if DEBUG
        @MainActor
        private func generateTestAltText(for attachment: ImageAttachment, requestID: UUID) async -> Bool {
            if usesAltTextTestMode("delayed") {
                await Task.detached { try? await Task.sleep(for: .seconds(3)) }.value
                guard !Task.isCancelled, altTextRequestID == requestID else { return true }
                if altTextReview?.id == attachment.id { altTextReview?.draft = "A delayed description" }
                return true
            }
            if usesAltTextTestMode("success") {
                if altTextReview?.id == attachment.id { altTextReview?.draft = "A generated description" }
                return true
            }
            if usesAltTextTestMode("failure") {
                altTextError = "The description could not be generated. Try again or add alt text yourself."
                return true
            }
            return false
        }

        private func usesAltTextTestMode(_ mode: String) -> Bool {
            let arguments = ProcessInfo.processInfo.arguments
            return altTextTestMode == mode
                || (arguments.contains("-ui-testing") && arguments.contains("-ui-testing-alt-\(mode)"))
        }
    #endif

}