Skip to content

Swift: Added example code for text to image generation with Amazon Nova Canvas for Bedrock #7452

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 7 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .doc_gen/metadata/bedrock-runtime_metadata.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -1383,6 +1383,14 @@ bedrock-runtime_InvokeModel_AmazonNovaImageGeneration:
- description: Create an image with the Amazon Nova Canvas.
snippet_tags:
- python.example_code.bedrock-runtime.InvokeModel_AmazonNovaImageGeneration
Swift:
versions:
- sdk_version: 1
github: swift/example_code/bedrock-runtime
excerpts:
- description: Create an image with Amazon Nova Canvas.
snippet_tags:
- swift.example_code.bedrock-runtime.InvokeModel_AmazonNovaImageGeneration
services:
bedrock-runtime: {InvokeModel}

Expand Down
4 changes: 4 additions & 0 deletions swift/example_code/bedrock-runtime/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@ For prerequisites, see the [README](../../README.md#Prerequisites) in the `swift
- [Converse](models/amazon-nova/amazon-nova-text/Sources/Converse/main.swift#L4)
- [ConverseStream](models/amazon-nova/amazon-nova-text/Sources/ConverseStream/main.swift#L4)

### Amazon Nova Canvas

- [InvokeModel](models/amazon-nova/amazon_nova_canvas/Sources/main.swift#L4)

### Anthropic Claude

- [Converse](models/anthropic_claude/Sources/Converse/main.swift#L4)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// swift-tools-version: 6.1
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//
// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescription

let package = Package(
name: "AmazonNovaCanvas",
// Let Xcode know the minimum Apple platforms supported.
platforms: [
.macOS(.v13),
.iOS(.v15)
],
dependencies: [
// Dependencies declare other packages that this package depends on.
.package(url: "https://github.com/awslabs/aws-sdk-swift", from: "1.2.61")
],
targets: [
// Targets are the basic building blocks of a package, defining a module or a test suite.
// Targets can depend on other targets in this package and products from dependencies.
.executableTarget(
name: "InvokeModel",
dependencies: [
.product(name: "AWSBedrockRuntime", package: "aws-sdk-swift"),
],
path: "Sources"
)
]
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//
// snippet-start:[swift.example_code.bedrock-runtime.InvokeModel_AmazonNovaImageGeneration]
// Use the native inference API to create an image with Amazon Nova Canvas

import AWSBedrockRuntime
import AWSSDKIdentity
import Foundation

struct NovaImageOutput: Decodable {
let images: [Data]
}

func generateImage(_ textPrompt: String) async throws {
// Create a Bedrock Runtime client in the AWS Region you want to use.
let config =
try await BedrockRuntimeClient.BedrockRuntimeClientConfiguration(
region: "us-east-1"
)
config.awsCredentialIdentityResolver = try SSOAWSCredentialIdentityResolver()

let client = BedrockRuntimeClient(config: config)

// Set the model ID.
let modelId = "amazon.nova-canvas-v1:0"

// Format the request payload using the model's native structure.
let input = InvokeModelInput(
accept: "application/json",
body: """
{
"textToImageParams": {
"text": "\(textPrompt)"
},
"taskType": "TEXT_IMAGE",
"imageGenerationConfig": {
"seed": 42,
"quality": "standard",
"width": 512,
"height": 512,
"numberOfImages": 1
}
}
""".data(using: .utf8),
modelId: modelId
)

// Invoke the model with the request.
let response = try await client.invokeModel(input: input)

// Decode the response body.
let output = try JSONDecoder().decode(NovaImageOutput.self, from: response.body!)

// Extract the image data.
guard let data = output.images.first else {
print("No image data found")
return
}

// Save the generated image to a local folder.
let fileURL = URL.documentsDirectory.appending(path: "nova_canvas.png")
print(fileURL)
try data.write(to: fileURL)
print("Image is saved at \(fileURL)")
}

// snippet-end:[swift.example_code.bedrock-runtime.InvokeModel_AmazonNovaImageGeneration]

do {
try await generateImage(
"A tabby cat in a teacup"
)
} catch {
print("An error occurred: \(error)")
}
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.