Last active
January 11, 2024 07:54
-
-
Save pitt500/8f626b0438f0cd7605b0716e1fb6060e to your computer and use it in GitHub Desktop.
Demo code used for https://youtu.be/JtPoqgNJohQ
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
import SensitiveContentAnalysis | |
struct ContentView: View { | |
enum AnalysisState { | |
case notStarted | |
case analyzing | |
case isSensitive | |
case notSensitive | |
case error(message: String) | |
} | |
@State private var analysisState: AnalysisState = .notStarted | |
@State private var errorMessage = "" | |
var body: some View { | |
VStack { | |
HStack(spacing: 100) { | |
Button { | |
Task { | |
await analyze(imageName: "pitt") | |
} | |
} label: { | |
Text("Pitt") | |
.font(.largeTitle) | |
} | |
Button { | |
Task { | |
await analyze(imageName: "lena") | |
} | |
} label: { | |
Text("Lena") | |
.font(.largeTitle) | |
} | |
} | |
.padding(.bottom, 50) | |
Group { | |
switch analysisState { | |
case .notStarted: | |
EmptyView() | |
case .isSensitive: | |
Text("Warning! Image contains nudity ⚠️") | |
case .notSensitive: | |
Text("The image is safe ✅") | |
case .analyzing: | |
ProgressView() | |
case .error(let message): | |
Text("Error analyzing image. \(message)") | |
.foregroundStyle(Color.red) | |
} | |
} | |
.font(.largeTitle) | |
} | |
.padding() | |
} | |
func analyze(imageName: String) async { | |
analysisState = .analyzing | |
let analyzer = SCSensitivityAnalyzer() | |
let policy = analyzer.analysisPolicy | |
if policy == .disabled { | |
print("Policy is disabled") | |
analysisState = .error(message: "Policy is disabled") | |
return | |
} | |
do { | |
guard let image = UIImage(named: imageName) | |
else { | |
print("Image not found") | |
analysisState = .error(message: "Image not found") | |
return | |
} | |
let response = try await analyzer.analyzeImage(image.cgImage!) | |
analysisState = if response.isSensitive { | |
.isSensitive | |
} else { | |
.notSensitive | |
} | |
} catch { | |
analysisState = .error(message: error.localizedDescription) | |
print("Unable to get a response", error) | |
} | |
} | |
} | |
#Preview { | |
ContentView() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment