PhotoReasoningViewModel.swift 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. // Copyright 2023 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. import FirebaseVertexAI
  15. import Foundation
  16. import OSLog
  17. import PhotosUI
  18. import SwiftUI
  19. @MainActor
  20. class PhotoReasoningViewModel: ObservableObject {
  21. // Maximum value for the larger of the two image dimensions (height and width) in pixels. This is
  22. // being used to reduce the image size in bytes.
  23. private static let largestImageDimension = 768.0
  24. private var logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "generative-ai")
  25. @Published
  26. var userInput: String = ""
  27. @Published
  28. var selectedItems = [PhotosPickerItem]()
  29. @Published
  30. var outputText: String? = nil
  31. @Published
  32. var errorMessage: String?
  33. @Published
  34. var inProgress = false
  35. private var model: GenerativeModel?
  36. init() {
  37. model = VertexAI.vertexAI().generativeModel(modelName: "gemini-1.5-flash")
  38. }
  39. func reason() async {
  40. defer {
  41. inProgress = false
  42. }
  43. guard let model else {
  44. return
  45. }
  46. do {
  47. inProgress = true
  48. errorMessage = nil
  49. outputText = ""
  50. let prompt = "Look at the image(s), and then answer the following question: \(userInput)"
  51. var images = [any PartsRepresentable]()
  52. for item in selectedItems {
  53. if let data = try? await item.loadTransferable(type: Data.self) {
  54. guard let image = UIImage(data: data) else {
  55. logger.error("Failed to parse data as an image, skipping.")
  56. continue
  57. }
  58. if image.size.fits(largestDimension: PhotoReasoningViewModel.largestImageDimension) {
  59. images.append(image)
  60. } else {
  61. guard let resizedImage = image
  62. .preparingThumbnail(of: image.size
  63. .aspectFit(largestDimension: PhotoReasoningViewModel.largestImageDimension)) else {
  64. logger.error("Failed to resize image: \(image)")
  65. continue
  66. }
  67. images.append(resizedImage)
  68. }
  69. }
  70. }
  71. let outputContentStream = try model.generateContentStream(prompt, images)
  72. // stream response
  73. for try await outputContent in outputContentStream {
  74. guard let line = outputContent.text else {
  75. return
  76. }
  77. outputText = (outputText ?? "") + line
  78. }
  79. } catch {
  80. logger.error("\(error.localizedDescription)")
  81. errorMessage = error.localizedDescription
  82. }
  83. }
  84. }
  85. private extension CGSize {
  86. func fits(largestDimension length: CGFloat) -> Bool {
  87. return width <= length && height <= length
  88. }
  89. func aspectFit(largestDimension length: CGFloat) -> CGSize {
  90. let aspectRatio = width / height
  91. if width > height {
  92. let width = min(self.width, length)
  93. return CGSize(width: width, height: round(width / aspectRatio))
  94. } else {
  95. let height = min(self.height, length)
  96. return CGSize(width: round(height * aspectRatio), height: height)
  97. }
  98. }
  99. }