diff --git a/src/libs/StabilityAI/Generated/StabilityAI.AudioResultsClient.FetchAudioResult.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.AudioResultsClient.FetchAudioResult.g.cs index 9286ecd..faad068 100644 --- a/src/libs/StabilityAI/Generated/StabilityAI.AudioResultsClient.FetchAudioResult.g.cs +++ b/src/libs/StabilityAI/Generated/StabilityAI.AudioResultsClient.FetchAudioResult.g.cs @@ -218,6 +218,10 @@ partial void ProcessFetchAudioResultResponseContent( __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || diff --git a/src/libs/StabilityAI/Generated/StabilityAI.AudioResultsClient.FetchAudioResultAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.AudioResultsClient.FetchAudioResultAsBytes.g.cs new file mode 100644 index 0000000..002566a --- /dev/null +++ b/src/libs/StabilityAI/Generated/StabilityAI.AudioResultsClient.FetchAudioResultAsBytes.g.cs @@ -0,0 +1,1150 @@ + +#nullable enable + +namespace StabilityAI +{ + public partial class AudioResultsClient + { + + + private static readonly global::StabilityAI.EndPointSecurityRequirement s_FetchAudioResultAsBytesSecurityRequirement0 = + new global::StabilityAI.EndPointSecurityRequirement + { + Authorizations = new global::StabilityAI.EndPointAuthorizationRequirement[] + { new global::StabilityAI.EndPointAuthorizationRequirement + { + Type = "Http", + SchemeId = "HttpBearer", + Location = "Header", + Name = "Bearer", + FriendlyName = "Bearer", + }, + }, + }; + private static readonly global::StabilityAI.EndPointSecurityRequirement[] s_FetchAudioResultAsBytesSecurityRequirements = + new global::StabilityAI.EndPointSecurityRequirement[] + { s_FetchAudioResultAsBytesSecurityRequirement0, + }; + partial void PrepareFetchAudioResultAsBytesArguments( + global::System.Net.Http.HttpClient httpClient, + ref string id, + ref global::StabilityAI.FetchAudioResultAccept? accept, + ref string? stabilityClientId, + ref string? stabilityClientUserId, + ref string? stabilityClientVersion); + partial void PrepareFetchAudioResultAsBytesRequest( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpRequestMessage httpRequestMessage, + string id, + global::StabilityAI.FetchAudioResultAccept? accept, + string? stabilityClientId, + string? stabilityClientUserId, + string? stabilityClientVersion); + partial void ProcessFetchAudioResultAsBytesResponse( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpResponseMessage httpResponseMessage); + + partial void ProcessFetchAudioResultAsBytesResponseContent( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpResponseMessage httpResponseMessage, + ref byte[] content); + + /// + /// Fetch Audio Result
+ /// Fetch the result of an audio generation by ID.
+ /// Poll this endpoint after starting an async audio generation. Returns `202` while
+ /// in-progress, `200` with the audio when complete. + ///
+ /// + /// The `id` of a generation, typically used for async generations, that can be used to check the status of the generation or retrieve the result.
+ /// Example: a6dc6c6e20acda010fe14d71f180658f2896ed9b4ec25aa99a6ff06c796987c4 + /// + /// + /// Specify `audio/*` to receive the bytes of the audio directly. Otherwise specify `application/json` to receive the audio as base64 encoded JSON.
+ /// Default Value: audio/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// generation_id = "e52772ac75b..."
+ /// result = requests.get(
+ /// f"https://api.stability.ai/v2beta/audio/results/{generation_id}",
+ /// headers={"authorization": f"Bearer sk-MYAPIKEY", "accept": "audio/*"},
+ /// )
+ /// if result.status_code == 202:
+ /// print("Generation is still in-progress.")
+ /// elif result.status_code == 200:
+ /// with open("./output.mp3", "wb") as f:
+ /// f.write(result.content)
+ /// print("Download complete!")
+ /// else:
+ /// raise Exception(str(result.json())) + ///
+ public async global::System.Threading.Tasks.Task FetchAudioResultAsBytesAsync( + string id, + global::StabilityAI.FetchAudioResultAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + var __response = await FetchAudioResultAsBytesAsResponseAsync( + id: id, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + requestOptions: requestOptions, + cancellationToken: cancellationToken + ).ConfigureAwait(false); + + return __response.Body; + } + /// + /// Fetch Audio Result
+ /// Fetch the result of an audio generation by ID.
+ /// Poll this endpoint after starting an async audio generation. Returns `202` while
+ /// in-progress, `200` with the audio when complete. + ///
+ /// + /// The `id` of a generation, typically used for async generations, that can be used to check the status of the generation or retrieve the result.
+ /// Example: a6dc6c6e20acda010fe14d71f180658f2896ed9b4ec25aa99a6ff06c796987c4 + /// + /// + /// Specify `audio/*` to receive the bytes of the audio directly. Otherwise specify `application/json` to receive the audio as base64 encoded JSON.
+ /// Default Value: audio/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// generation_id = "e52772ac75b..."
+ /// result = requests.get(
+ /// f"https://api.stability.ai/v2beta/audio/results/{generation_id}",
+ /// headers={"authorization": f"Bearer sk-MYAPIKEY", "accept": "audio/*"},
+ /// )
+ /// if result.status_code == 202:
+ /// print("Generation is still in-progress.")
+ /// elif result.status_code == 200:
+ /// with open("./output.mp3", "wb") as f:
+ /// f.write(result.content)
+ /// print("Download complete!")
+ /// else:
+ /// raise Exception(str(result.json())) + ///
+ public async global::System.Threading.Tasks.Task FetchAudioResultAsBytesAsStreamAsync( + string id, + global::StabilityAI.FetchAudioResultAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + PrepareArguments( + client: HttpClient); + PrepareFetchAudioResultAsBytesArguments( + httpClient: HttpClient, + id: ref id, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_FetchAudioResultAsBytesSecurityRequirements, + operationName: "FetchAudioResultAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: true); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: $"/v2beta/audio/results/{id}", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Get, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "audio/mpeg"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareFetchAudioResultAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + id: id!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "FetchAudioResultAsBytes", + methodName: "FetchAudioResultAsBytesAsync", + pathTemplate: "$\"/v2beta/audio/results/{id}\"", + httpMethod: "GET", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseHeadersRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "FetchAudioResultAsBytes", + methodName: "FetchAudioResultAsBytesAsync", + pathTemplate: "$\"/v2beta/audio/results/{id}\"", + httpMethod: "GET", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "FetchAudioResultAsBytes", + methodName: "FetchAudioResultAsBytesAsync", + pathTemplate: "$\"/v2beta/audio/results/{id}\"", + httpMethod: "GET", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + try + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessFetchAudioResultAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "FetchAudioResultAsBytes", + methodName: "FetchAudioResultAsBytesAsync", + pathTemplate: "$\"/v2beta/audio/results/{id}\"", + httpMethod: "GET", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "FetchAudioResultAsBytes", + methodName: "FetchAudioResultAsBytesAsync", + pathTemplate: "$\"/v2beta/audio/results/{id}\"", + httpMethod: "GET", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.FetchAudioResultResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.FetchAudioResultResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.FetchAudioResultResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // id: the generation either does not exist or has expired. + if ((int)__response.StatusCode == 404) + { + string? __content_404 = null; + global::System.Exception? __exception_404 = null; + global::StabilityAI.FetchAudioResultResponse5? __value_404 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_404 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_404 = global::StabilityAI.FetchAudioResultResponse5.FromJson(__content_404, JsonSerializerContext); + } + else + { + __content_404 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_404 = global::StabilityAI.FetchAudioResultResponse5.FromJson(__content_404, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_404 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_404 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_404, + responseBody: __content_404, + responseObject: __value_404, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.FetchAudioResultResponse6? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.FetchAudioResultResponse6.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.FetchAudioResultResponse6.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + try + { + __response.EnsureSuccessStatusCode(); + + var __content = await __response.Content.ReadAsStreamAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.ResponseStream(__response, __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + } + catch + { + __response.Dispose(); + throw; + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Fetch Audio Result
+ /// Fetch the result of an audio generation by ID.
+ /// Poll this endpoint after starting an async audio generation. Returns `202` while
+ /// in-progress, `200` with the audio when complete. + ///
+ /// + /// The `id` of a generation, typically used for async generations, that can be used to check the status of the generation or retrieve the result.
+ /// Example: a6dc6c6e20acda010fe14d71f180658f2896ed9b4ec25aa99a6ff06c796987c4 + /// + /// + /// Specify `audio/*` to receive the bytes of the audio directly. Otherwise specify `application/json` to receive the audio as base64 encoded JSON.
+ /// Default Value: audio/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// generation_id = "e52772ac75b..."
+ /// result = requests.get(
+ /// f"https://api.stability.ai/v2beta/audio/results/{generation_id}",
+ /// headers={"authorization": f"Bearer sk-MYAPIKEY", "accept": "audio/*"},
+ /// )
+ /// if result.status_code == 202:
+ /// print("Generation is still in-progress.")
+ /// elif result.status_code == 200:
+ /// with open("./output.mp3", "wb") as f:
+ /// f.write(result.content)
+ /// print("Download complete!")
+ /// else:
+ /// raise Exception(str(result.json())) + ///
+ public async global::System.Threading.Tasks.Task> FetchAudioResultAsBytesAsResponseAsync( + string id, + global::StabilityAI.FetchAudioResultAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + PrepareArguments( + client: HttpClient); + PrepareFetchAudioResultAsBytesArguments( + httpClient: HttpClient, + id: ref id, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_FetchAudioResultAsBytesSecurityRequirements, + operationName: "FetchAudioResultAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: true); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: $"/v2beta/audio/results/{id}", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Get, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "audio/mpeg"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareFetchAudioResultAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + id: id!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "FetchAudioResultAsBytes", + methodName: "FetchAudioResultAsBytesAsync", + pathTemplate: "$\"/v2beta/audio/results/{id}\"", + httpMethod: "GET", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "FetchAudioResultAsBytes", + methodName: "FetchAudioResultAsBytesAsync", + pathTemplate: "$\"/v2beta/audio/results/{id}\"", + httpMethod: "GET", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "FetchAudioResultAsBytes", + methodName: "FetchAudioResultAsBytesAsync", + pathTemplate: "$\"/v2beta/audio/results/{id}\"", + httpMethod: "GET", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessFetchAudioResultAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "FetchAudioResultAsBytes", + methodName: "FetchAudioResultAsBytesAsync", + pathTemplate: "$\"/v2beta/audio/results/{id}\"", + httpMethod: "GET", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "FetchAudioResultAsBytes", + methodName: "FetchAudioResultAsBytesAsync", + pathTemplate: "$\"/v2beta/audio/results/{id}\"", + httpMethod: "GET", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.FetchAudioResultResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.FetchAudioResultResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.FetchAudioResultResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // id: the generation either does not exist or has expired. + if ((int)__response.StatusCode == 404) + { + string? __content_404 = null; + global::System.Exception? __exception_404 = null; + global::StabilityAI.FetchAudioResultResponse5? __value_404 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_404 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_404 = global::StabilityAI.FetchAudioResultResponse5.FromJson(__content_404, JsonSerializerContext); + } + else + { + __content_404 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_404 = global::StabilityAI.FetchAudioResultResponse5.FromJson(__content_404, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_404 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_404 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_404, + responseBody: __content_404, + responseObject: __value_404, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.FetchAudioResultResponse6? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.FetchAudioResultResponse6.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.FetchAudioResultResponse6.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessFetchAudioResultAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + } +} \ No newline at end of file diff --git a/src/libs/StabilityAI/Generated/StabilityAI.ControlClient.CreateStableImageControlSketch.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.ControlClient.CreateStableImageControlSketch.g.cs index 2be8dde..fdde785 100644 --- a/src/libs/StabilityAI/Generated/StabilityAI.ControlClient.CreateStableImageControlSketch.g.cs +++ b/src/libs/StabilityAI/Generated/StabilityAI.ControlClient.CreateStableImageControlSketch.g.cs @@ -291,6 +291,10 @@ partial void ProcessCreateStableImageControlSketchResponseContent( __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || @@ -328,42 +332,6 @@ partial void ProcessCreateStableImageControlSketchResponseContent( var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"accept\""); - - } - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } __httpRequestContent.Add( content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), name: "\"prompt\""); @@ -1311,6 +1279,10 @@ request.Imagename is null __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || @@ -1348,42 +1320,6 @@ request.Imagename is null var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"accept\""); - - } - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } __httpRequestContent.Add( content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), name: "\"prompt\""); @@ -2180,6 +2116,10 @@ request.Imagename is null __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || @@ -2217,42 +2157,6 @@ request.Imagename is null var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"accept\""); - - } - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } __httpRequestContent.Add( content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), name: "\"prompt\""); diff --git a/src/libs/StabilityAI/Generated/StabilityAI.ControlClient.CreateStableImageControlSketchAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.ControlClient.CreateStableImageControlSketchAsBytes.g.cs new file mode 100644 index 0000000..a2a007a --- /dev/null +++ b/src/libs/StabilityAI/Generated/StabilityAI.ControlClient.CreateStableImageControlSketchAsBytes.g.cs @@ -0,0 +1,4268 @@ + +#nullable enable + +namespace StabilityAI +{ + public partial class ControlClient + { + + + private static readonly global::StabilityAI.EndPointSecurityRequirement s_CreateStableImageControlSketchAsBytesSecurityRequirement0 = + new global::StabilityAI.EndPointSecurityRequirement + { + Authorizations = new global::StabilityAI.EndPointAuthorizationRequirement[] + { new global::StabilityAI.EndPointAuthorizationRequirement + { + Type = "Http", + SchemeId = "HttpBearer", + Location = "Header", + Name = "Bearer", + FriendlyName = "Bearer", + }, + }, + }; + private static readonly global::StabilityAI.EndPointSecurityRequirement[] s_CreateStableImageControlSketchAsBytesSecurityRequirements = + new global::StabilityAI.EndPointSecurityRequirement[] + { s_CreateStableImageControlSketchAsBytesSecurityRequirement0, + }; + partial void PrepareCreateStableImageControlSketchAsBytesArguments( + global::System.Net.Http.HttpClient httpClient, + ref string contentType, + ref global::StabilityAI.CreateStableImageControlSketchAccept? accept, + ref string? stabilityClientId, + ref string? stabilityClientUserId, + ref string? stabilityClientVersion, + global::StabilityAI.CreateStableImageControlSketchRequest request); + partial void PrepareCreateStableImageControlSketchAsBytesRequest( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpRequestMessage httpRequestMessage, + string contentType, + global::StabilityAI.CreateStableImageControlSketchAccept? accept, + string? stabilityClientId, + string? stabilityClientUserId, + string? stabilityClientVersion, + global::StabilityAI.CreateStableImageControlSketchRequest request); + partial void ProcessCreateStableImageControlSketchAsBytesResponse( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpResponseMessage httpResponseMessage); + + partial void ProcessCreateStableImageControlSketchAsBytesResponseContent( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpResponseMessage httpResponseMessage, + ref byte[] content); + + /// + /// Sketch
+ /// This service offers an ideal solution for design projects that require brainstorming and
+ /// frequent iterations. It upgrades rough hand-drawn sketches to refined outputs with precise
+ /// control. For non-sketch images, it allows detailed manipulation of the final appearance by
+ /// leveraging the contour lines and edges within the image.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=ZKIAqHzJzzUo)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `control_strength`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will match that of the input image.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/sketch",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./sketch.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a medieval castle on a hill",
+ /// "control_strength": 0.7,
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./castle.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateStableImageControlSketchAsBytesAsync( + string contentType, + + global::StabilityAI.CreateStableImageControlSketchRequest request, + global::StabilityAI.CreateStableImageControlSketchAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + var __response = await CreateStableImageControlSketchAsBytesAsResponseAsync( + contentType: contentType, + + request: request, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + requestOptions: requestOptions, + cancellationToken: cancellationToken + ).ConfigureAwait(false); + + return __response.Body; + } + /// + /// Sketch
+ /// This service offers an ideal solution for design projects that require brainstorming and
+ /// frequent iterations. It upgrades rough hand-drawn sketches to refined outputs with precise
+ /// control. For non-sketch images, it allows detailed manipulation of the final appearance by
+ /// leveraging the contour lines and edges within the image.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=ZKIAqHzJzzUo)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `control_strength`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will match that of the input image.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/sketch",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./sketch.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a medieval castle on a hill",
+ /// "control_strength": 0.7,
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./castle.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateStableImageControlSketchAsBytesAsStreamAsync( + string contentType, + + global::StabilityAI.CreateStableImageControlSketchRequest request, + global::StabilityAI.CreateStableImageControlSketchAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + request = request ?? throw new global::System.ArgumentNullException(nameof(request)); + + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageControlSketchAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageControlSketchAsBytesSecurityRequirements, + operationName: "CreateStableImageControlSketchAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/control/sketch", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/png"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + var __contentImage = new global::System.Net.Http.ByteArrayContent(request.Image ?? global::System.Array.Empty()); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.ControlStrength != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.ControlStrength, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"control_strength\""); + + } + if (request.NegativePrompt != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty), + name: "\"negative_prompt\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + if (request.StylePreset != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.StylePreset).HasValue ? (request.StylePreset).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"style_preset\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageControlSketchAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlSketchAsBytes", + methodName: "CreateStableImageControlSketchAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/sketch\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseHeadersRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlSketchAsBytes", + methodName: "CreateStableImageControlSketchAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/sketch\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlSketchAsBytes", + methodName: "CreateStableImageControlSketchAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/sketch\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + try + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageControlSketchAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlSketchAsBytes", + methodName: "CreateStableImageControlSketchAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/sketch\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlSketchAsBytes", + methodName: "CreateStableImageControlSketchAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/sketch\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageControlSketchResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageControlSketchResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageControlSketchResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageControlSketchResponse5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageControlSketchResponse5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageControlSketchResponse5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateStableImageControlSketchResponse6? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateStableImageControlSketchResponse6.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateStableImageControlSketchResponse6.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageControlSketchResponse7? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageControlSketchResponse7.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageControlSketchResponse7.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageControlSketchResponse8? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageControlSketchResponse8.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageControlSketchResponse8.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + try + { + __response.EnsureSuccessStatusCode(); + + var __content = await __response.Content.ReadAsStreamAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.ResponseStream(__response, __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + } + catch + { + __response.Dispose(); + throw; + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Sketch
+ /// This service offers an ideal solution for design projects that require brainstorming and
+ /// frequent iterations. It upgrades rough hand-drawn sketches to refined outputs with precise
+ /// control. For non-sketch images, it allows detailed manipulation of the final appearance by
+ /// leveraging the contour lines and edges within the image.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=ZKIAqHzJzzUo)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `control_strength`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will match that of the input image.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/sketch",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./sketch.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a medieval castle on a hill",
+ /// "control_strength": 0.7,
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./castle.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task> CreateStableImageControlSketchAsBytesAsResponseAsync( + string contentType, + + global::StabilityAI.CreateStableImageControlSketchRequest request, + global::StabilityAI.CreateStableImageControlSketchAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + request = request ?? throw new global::System.ArgumentNullException(nameof(request)); + + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageControlSketchAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageControlSketchAsBytesSecurityRequirements, + operationName: "CreateStableImageControlSketchAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/control/sketch", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/png"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + var __contentImage = new global::System.Net.Http.ByteArrayContent(request.Image ?? global::System.Array.Empty()); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.ControlStrength != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.ControlStrength, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"control_strength\""); + + } + if (request.NegativePrompt != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty), + name: "\"negative_prompt\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + if (request.StylePreset != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.StylePreset).HasValue ? (request.StylePreset).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"style_preset\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageControlSketchAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlSketchAsBytes", + methodName: "CreateStableImageControlSketchAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/sketch\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlSketchAsBytes", + methodName: "CreateStableImageControlSketchAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/sketch\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlSketchAsBytes", + methodName: "CreateStableImageControlSketchAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/sketch\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageControlSketchAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlSketchAsBytes", + methodName: "CreateStableImageControlSketchAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/sketch\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlSketchAsBytes", + methodName: "CreateStableImageControlSketchAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/sketch\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageControlSketchResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageControlSketchResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageControlSketchResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageControlSketchResponse5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageControlSketchResponse5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageControlSketchResponse5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateStableImageControlSketchResponse6? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateStableImageControlSketchResponse6.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateStableImageControlSketchResponse6.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageControlSketchResponse7? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageControlSketchResponse7.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageControlSketchResponse7.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageControlSketchResponse8? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageControlSketchResponse8.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageControlSketchResponse8.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessCreateStableImageControlSketchAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Sketch
+ /// This service offers an ideal solution for design projects that require brainstorming and
+ /// frequent iterations. It upgrades rough hand-drawn sketches to refined outputs with precise
+ /// control. For non-sketch images, it allows detailed manipulation of the final appearance by
+ /// leveraging the contour lines and edges within the image.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=ZKIAqHzJzzUo)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `control_strength`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will match that of the input image.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Image Dimensions:
+ /// - Every side must be at least 64 pixels
+ /// - The total pixel count cannot exceed 9,437,184 pixels (e.g. 3072x3072, 4096x2304, etc.)
+ /// Image Aspect Ratio:
+ /// - Must be between 1:2.5 and 2.5:1 (i.e. cannot be too tall or too wide)
+ /// Example: ./some/image.png + /// + /// + /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Image Dimensions:
+ /// - Every side must be at least 64 pixels
+ /// - The total pixel count cannot exceed 9,437,184 pixels (e.g. 3072x3072, 4096x2304, etc.)
+ /// Image Aspect Ratio:
+ /// - Must be between 1:2.5 and 2.5:1 (i.e. cannot be too tall or too wide)
+ /// Example: ./some/image.png + /// + /// + /// How much influence, or control, the `image` has on the generation. Represented as a float between 0 and 1, where 0 is the least influence and 1 is the maximum.
+ /// Default Value: 0.7F + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + public async global::System.Threading.Tasks.Task CreateStableImageControlSketchAsBytesAsync( + string contentType, + string prompt, + byte[] image, + string imagename, + global::StabilityAI.CreateStableImageControlSketchAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + double? controlStrength = default, + string? negativePrompt = default, + double? seed = default, + global::StabilityAI.CreateStableImageControlSketchRequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageControlSketchRequestStylePreset? stylePreset = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + var __request = new global::StabilityAI.CreateStableImageControlSketchRequest + { + Prompt = prompt, + Image = image, + Imagename = imagename, + ControlStrength = controlStrength, + NegativePrompt = negativePrompt, + Seed = seed, + OutputFormat = outputFormat, + StylePreset = stylePreset, + }; + + return await CreateStableImageControlSketchAsBytesAsync( + contentType: contentType, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: __request, + requestOptions: requestOptions, + cancellationToken: cancellationToken).ConfigureAwait(false); + } + + /// + /// Sketch
+ /// This service offers an ideal solution for design projects that require brainstorming and
+ /// frequent iterations. It upgrades rough hand-drawn sketches to refined outputs with precise
+ /// control. For non-sketch images, it allows detailed manipulation of the final appearance by
+ /// leveraging the contour lines and edges within the image.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=ZKIAqHzJzzUo)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `control_strength`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will match that of the input image.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Image Dimensions:
+ /// - Every side must be at least 64 pixels
+ /// - The total pixel count cannot exceed 9,437,184 pixels (e.g. 3072x3072, 4096x2304, etc.)
+ /// Image Aspect Ratio:
+ /// - Must be between 1:2.5 and 2.5:1 (i.e. cannot be too tall or too wide)
+ /// Example: ./some/image.png + /// + /// + /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Image Dimensions:
+ /// - Every side must be at least 64 pixels
+ /// - The total pixel count cannot exceed 9,437,184 pixels (e.g. 3072x3072, 4096x2304, etc.)
+ /// Image Aspect Ratio:
+ /// - Must be between 1:2.5 and 2.5:1 (i.e. cannot be too tall or too wide)
+ /// Example: ./some/image.png + /// + /// + /// How much influence, or control, the `image` has on the generation. Represented as a float between 0 and 1, where 0 is the least influence and 1 is the maximum.
+ /// Default Value: 0.7F + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/sketch",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./sketch.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a medieval castle on a hill",
+ /// "control_strength": 0.7,
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./castle.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateStableImageControlSketchAsBytesAsync( + string contentType, + string prompt, + global::System.IO.Stream image, + string imagename, + global::StabilityAI.CreateStableImageControlSketchAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + double? controlStrength = default, + string? negativePrompt = default, + double? seed = default, + global::StabilityAI.CreateStableImageControlSketchRequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageControlSketchRequestStylePreset? stylePreset = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + + image = image ?? throw new global::System.ArgumentNullException(nameof(image)); + var request = new global::StabilityAI.CreateStableImageControlSketchRequest + { + Prompt = prompt, + Image = global::System.Array.Empty(), + Imagename = imagename, + ControlStrength = controlStrength, + NegativePrompt = negativePrompt, + Seed = seed, + OutputFormat = outputFormat, + StylePreset = stylePreset, + }; + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageControlSketchAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageControlSketchAsBytesSecurityRequirements, + operationName: "CreateStableImageControlSketchAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/control/sketch", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/png"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + var __contentImage = new global::System.Net.Http.StreamContent(image); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.ControlStrength != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.ControlStrength, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"control_strength\""); + + } + if (request.NegativePrompt != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty), + name: "\"negative_prompt\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + if (request.StylePreset != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.StylePreset).HasValue ? (request.StylePreset).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"style_preset\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageControlSketchAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlSketchAsBytes", + methodName: "CreateStableImageControlSketchAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/sketch\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlSketchAsBytes", + methodName: "CreateStableImageControlSketchAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/sketch\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlSketchAsBytes", + methodName: "CreateStableImageControlSketchAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/sketch\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageControlSketchAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlSketchAsBytes", + methodName: "CreateStableImageControlSketchAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/sketch\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlSketchAsBytes", + methodName: "CreateStableImageControlSketchAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/sketch\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageControlSketchResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageControlSketchResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageControlSketchResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageControlSketchResponse5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageControlSketchResponse5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageControlSketchResponse5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateStableImageControlSketchResponse6? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateStableImageControlSketchResponse6.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateStableImageControlSketchResponse6.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageControlSketchResponse7? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageControlSketchResponse7.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageControlSketchResponse7.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageControlSketchResponse8? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageControlSketchResponse8.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageControlSketchResponse8.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessCreateStableImageControlSketchAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return __content; + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return __content; + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Sketch
+ /// This service offers an ideal solution for design projects that require brainstorming and
+ /// frequent iterations. It upgrades rough hand-drawn sketches to refined outputs with precise
+ /// control. For non-sketch images, it allows detailed manipulation of the final appearance by
+ /// leveraging the contour lines and edges within the image.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=ZKIAqHzJzzUo)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `control_strength`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will match that of the input image.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Image Dimensions:
+ /// - Every side must be at least 64 pixels
+ /// - The total pixel count cannot exceed 9,437,184 pixels (e.g. 3072x3072, 4096x2304, etc.)
+ /// Image Aspect Ratio:
+ /// - Must be between 1:2.5 and 2.5:1 (i.e. cannot be too tall or too wide)
+ /// Example: ./some/image.png + /// + /// + /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Image Dimensions:
+ /// - Every side must be at least 64 pixels
+ /// - The total pixel count cannot exceed 9,437,184 pixels (e.g. 3072x3072, 4096x2304, etc.)
+ /// Image Aspect Ratio:
+ /// - Must be between 1:2.5 and 2.5:1 (i.e. cannot be too tall or too wide)
+ /// Example: ./some/image.png + /// + /// + /// How much influence, or control, the `image` has on the generation. Represented as a float between 0 and 1, where 0 is the least influence and 1 is the maximum.
+ /// Default Value: 0.7F + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/sketch",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./sketch.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a medieval castle on a hill",
+ /// "control_strength": 0.7,
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./castle.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateStableImageControlSketchAsBytesAsStreamAsync( + string contentType, + string prompt, + global::System.IO.Stream image, + string imagename, + global::StabilityAI.CreateStableImageControlSketchAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + double? controlStrength = default, + string? negativePrompt = default, + double? seed = default, + global::StabilityAI.CreateStableImageControlSketchRequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageControlSketchRequestStylePreset? stylePreset = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + + image = image ?? throw new global::System.ArgumentNullException(nameof(image)); + var request = new global::StabilityAI.CreateStableImageControlSketchRequest + { + Prompt = prompt, + Image = global::System.Array.Empty(), + Imagename = imagename, + ControlStrength = controlStrength, + NegativePrompt = negativePrompt, + Seed = seed, + OutputFormat = outputFormat, + StylePreset = stylePreset, + }; + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageControlSketchAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageControlSketchAsBytesSecurityRequirements, + operationName: "CreateStableImageControlSketchAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/control/sketch", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/png"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + var __contentImage = new global::System.Net.Http.StreamContent(image); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.ControlStrength != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.ControlStrength, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"control_strength\""); + + } + if (request.NegativePrompt != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty), + name: "\"negative_prompt\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + if (request.StylePreset != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.StylePreset).HasValue ? (request.StylePreset).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"style_preset\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageControlSketchAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlSketchAsBytes", + methodName: "CreateStableImageControlSketchAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/sketch\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseHeadersRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlSketchAsBytes", + methodName: "CreateStableImageControlSketchAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/sketch\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlSketchAsBytes", + methodName: "CreateStableImageControlSketchAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/sketch\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + try + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageControlSketchAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlSketchAsBytes", + methodName: "CreateStableImageControlSketchAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/sketch\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlSketchAsBytes", + methodName: "CreateStableImageControlSketchAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/sketch\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageControlSketchResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageControlSketchResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageControlSketchResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageControlSketchResponse5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageControlSketchResponse5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageControlSketchResponse5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateStableImageControlSketchResponse6? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateStableImageControlSketchResponse6.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateStableImageControlSketchResponse6.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageControlSketchResponse7? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageControlSketchResponse7.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageControlSketchResponse7.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageControlSketchResponse8? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageControlSketchResponse8.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageControlSketchResponse8.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + try + { + __response.EnsureSuccessStatusCode(); + + var __content = await __response.Content.ReadAsStreamAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.ResponseStream(__response, __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + } + catch + { + __response.Dispose(); + throw; + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Sketch
+ /// This service offers an ideal solution for design projects that require brainstorming and
+ /// frequent iterations. It upgrades rough hand-drawn sketches to refined outputs with precise
+ /// control. For non-sketch images, it allows detailed manipulation of the final appearance by
+ /// leveraging the contour lines and edges within the image.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=ZKIAqHzJzzUo)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `control_strength`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will match that of the input image.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Image Dimensions:
+ /// - Every side must be at least 64 pixels
+ /// - The total pixel count cannot exceed 9,437,184 pixels (e.g. 3072x3072, 4096x2304, etc.)
+ /// Image Aspect Ratio:
+ /// - Must be between 1:2.5 and 2.5:1 (i.e. cannot be too tall or too wide)
+ /// Example: ./some/image.png + /// + /// + /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Image Dimensions:
+ /// - Every side must be at least 64 pixels
+ /// - The total pixel count cannot exceed 9,437,184 pixels (e.g. 3072x3072, 4096x2304, etc.)
+ /// Image Aspect Ratio:
+ /// - Must be between 1:2.5 and 2.5:1 (i.e. cannot be too tall or too wide)
+ /// Example: ./some/image.png + /// + /// + /// How much influence, or control, the `image` has on the generation. Represented as a float between 0 and 1, where 0 is the least influence and 1 is the maximum.
+ /// Default Value: 0.7F + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/sketch",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./sketch.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a medieval castle on a hill",
+ /// "control_strength": 0.7,
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./castle.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task> CreateStableImageControlSketchAsBytesAsResponseAsync( + string contentType, + string prompt, + global::System.IO.Stream image, + string imagename, + global::StabilityAI.CreateStableImageControlSketchAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + double? controlStrength = default, + string? negativePrompt = default, + double? seed = default, + global::StabilityAI.CreateStableImageControlSketchRequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageControlSketchRequestStylePreset? stylePreset = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + + image = image ?? throw new global::System.ArgumentNullException(nameof(image)); + var request = new global::StabilityAI.CreateStableImageControlSketchRequest + { + Prompt = prompt, + Image = global::System.Array.Empty(), + Imagename = imagename, + ControlStrength = controlStrength, + NegativePrompt = negativePrompt, + Seed = seed, + OutputFormat = outputFormat, + StylePreset = stylePreset, + }; + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageControlSketchAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageControlSketchAsBytesSecurityRequirements, + operationName: "CreateStableImageControlSketchAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/control/sketch", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/png"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + var __contentImage = new global::System.Net.Http.StreamContent(image); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.ControlStrength != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.ControlStrength, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"control_strength\""); + + } + if (request.NegativePrompt != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty), + name: "\"negative_prompt\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + if (request.StylePreset != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.StylePreset).HasValue ? (request.StylePreset).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"style_preset\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageControlSketchAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlSketchAsBytes", + methodName: "CreateStableImageControlSketchAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/sketch\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlSketchAsBytes", + methodName: "CreateStableImageControlSketchAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/sketch\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlSketchAsBytes", + methodName: "CreateStableImageControlSketchAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/sketch\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageControlSketchAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlSketchAsBytes", + methodName: "CreateStableImageControlSketchAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/sketch\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlSketchAsBytes", + methodName: "CreateStableImageControlSketchAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/sketch\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageControlSketchResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageControlSketchResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageControlSketchResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageControlSketchResponse5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageControlSketchResponse5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageControlSketchResponse5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateStableImageControlSketchResponse6? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateStableImageControlSketchResponse6.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateStableImageControlSketchResponse6.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageControlSketchResponse7? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageControlSketchResponse7.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageControlSketchResponse7.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageControlSketchResponse8? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageControlSketchResponse8.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageControlSketchResponse8.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessCreateStableImageControlSketchAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + } +} \ No newline at end of file diff --git a/src/libs/StabilityAI/Generated/StabilityAI.ControlClient.CreateStableImageControlStructure.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.ControlClient.CreateStableImageControlStructure.g.cs index acae1df..1ba8897 100644 --- a/src/libs/StabilityAI/Generated/StabilityAI.ControlClient.CreateStableImageControlStructure.g.cs +++ b/src/libs/StabilityAI/Generated/StabilityAI.ControlClient.CreateStableImageControlStructure.g.cs @@ -289,6 +289,10 @@ partial void ProcessCreateStableImageControlStructureResponseContent( __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || @@ -326,42 +330,6 @@ partial void ProcessCreateStableImageControlStructureResponseContent( var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"accept\""); - - } - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } __httpRequestContent.Add( content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), name: "\"prompt\""); @@ -1307,6 +1275,10 @@ request.Imagename is null __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || @@ -1344,42 +1316,6 @@ request.Imagename is null var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"accept\""); - - } - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } __httpRequestContent.Add( content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), name: "\"prompt\""); @@ -2175,6 +2111,10 @@ request.Imagename is null __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || @@ -2212,42 +2152,6 @@ request.Imagename is null var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"accept\""); - - } - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } __httpRequestContent.Add( content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), name: "\"prompt\""); diff --git a/src/libs/StabilityAI/Generated/StabilityAI.ControlClient.CreateStableImageControlStructureAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.ControlClient.CreateStableImageControlStructureAsBytes.g.cs new file mode 100644 index 0000000..6a6d5d4 --- /dev/null +++ b/src/libs/StabilityAI/Generated/StabilityAI.ControlClient.CreateStableImageControlStructureAsBytes.g.cs @@ -0,0 +1,4261 @@ + +#nullable enable + +namespace StabilityAI +{ + public partial class ControlClient + { + + + private static readonly global::StabilityAI.EndPointSecurityRequirement s_CreateStableImageControlStructureAsBytesSecurityRequirement0 = + new global::StabilityAI.EndPointSecurityRequirement + { + Authorizations = new global::StabilityAI.EndPointAuthorizationRequirement[] + { new global::StabilityAI.EndPointAuthorizationRequirement + { + Type = "Http", + SchemeId = "HttpBearer", + Location = "Header", + Name = "Bearer", + FriendlyName = "Bearer", + }, + }, + }; + private static readonly global::StabilityAI.EndPointSecurityRequirement[] s_CreateStableImageControlStructureAsBytesSecurityRequirements = + new global::StabilityAI.EndPointSecurityRequirement[] + { s_CreateStableImageControlStructureAsBytesSecurityRequirement0, + }; + partial void PrepareCreateStableImageControlStructureAsBytesArguments( + global::System.Net.Http.HttpClient httpClient, + ref string contentType, + ref global::StabilityAI.CreateStableImageControlStructureAccept? accept, + ref string? stabilityClientId, + ref string? stabilityClientUserId, + ref string? stabilityClientVersion, + global::StabilityAI.CreateStableImageControlStructureRequest request); + partial void PrepareCreateStableImageControlStructureAsBytesRequest( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpRequestMessage httpRequestMessage, + string contentType, + global::StabilityAI.CreateStableImageControlStructureAccept? accept, + string? stabilityClientId, + string? stabilityClientUserId, + string? stabilityClientVersion, + global::StabilityAI.CreateStableImageControlStructureRequest request); + partial void ProcessCreateStableImageControlStructureAsBytesResponse( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpResponseMessage httpResponseMessage); + + partial void ProcessCreateStableImageControlStructureAsBytesResponseContent( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpResponseMessage httpResponseMessage, + ref byte[] content); + + /// + /// Structure
+ /// This service excels in generating images by maintaining the structure of an input image,
+ /// making it especially valuable for advanced content creation scenarios such as recreating
+ /// scenes or rendering characters from models.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=59RaZazXz0AU)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `control_strength`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will match that of the input image.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/structure",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./cat-statue.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a well manicured shrub in an english garden",
+ /// "control_strength": 0.7,
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./shrub-in-a-garden.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateStableImageControlStructureAsBytesAsync( + string contentType, + + global::StabilityAI.CreateStableImageControlStructureRequest request, + global::StabilityAI.CreateStableImageControlStructureAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + var __response = await CreateStableImageControlStructureAsBytesAsResponseAsync( + contentType: contentType, + + request: request, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + requestOptions: requestOptions, + cancellationToken: cancellationToken + ).ConfigureAwait(false); + + return __response.Body; + } + /// + /// Structure
+ /// This service excels in generating images by maintaining the structure of an input image,
+ /// making it especially valuable for advanced content creation scenarios such as recreating
+ /// scenes or rendering characters from models.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=59RaZazXz0AU)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `control_strength`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will match that of the input image.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/structure",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./cat-statue.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a well manicured shrub in an english garden",
+ /// "control_strength": 0.7,
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./shrub-in-a-garden.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateStableImageControlStructureAsBytesAsStreamAsync( + string contentType, + + global::StabilityAI.CreateStableImageControlStructureRequest request, + global::StabilityAI.CreateStableImageControlStructureAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + request = request ?? throw new global::System.ArgumentNullException(nameof(request)); + + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageControlStructureAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageControlStructureAsBytesSecurityRequirements, + operationName: "CreateStableImageControlStructureAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/control/structure", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/png"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + var __contentImage = new global::System.Net.Http.ByteArrayContent(request.Image ?? global::System.Array.Empty()); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.ControlStrength != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.ControlStrength, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"control_strength\""); + + } + if (request.NegativePrompt != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty), + name: "\"negative_prompt\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + if (request.StylePreset != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.StylePreset).HasValue ? (request.StylePreset).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"style_preset\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageControlStructureAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStructureAsBytes", + methodName: "CreateStableImageControlStructureAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/structure\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseHeadersRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStructureAsBytes", + methodName: "CreateStableImageControlStructureAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/structure\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStructureAsBytes", + methodName: "CreateStableImageControlStructureAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/structure\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + try + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageControlStructureAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStructureAsBytes", + methodName: "CreateStableImageControlStructureAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/structure\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStructureAsBytes", + methodName: "CreateStableImageControlStructureAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/structure\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageControlStructureResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageControlStructureResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageControlStructureResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageControlStructureResponse5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageControlStructureResponse5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageControlStructureResponse5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateStableImageControlStructureResponse6? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateStableImageControlStructureResponse6.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateStableImageControlStructureResponse6.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageControlStructureResponse7? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageControlStructureResponse7.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageControlStructureResponse7.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageControlStructureResponse8? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageControlStructureResponse8.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageControlStructureResponse8.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + try + { + __response.EnsureSuccessStatusCode(); + + var __content = await __response.Content.ReadAsStreamAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.ResponseStream(__response, __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + } + catch + { + __response.Dispose(); + throw; + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Structure
+ /// This service excels in generating images by maintaining the structure of an input image,
+ /// making it especially valuable for advanced content creation scenarios such as recreating
+ /// scenes or rendering characters from models.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=59RaZazXz0AU)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `control_strength`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will match that of the input image.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/structure",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./cat-statue.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a well manicured shrub in an english garden",
+ /// "control_strength": 0.7,
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./shrub-in-a-garden.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task> CreateStableImageControlStructureAsBytesAsResponseAsync( + string contentType, + + global::StabilityAI.CreateStableImageControlStructureRequest request, + global::StabilityAI.CreateStableImageControlStructureAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + request = request ?? throw new global::System.ArgumentNullException(nameof(request)); + + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageControlStructureAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageControlStructureAsBytesSecurityRequirements, + operationName: "CreateStableImageControlStructureAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/control/structure", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/png"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + var __contentImage = new global::System.Net.Http.ByteArrayContent(request.Image ?? global::System.Array.Empty()); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.ControlStrength != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.ControlStrength, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"control_strength\""); + + } + if (request.NegativePrompt != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty), + name: "\"negative_prompt\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + if (request.StylePreset != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.StylePreset).HasValue ? (request.StylePreset).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"style_preset\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageControlStructureAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStructureAsBytes", + methodName: "CreateStableImageControlStructureAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/structure\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStructureAsBytes", + methodName: "CreateStableImageControlStructureAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/structure\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStructureAsBytes", + methodName: "CreateStableImageControlStructureAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/structure\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageControlStructureAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStructureAsBytes", + methodName: "CreateStableImageControlStructureAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/structure\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStructureAsBytes", + methodName: "CreateStableImageControlStructureAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/structure\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageControlStructureResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageControlStructureResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageControlStructureResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageControlStructureResponse5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageControlStructureResponse5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageControlStructureResponse5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateStableImageControlStructureResponse6? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateStableImageControlStructureResponse6.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateStableImageControlStructureResponse6.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageControlStructureResponse7? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageControlStructureResponse7.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageControlStructureResponse7.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageControlStructureResponse8? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageControlStructureResponse8.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageControlStructureResponse8.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessCreateStableImageControlStructureAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Structure
+ /// This service excels in generating images by maintaining the structure of an input image,
+ /// making it especially valuable for advanced content creation scenarios such as recreating
+ /// scenes or rendering characters from models.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=59RaZazXz0AU)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `control_strength`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will match that of the input image.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// An image whose structure you wish to use as the foundation for a generation.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// An image whose structure you wish to use as the foundation for a generation.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// How much influence, or control, the `image` has on the generation. Represented as a float between 0 and 1, where 0 is the least influence and 1 is the maximum.
+ /// Default Value: 0.7F + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + public async global::System.Threading.Tasks.Task CreateStableImageControlStructureAsBytesAsync( + string contentType, + string prompt, + byte[] image, + string imagename, + global::StabilityAI.CreateStableImageControlStructureAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + double? controlStrength = default, + string? negativePrompt = default, + double? seed = default, + global::StabilityAI.CreateStableImageControlStructureRequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageControlStructureRequestStylePreset? stylePreset = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + var __request = new global::StabilityAI.CreateStableImageControlStructureRequest + { + Prompt = prompt, + Image = image, + Imagename = imagename, + ControlStrength = controlStrength, + NegativePrompt = negativePrompt, + Seed = seed, + OutputFormat = outputFormat, + StylePreset = stylePreset, + }; + + return await CreateStableImageControlStructureAsBytesAsync( + contentType: contentType, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: __request, + requestOptions: requestOptions, + cancellationToken: cancellationToken).ConfigureAwait(false); + } + + /// + /// Structure
+ /// This service excels in generating images by maintaining the structure of an input image,
+ /// making it especially valuable for advanced content creation scenarios such as recreating
+ /// scenes or rendering characters from models.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=59RaZazXz0AU)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `control_strength`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will match that of the input image.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// An image whose structure you wish to use as the foundation for a generation.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// An image whose structure you wish to use as the foundation for a generation.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// How much influence, or control, the `image` has on the generation. Represented as a float between 0 and 1, where 0 is the least influence and 1 is the maximum.
+ /// Default Value: 0.7F + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/structure",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./cat-statue.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a well manicured shrub in an english garden",
+ /// "control_strength": 0.7,
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./shrub-in-a-garden.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateStableImageControlStructureAsBytesAsync( + string contentType, + string prompt, + global::System.IO.Stream image, + string imagename, + global::StabilityAI.CreateStableImageControlStructureAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + double? controlStrength = default, + string? negativePrompt = default, + double? seed = default, + global::StabilityAI.CreateStableImageControlStructureRequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageControlStructureRequestStylePreset? stylePreset = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + + image = image ?? throw new global::System.ArgumentNullException(nameof(image)); + var request = new global::StabilityAI.CreateStableImageControlStructureRequest + { + Prompt = prompt, + Image = global::System.Array.Empty(), + Imagename = imagename, + ControlStrength = controlStrength, + NegativePrompt = negativePrompt, + Seed = seed, + OutputFormat = outputFormat, + StylePreset = stylePreset, + }; + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageControlStructureAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageControlStructureAsBytesSecurityRequirements, + operationName: "CreateStableImageControlStructureAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/control/structure", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/png"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + var __contentImage = new global::System.Net.Http.StreamContent(image); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.ControlStrength != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.ControlStrength, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"control_strength\""); + + } + if (request.NegativePrompt != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty), + name: "\"negative_prompt\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + if (request.StylePreset != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.StylePreset).HasValue ? (request.StylePreset).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"style_preset\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageControlStructureAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStructureAsBytes", + methodName: "CreateStableImageControlStructureAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/structure\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStructureAsBytes", + methodName: "CreateStableImageControlStructureAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/structure\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStructureAsBytes", + methodName: "CreateStableImageControlStructureAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/structure\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageControlStructureAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStructureAsBytes", + methodName: "CreateStableImageControlStructureAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/structure\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStructureAsBytes", + methodName: "CreateStableImageControlStructureAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/structure\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageControlStructureResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageControlStructureResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageControlStructureResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageControlStructureResponse5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageControlStructureResponse5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageControlStructureResponse5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateStableImageControlStructureResponse6? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateStableImageControlStructureResponse6.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateStableImageControlStructureResponse6.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageControlStructureResponse7? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageControlStructureResponse7.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageControlStructureResponse7.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageControlStructureResponse8? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageControlStructureResponse8.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageControlStructureResponse8.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessCreateStableImageControlStructureAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return __content; + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return __content; + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Structure
+ /// This service excels in generating images by maintaining the structure of an input image,
+ /// making it especially valuable for advanced content creation scenarios such as recreating
+ /// scenes or rendering characters from models.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=59RaZazXz0AU)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `control_strength`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will match that of the input image.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// An image whose structure you wish to use as the foundation for a generation.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// An image whose structure you wish to use as the foundation for a generation.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// How much influence, or control, the `image` has on the generation. Represented as a float between 0 and 1, where 0 is the least influence and 1 is the maximum.
+ /// Default Value: 0.7F + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/structure",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./cat-statue.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a well manicured shrub in an english garden",
+ /// "control_strength": 0.7,
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./shrub-in-a-garden.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateStableImageControlStructureAsBytesAsStreamAsync( + string contentType, + string prompt, + global::System.IO.Stream image, + string imagename, + global::StabilityAI.CreateStableImageControlStructureAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + double? controlStrength = default, + string? negativePrompt = default, + double? seed = default, + global::StabilityAI.CreateStableImageControlStructureRequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageControlStructureRequestStylePreset? stylePreset = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + + image = image ?? throw new global::System.ArgumentNullException(nameof(image)); + var request = new global::StabilityAI.CreateStableImageControlStructureRequest + { + Prompt = prompt, + Image = global::System.Array.Empty(), + Imagename = imagename, + ControlStrength = controlStrength, + NegativePrompt = negativePrompt, + Seed = seed, + OutputFormat = outputFormat, + StylePreset = stylePreset, + }; + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageControlStructureAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageControlStructureAsBytesSecurityRequirements, + operationName: "CreateStableImageControlStructureAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/control/structure", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/png"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + var __contentImage = new global::System.Net.Http.StreamContent(image); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.ControlStrength != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.ControlStrength, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"control_strength\""); + + } + if (request.NegativePrompt != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty), + name: "\"negative_prompt\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + if (request.StylePreset != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.StylePreset).HasValue ? (request.StylePreset).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"style_preset\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageControlStructureAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStructureAsBytes", + methodName: "CreateStableImageControlStructureAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/structure\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseHeadersRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStructureAsBytes", + methodName: "CreateStableImageControlStructureAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/structure\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStructureAsBytes", + methodName: "CreateStableImageControlStructureAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/structure\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + try + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageControlStructureAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStructureAsBytes", + methodName: "CreateStableImageControlStructureAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/structure\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStructureAsBytes", + methodName: "CreateStableImageControlStructureAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/structure\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageControlStructureResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageControlStructureResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageControlStructureResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageControlStructureResponse5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageControlStructureResponse5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageControlStructureResponse5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateStableImageControlStructureResponse6? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateStableImageControlStructureResponse6.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateStableImageControlStructureResponse6.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageControlStructureResponse7? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageControlStructureResponse7.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageControlStructureResponse7.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageControlStructureResponse8? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageControlStructureResponse8.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageControlStructureResponse8.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + try + { + __response.EnsureSuccessStatusCode(); + + var __content = await __response.Content.ReadAsStreamAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.ResponseStream(__response, __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + } + catch + { + __response.Dispose(); + throw; + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Structure
+ /// This service excels in generating images by maintaining the structure of an input image,
+ /// making it especially valuable for advanced content creation scenarios such as recreating
+ /// scenes or rendering characters from models.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=59RaZazXz0AU)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `control_strength`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will match that of the input image.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// An image whose structure you wish to use as the foundation for a generation.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// An image whose structure you wish to use as the foundation for a generation.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// How much influence, or control, the `image` has on the generation. Represented as a float between 0 and 1, where 0 is the least influence and 1 is the maximum.
+ /// Default Value: 0.7F + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/structure",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./cat-statue.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a well manicured shrub in an english garden",
+ /// "control_strength": 0.7,
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./shrub-in-a-garden.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task> CreateStableImageControlStructureAsBytesAsResponseAsync( + string contentType, + string prompt, + global::System.IO.Stream image, + string imagename, + global::StabilityAI.CreateStableImageControlStructureAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + double? controlStrength = default, + string? negativePrompt = default, + double? seed = default, + global::StabilityAI.CreateStableImageControlStructureRequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageControlStructureRequestStylePreset? stylePreset = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + + image = image ?? throw new global::System.ArgumentNullException(nameof(image)); + var request = new global::StabilityAI.CreateStableImageControlStructureRequest + { + Prompt = prompt, + Image = global::System.Array.Empty(), + Imagename = imagename, + ControlStrength = controlStrength, + NegativePrompt = negativePrompt, + Seed = seed, + OutputFormat = outputFormat, + StylePreset = stylePreset, + }; + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageControlStructureAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageControlStructureAsBytesSecurityRequirements, + operationName: "CreateStableImageControlStructureAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/control/structure", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/png"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + var __contentImage = new global::System.Net.Http.StreamContent(image); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.ControlStrength != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.ControlStrength, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"control_strength\""); + + } + if (request.NegativePrompt != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty), + name: "\"negative_prompt\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + if (request.StylePreset != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.StylePreset).HasValue ? (request.StylePreset).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"style_preset\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageControlStructureAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStructureAsBytes", + methodName: "CreateStableImageControlStructureAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/structure\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStructureAsBytes", + methodName: "CreateStableImageControlStructureAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/structure\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStructureAsBytes", + methodName: "CreateStableImageControlStructureAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/structure\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageControlStructureAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStructureAsBytes", + methodName: "CreateStableImageControlStructureAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/structure\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStructureAsBytes", + methodName: "CreateStableImageControlStructureAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/structure\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageControlStructureResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageControlStructureResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageControlStructureResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageControlStructureResponse5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageControlStructureResponse5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageControlStructureResponse5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateStableImageControlStructureResponse6? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateStableImageControlStructureResponse6.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateStableImageControlStructureResponse6.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageControlStructureResponse7? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageControlStructureResponse7.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageControlStructureResponse7.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageControlStructureResponse8? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageControlStructureResponse8.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageControlStructureResponse8.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessCreateStableImageControlStructureAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + } +} \ No newline at end of file diff --git a/src/libs/StabilityAI/Generated/StabilityAI.ControlClient.CreateStableImageControlStyle.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.ControlClient.CreateStableImageControlStyle.g.cs index a0fc74f..9724bfb 100644 --- a/src/libs/StabilityAI/Generated/StabilityAI.ControlClient.CreateStableImageControlStyle.g.cs +++ b/src/libs/StabilityAI/Generated/StabilityAI.ControlClient.CreateStableImageControlStyle.g.cs @@ -285,6 +285,10 @@ partial void ProcessCreateStableImageControlStyleResponseContent( __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || @@ -322,42 +326,6 @@ partial void ProcessCreateStableImageControlStyleResponseContent( var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"accept\""); - - } - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } __httpRequestContent.Add( content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), name: "\"prompt\""); @@ -1320,6 +1288,10 @@ request.Imagename is null __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || @@ -1357,42 +1329,6 @@ request.Imagename is null var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"accept\""); - - } - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } __httpRequestContent.Add( content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), name: "\"prompt\""); @@ -2200,6 +2136,10 @@ request.Imagename is null __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || @@ -2237,42 +2177,6 @@ request.Imagename is null var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"accept\""); - - } - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } __httpRequestContent.Add( content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), name: "\"prompt\""); diff --git a/src/libs/StabilityAI/Generated/StabilityAI.ControlClient.CreateStableImageControlStyleAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.ControlClient.CreateStableImageControlStyleAsBytes.g.cs new file mode 100644 index 0000000..20865d7 --- /dev/null +++ b/src/libs/StabilityAI/Generated/StabilityAI.ControlClient.CreateStableImageControlStyleAsBytes.g.cs @@ -0,0 +1,4312 @@ + +#nullable enable + +namespace StabilityAI +{ + public partial class ControlClient + { + + + private static readonly global::StabilityAI.EndPointSecurityRequirement s_CreateStableImageControlStyleAsBytesSecurityRequirement0 = + new global::StabilityAI.EndPointSecurityRequirement + { + Authorizations = new global::StabilityAI.EndPointAuthorizationRequirement[] + { new global::StabilityAI.EndPointAuthorizationRequirement + { + Type = "Http", + SchemeId = "HttpBearer", + Location = "Header", + Name = "Bearer", + FriendlyName = "Bearer", + }, + }, + }; + private static readonly global::StabilityAI.EndPointSecurityRequirement[] s_CreateStableImageControlStyleAsBytesSecurityRequirements = + new global::StabilityAI.EndPointSecurityRequirement[] + { s_CreateStableImageControlStyleAsBytesSecurityRequirement0, + }; + partial void PrepareCreateStableImageControlStyleAsBytesArguments( + global::System.Net.Http.HttpClient httpClient, + ref string contentType, + ref global::StabilityAI.CreateStableImageControlStyleAccept? accept, + ref string? stabilityClientId, + ref string? stabilityClientUserId, + ref string? stabilityClientVersion, + global::StabilityAI.CreateStableImageControlStyleRequest request); + partial void PrepareCreateStableImageControlStyleAsBytesRequest( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpRequestMessage httpRequestMessage, + string contentType, + global::StabilityAI.CreateStableImageControlStyleAccept? accept, + string? stabilityClientId, + string? stabilityClientUserId, + string? stabilityClientVersion, + global::StabilityAI.CreateStableImageControlStyleRequest request); + partial void ProcessCreateStableImageControlStyleAsBytesResponse( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpResponseMessage httpResponseMessage); + + partial void ProcessCreateStableImageControlStyleAsBytesResponseContent( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpResponseMessage httpResponseMessage, + ref byte[] content); + + /// + /// Style Guide
+ /// This service extracts stylistic elements from an input image (control image) and uses it to guide the creation of an output image based on the prompt. The result is a new image in the same style as the control image.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=y0WKjG72RvTE)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `negative_prompt`
+ /// - `aspect_ratio`
+ /// - `fidelity`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1MP. The default resolution is 1024x1024.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/style",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./cinematic-portrait.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a majestic portrait of a chicken",
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./chicken-portrait.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateStableImageControlStyleAsBytesAsync( + string contentType, + + global::StabilityAI.CreateStableImageControlStyleRequest request, + global::StabilityAI.CreateStableImageControlStyleAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + var __response = await CreateStableImageControlStyleAsBytesAsResponseAsync( + contentType: contentType, + + request: request, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + requestOptions: requestOptions, + cancellationToken: cancellationToken + ).ConfigureAwait(false); + + return __response.Body; + } + /// + /// Style Guide
+ /// This service extracts stylistic elements from an input image (control image) and uses it to guide the creation of an output image based on the prompt. The result is a new image in the same style as the control image.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=y0WKjG72RvTE)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `negative_prompt`
+ /// - `aspect_ratio`
+ /// - `fidelity`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1MP. The default resolution is 1024x1024.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/style",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./cinematic-portrait.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a majestic portrait of a chicken",
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./chicken-portrait.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateStableImageControlStyleAsBytesAsStreamAsync( + string contentType, + + global::StabilityAI.CreateStableImageControlStyleRequest request, + global::StabilityAI.CreateStableImageControlStyleAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + request = request ?? throw new global::System.ArgumentNullException(nameof(request)); + + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageControlStyleAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageControlStyleAsBytesSecurityRequirements, + operationName: "CreateStableImageControlStyleAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/control/style", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/png"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + var __contentImage = new global::System.Net.Http.ByteArrayContent(request.Image ?? global::System.Array.Empty()); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.NegativePrompt != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty), + name: "\"negative_prompt\""); + + } + if (request.AspectRatio != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.AspectRatio).HasValue ? (request.AspectRatio).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"aspect_ratio\""); + + } + if (request.Fidelity != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Fidelity, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"fidelity\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + if (request.StylePreset != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.StylePreset).HasValue ? (request.StylePreset).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"style_preset\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageControlStyleAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStyleAsBytes", + methodName: "CreateStableImageControlStyleAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/style\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseHeadersRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStyleAsBytes", + methodName: "CreateStableImageControlStyleAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/style\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStyleAsBytes", + methodName: "CreateStableImageControlStyleAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/style\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + try + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageControlStyleAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStyleAsBytes", + methodName: "CreateStableImageControlStyleAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/style\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStyleAsBytes", + methodName: "CreateStableImageControlStyleAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/style\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageControlStyleResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageControlStyleResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageControlStyleResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageControlStyleResponse5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageControlStyleResponse5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageControlStyleResponse5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateStableImageControlStyleResponse6? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateStableImageControlStyleResponse6.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateStableImageControlStyleResponse6.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageControlStyleResponse7? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageControlStyleResponse7.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageControlStyleResponse7.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageControlStyleResponse8? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageControlStyleResponse8.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageControlStyleResponse8.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + try + { + __response.EnsureSuccessStatusCode(); + + var __content = await __response.Content.ReadAsStreamAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.ResponseStream(__response, __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + } + catch + { + __response.Dispose(); + throw; + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Style Guide
+ /// This service extracts stylistic elements from an input image (control image) and uses it to guide the creation of an output image based on the prompt. The result is a new image in the same style as the control image.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=y0WKjG72RvTE)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `negative_prompt`
+ /// - `aspect_ratio`
+ /// - `fidelity`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1MP. The default resolution is 1024x1024.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/style",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./cinematic-portrait.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a majestic portrait of a chicken",
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./chicken-portrait.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task> CreateStableImageControlStyleAsBytesAsResponseAsync( + string contentType, + + global::StabilityAI.CreateStableImageControlStyleRequest request, + global::StabilityAI.CreateStableImageControlStyleAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + request = request ?? throw new global::System.ArgumentNullException(nameof(request)); + + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageControlStyleAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageControlStyleAsBytesSecurityRequirements, + operationName: "CreateStableImageControlStyleAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/control/style", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/png"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + var __contentImage = new global::System.Net.Http.ByteArrayContent(request.Image ?? global::System.Array.Empty()); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.NegativePrompt != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty), + name: "\"negative_prompt\""); + + } + if (request.AspectRatio != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.AspectRatio).HasValue ? (request.AspectRatio).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"aspect_ratio\""); + + } + if (request.Fidelity != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Fidelity, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"fidelity\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + if (request.StylePreset != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.StylePreset).HasValue ? (request.StylePreset).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"style_preset\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageControlStyleAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStyleAsBytes", + methodName: "CreateStableImageControlStyleAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/style\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStyleAsBytes", + methodName: "CreateStableImageControlStyleAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/style\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStyleAsBytes", + methodName: "CreateStableImageControlStyleAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/style\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageControlStyleAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStyleAsBytes", + methodName: "CreateStableImageControlStyleAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/style\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStyleAsBytes", + methodName: "CreateStableImageControlStyleAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/style\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageControlStyleResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageControlStyleResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageControlStyleResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageControlStyleResponse5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageControlStyleResponse5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageControlStyleResponse5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateStableImageControlStyleResponse6? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateStableImageControlStyleResponse6.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateStableImageControlStyleResponse6.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageControlStyleResponse7? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageControlStyleResponse7.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageControlStyleResponse7.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageControlStyleResponse8? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageControlStyleResponse8.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageControlStyleResponse8.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessCreateStableImageControlStyleAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Style Guide
+ /// This service extracts stylistic elements from an input image (control image) and uses it to guide the creation of an output image based on the prompt. The result is a new image in the same style as the control image.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=y0WKjG72RvTE)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `negative_prompt`
+ /// - `aspect_ratio`
+ /// - `fidelity`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1MP. The default resolution is 1024x1024.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// An image whose style you wish to use as the foundation for a generation.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// An image whose style you wish to use as the foundation for a generation.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// Controls the aspect ratio of the generated image.
+ /// Default Value: 1:1 + /// + /// + /// How closely the output image's style resembles the input image's style.
+ /// Default Value: 0.5F + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + public async global::System.Threading.Tasks.Task CreateStableImageControlStyleAsBytesAsync( + string contentType, + string prompt, + byte[] image, + string imagename, + global::StabilityAI.CreateStableImageControlStyleAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + string? negativePrompt = default, + global::StabilityAI.CreateStableImageControlStyleRequestAspectRatio? aspectRatio = default, + double? fidelity = default, + double? seed = default, + global::StabilityAI.CreateStableImageControlStyleRequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageControlStyleRequestStylePreset? stylePreset = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + var __request = new global::StabilityAI.CreateStableImageControlStyleRequest + { + Prompt = prompt, + Image = image, + Imagename = imagename, + NegativePrompt = negativePrompt, + AspectRatio = aspectRatio, + Fidelity = fidelity, + Seed = seed, + OutputFormat = outputFormat, + StylePreset = stylePreset, + }; + + return await CreateStableImageControlStyleAsBytesAsync( + contentType: contentType, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: __request, + requestOptions: requestOptions, + cancellationToken: cancellationToken).ConfigureAwait(false); + } + + /// + /// Style Guide
+ /// This service extracts stylistic elements from an input image (control image) and uses it to guide the creation of an output image based on the prompt. The result is a new image in the same style as the control image.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=y0WKjG72RvTE)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `negative_prompt`
+ /// - `aspect_ratio`
+ /// - `fidelity`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1MP. The default resolution is 1024x1024.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// An image whose style you wish to use as the foundation for a generation.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// An image whose style you wish to use as the foundation for a generation.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// Controls the aspect ratio of the generated image.
+ /// Default Value: 1:1 + /// + /// + /// How closely the output image's style resembles the input image's style.
+ /// Default Value: 0.5F + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/style",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./cinematic-portrait.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a majestic portrait of a chicken",
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./chicken-portrait.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateStableImageControlStyleAsBytesAsync( + string contentType, + string prompt, + global::System.IO.Stream image, + string imagename, + global::StabilityAI.CreateStableImageControlStyleAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + string? negativePrompt = default, + global::StabilityAI.CreateStableImageControlStyleRequestAspectRatio? aspectRatio = default, + double? fidelity = default, + double? seed = default, + global::StabilityAI.CreateStableImageControlStyleRequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageControlStyleRequestStylePreset? stylePreset = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + + image = image ?? throw new global::System.ArgumentNullException(nameof(image)); + var request = new global::StabilityAI.CreateStableImageControlStyleRequest + { + Prompt = prompt, + Image = global::System.Array.Empty(), + Imagename = imagename, + NegativePrompt = negativePrompt, + AspectRatio = aspectRatio, + Fidelity = fidelity, + Seed = seed, + OutputFormat = outputFormat, + StylePreset = stylePreset, + }; + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageControlStyleAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageControlStyleAsBytesSecurityRequirements, + operationName: "CreateStableImageControlStyleAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/control/style", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/png"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + var __contentImage = new global::System.Net.Http.StreamContent(image); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.NegativePrompt != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty), + name: "\"negative_prompt\""); + + } + if (request.AspectRatio != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.AspectRatio).HasValue ? (request.AspectRatio).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"aspect_ratio\""); + + } + if (request.Fidelity != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Fidelity, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"fidelity\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + if (request.StylePreset != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.StylePreset).HasValue ? (request.StylePreset).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"style_preset\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageControlStyleAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStyleAsBytes", + methodName: "CreateStableImageControlStyleAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/style\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStyleAsBytes", + methodName: "CreateStableImageControlStyleAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/style\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStyleAsBytes", + methodName: "CreateStableImageControlStyleAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/style\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageControlStyleAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStyleAsBytes", + methodName: "CreateStableImageControlStyleAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/style\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStyleAsBytes", + methodName: "CreateStableImageControlStyleAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/style\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageControlStyleResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageControlStyleResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageControlStyleResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageControlStyleResponse5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageControlStyleResponse5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageControlStyleResponse5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateStableImageControlStyleResponse6? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateStableImageControlStyleResponse6.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateStableImageControlStyleResponse6.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageControlStyleResponse7? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageControlStyleResponse7.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageControlStyleResponse7.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageControlStyleResponse8? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageControlStyleResponse8.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageControlStyleResponse8.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessCreateStableImageControlStyleAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return __content; + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return __content; + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Style Guide
+ /// This service extracts stylistic elements from an input image (control image) and uses it to guide the creation of an output image based on the prompt. The result is a new image in the same style as the control image.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=y0WKjG72RvTE)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `negative_prompt`
+ /// - `aspect_ratio`
+ /// - `fidelity`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1MP. The default resolution is 1024x1024.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// An image whose style you wish to use as the foundation for a generation.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// An image whose style you wish to use as the foundation for a generation.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// Controls the aspect ratio of the generated image.
+ /// Default Value: 1:1 + /// + /// + /// How closely the output image's style resembles the input image's style.
+ /// Default Value: 0.5F + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/style",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./cinematic-portrait.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a majestic portrait of a chicken",
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./chicken-portrait.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateStableImageControlStyleAsBytesAsStreamAsync( + string contentType, + string prompt, + global::System.IO.Stream image, + string imagename, + global::StabilityAI.CreateStableImageControlStyleAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + string? negativePrompt = default, + global::StabilityAI.CreateStableImageControlStyleRequestAspectRatio? aspectRatio = default, + double? fidelity = default, + double? seed = default, + global::StabilityAI.CreateStableImageControlStyleRequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageControlStyleRequestStylePreset? stylePreset = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + + image = image ?? throw new global::System.ArgumentNullException(nameof(image)); + var request = new global::StabilityAI.CreateStableImageControlStyleRequest + { + Prompt = prompt, + Image = global::System.Array.Empty(), + Imagename = imagename, + NegativePrompt = negativePrompt, + AspectRatio = aspectRatio, + Fidelity = fidelity, + Seed = seed, + OutputFormat = outputFormat, + StylePreset = stylePreset, + }; + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageControlStyleAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageControlStyleAsBytesSecurityRequirements, + operationName: "CreateStableImageControlStyleAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/control/style", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/png"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + var __contentImage = new global::System.Net.Http.StreamContent(image); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.NegativePrompt != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty), + name: "\"negative_prompt\""); + + } + if (request.AspectRatio != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.AspectRatio).HasValue ? (request.AspectRatio).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"aspect_ratio\""); + + } + if (request.Fidelity != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Fidelity, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"fidelity\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + if (request.StylePreset != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.StylePreset).HasValue ? (request.StylePreset).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"style_preset\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageControlStyleAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStyleAsBytes", + methodName: "CreateStableImageControlStyleAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/style\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseHeadersRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStyleAsBytes", + methodName: "CreateStableImageControlStyleAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/style\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStyleAsBytes", + methodName: "CreateStableImageControlStyleAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/style\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + try + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageControlStyleAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStyleAsBytes", + methodName: "CreateStableImageControlStyleAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/style\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStyleAsBytes", + methodName: "CreateStableImageControlStyleAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/style\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageControlStyleResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageControlStyleResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageControlStyleResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageControlStyleResponse5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageControlStyleResponse5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageControlStyleResponse5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateStableImageControlStyleResponse6? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateStableImageControlStyleResponse6.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateStableImageControlStyleResponse6.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageControlStyleResponse7? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageControlStyleResponse7.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageControlStyleResponse7.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageControlStyleResponse8? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageControlStyleResponse8.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageControlStyleResponse8.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + try + { + __response.EnsureSuccessStatusCode(); + + var __content = await __response.Content.ReadAsStreamAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.ResponseStream(__response, __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + } + catch + { + __response.Dispose(); + throw; + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Style Guide
+ /// This service extracts stylistic elements from an input image (control image) and uses it to guide the creation of an output image based on the prompt. The result is a new image in the same style as the control image.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=y0WKjG72RvTE)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `negative_prompt`
+ /// - `aspect_ratio`
+ /// - `fidelity`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1MP. The default resolution is 1024x1024.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// An image whose style you wish to use as the foundation for a generation.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// An image whose style you wish to use as the foundation for a generation.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// Controls the aspect ratio of the generated image.
+ /// Default Value: 1:1 + /// + /// + /// How closely the output image's style resembles the input image's style.
+ /// Default Value: 0.5F + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/style",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./cinematic-portrait.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a majestic portrait of a chicken",
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./chicken-portrait.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task> CreateStableImageControlStyleAsBytesAsResponseAsync( + string contentType, + string prompt, + global::System.IO.Stream image, + string imagename, + global::StabilityAI.CreateStableImageControlStyleAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + string? negativePrompt = default, + global::StabilityAI.CreateStableImageControlStyleRequestAspectRatio? aspectRatio = default, + double? fidelity = default, + double? seed = default, + global::StabilityAI.CreateStableImageControlStyleRequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageControlStyleRequestStylePreset? stylePreset = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + + image = image ?? throw new global::System.ArgumentNullException(nameof(image)); + var request = new global::StabilityAI.CreateStableImageControlStyleRequest + { + Prompt = prompt, + Image = global::System.Array.Empty(), + Imagename = imagename, + NegativePrompt = negativePrompt, + AspectRatio = aspectRatio, + Fidelity = fidelity, + Seed = seed, + OutputFormat = outputFormat, + StylePreset = stylePreset, + }; + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageControlStyleAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageControlStyleAsBytesSecurityRequirements, + operationName: "CreateStableImageControlStyleAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/control/style", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/png"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + var __contentImage = new global::System.Net.Http.StreamContent(image); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.NegativePrompt != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty), + name: "\"negative_prompt\""); + + } + if (request.AspectRatio != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.AspectRatio).HasValue ? (request.AspectRatio).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"aspect_ratio\""); + + } + if (request.Fidelity != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Fidelity, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"fidelity\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + if (request.StylePreset != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.StylePreset).HasValue ? (request.StylePreset).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"style_preset\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageControlStyleAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStyleAsBytes", + methodName: "CreateStableImageControlStyleAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/style\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStyleAsBytes", + methodName: "CreateStableImageControlStyleAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/style\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStyleAsBytes", + methodName: "CreateStableImageControlStyleAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/style\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageControlStyleAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStyleAsBytes", + methodName: "CreateStableImageControlStyleAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/style\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStyleAsBytes", + methodName: "CreateStableImageControlStyleAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/style\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageControlStyleResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageControlStyleResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageControlStyleResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageControlStyleResponse5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageControlStyleResponse5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageControlStyleResponse5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateStableImageControlStyleResponse6? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateStableImageControlStyleResponse6.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateStableImageControlStyleResponse6.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageControlStyleResponse7? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageControlStyleResponse7.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageControlStyleResponse7.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageControlStyleResponse8? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageControlStyleResponse8.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageControlStyleResponse8.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessCreateStableImageControlStyleAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + } +} \ No newline at end of file diff --git a/src/libs/StabilityAI/Generated/StabilityAI.ControlClient.CreateStableImageControlStyleTransfer.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.ControlClient.CreateStableImageControlStyleTransfer.g.cs index bbf7550..36828af 100644 --- a/src/libs/StabilityAI/Generated/StabilityAI.ControlClient.CreateStableImageControlStyleTransfer.g.cs +++ b/src/libs/StabilityAI/Generated/StabilityAI.ControlClient.CreateStableImageControlStyleTransfer.g.cs @@ -297,6 +297,10 @@ partial void ProcessCreateStableImageControlStyleTransferResponseContent( __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || @@ -334,42 +338,6 @@ partial void ProcessCreateStableImageControlStyleTransferResponseContent( var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"accept\""); - - } - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } var __contentInitImage = new global::System.Net.Http.ByteArrayContent(request.InitImage ?? global::System.Array.Empty()); __contentInitImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( request.InitImagename is null @@ -1453,6 +1421,10 @@ request.StyleImagename is null __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || @@ -1490,42 +1462,6 @@ request.StyleImagename is null var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"accept\""); - - } - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } var __contentInitImage = new global::System.Net.Http.StreamContent(initImage); __contentInitImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( request.InitImagename is null @@ -2415,6 +2351,10 @@ request.StyleImagename is null __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || @@ -2452,42 +2392,6 @@ request.StyleImagename is null var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"accept\""); - - } - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } var __contentInitImage = new global::System.Net.Http.StreamContent(initImage); __contentInitImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( request.InitImagename is null diff --git a/src/libs/StabilityAI/Generated/StabilityAI.ControlClient.CreateStableImageControlStyleTransferAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.ControlClient.CreateStableImageControlStyleTransferAsBytes.g.cs new file mode 100644 index 0000000..1f18c13 --- /dev/null +++ b/src/libs/StabilityAI/Generated/StabilityAI.ControlClient.CreateStableImageControlStyleTransferAsBytes.g.cs @@ -0,0 +1,4699 @@ + +#nullable enable + +namespace StabilityAI +{ + public partial class ControlClient + { + + + private static readonly global::StabilityAI.EndPointSecurityRequirement s_CreateStableImageControlStyleTransferAsBytesSecurityRequirement0 = + new global::StabilityAI.EndPointSecurityRequirement + { + Authorizations = new global::StabilityAI.EndPointAuthorizationRequirement[] + { new global::StabilityAI.EndPointAuthorizationRequirement + { + Type = "Http", + SchemeId = "HttpBearer", + Location = "Header", + Name = "Bearer", + FriendlyName = "Bearer", + }, + }, + }; + private static readonly global::StabilityAI.EndPointSecurityRequirement[] s_CreateStableImageControlStyleTransferAsBytesSecurityRequirements = + new global::StabilityAI.EndPointSecurityRequirement[] + { s_CreateStableImageControlStyleTransferAsBytesSecurityRequirement0, + }; + partial void PrepareCreateStableImageControlStyleTransferAsBytesArguments( + global::System.Net.Http.HttpClient httpClient, + ref string contentType, + ref global::StabilityAI.CreateStableImageControlStyleTransferAccept? accept, + ref string? stabilityClientId, + ref string? stabilityClientUserId, + ref string? stabilityClientVersion, + global::StabilityAI.CreateStableImageControlStyleTransferRequest request); + partial void PrepareCreateStableImageControlStyleTransferAsBytesRequest( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpRequestMessage httpRequestMessage, + string contentType, + global::StabilityAI.CreateStableImageControlStyleTransferAccept? accept, + string? stabilityClientId, + string? stabilityClientUserId, + string? stabilityClientVersion, + global::StabilityAI.CreateStableImageControlStyleTransferRequest request); + partial void ProcessCreateStableImageControlStyleTransferAsBytesResponse( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpResponseMessage httpResponseMessage); + + partial void ProcessCreateStableImageControlStyleTransferAsBytesResponseContent( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpResponseMessage httpResponseMessage, + ref byte[] content); + + /// + /// Style Transfer
+ /// Style Transfer applies visual characteristics from reference style images to target images.
+ /// While Style Guide extracts stylistic elements from an input image (control image) and uses it
+ /// to guide the creation of an output image based on the prompt, Style Transfer specifically
+ /// transforms existing content while preserving the original composition.
+ /// This tool helps create consistent content across multiple assets.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to
+ /// [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=YCrxdv5LzqJ9)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `init_image`
+ /// - `style_image`
+ /// The body may optionally include:
+ /// - `prompt`
+ /// - `negative_prompt`
+ /// - `style_strength`
+ /// - `composition_fidelity`
+ /// - `change_strength`
+ /// - `seed`
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1MP, with the same aspect ratio as the `init_image`.
+ /// ### Credits
+ /// Flat rate of 8 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/style-transfer",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "init_image": open("./chicken-portrait.png", "rb"),
+ /// "style_image": open("./glowbot.png", "rb")
+ /// },
+ /// data={
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./glow-chicken.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateStableImageControlStyleTransferAsBytesAsync( + string contentType, + + global::StabilityAI.CreateStableImageControlStyleTransferRequest request, + global::StabilityAI.CreateStableImageControlStyleTransferAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + var __response = await CreateStableImageControlStyleTransferAsBytesAsResponseAsync( + contentType: contentType, + + request: request, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + requestOptions: requestOptions, + cancellationToken: cancellationToken + ).ConfigureAwait(false); + + return __response.Body; + } + /// + /// Style Transfer
+ /// Style Transfer applies visual characteristics from reference style images to target images.
+ /// While Style Guide extracts stylistic elements from an input image (control image) and uses it
+ /// to guide the creation of an output image based on the prompt, Style Transfer specifically
+ /// transforms existing content while preserving the original composition.
+ /// This tool helps create consistent content across multiple assets.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to
+ /// [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=YCrxdv5LzqJ9)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `init_image`
+ /// - `style_image`
+ /// The body may optionally include:
+ /// - `prompt`
+ /// - `negative_prompt`
+ /// - `style_strength`
+ /// - `composition_fidelity`
+ /// - `change_strength`
+ /// - `seed`
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1MP, with the same aspect ratio as the `init_image`.
+ /// ### Credits
+ /// Flat rate of 8 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/style-transfer",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "init_image": open("./chicken-portrait.png", "rb"),
+ /// "style_image": open("./glowbot.png", "rb")
+ /// },
+ /// data={
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./glow-chicken.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateStableImageControlStyleTransferAsBytesAsStreamAsync( + string contentType, + + global::StabilityAI.CreateStableImageControlStyleTransferRequest request, + global::StabilityAI.CreateStableImageControlStyleTransferAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + request = request ?? throw new global::System.ArgumentNullException(nameof(request)); + + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageControlStyleTransferAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageControlStyleTransferAsBytesSecurityRequirements, + operationName: "CreateStableImageControlStyleTransferAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/control/style-transfer", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/png"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + var __contentInitImage = new global::System.Net.Http.ByteArrayContent(request.InitImage ?? global::System.Array.Empty()); + __contentInitImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.InitImagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.InitImagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentInitImage, + name: "\"init_image\"", + fileName: request.InitImagename != null ? $"\"{request.InitImagename}\"" : string.Empty); + if (__contentInitImage.Headers.ContentDisposition != null) + { + __contentInitImage.Headers.ContentDisposition.FileNameStar = null; + } + + var __contentStyleImage = new global::System.Net.Http.ByteArrayContent(request.StyleImage ?? global::System.Array.Empty()); + __contentStyleImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.StyleImagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.StyleImagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentStyleImage, + name: "\"style_image\"", + fileName: request.StyleImagename != null ? $"\"{request.StyleImagename}\"" : string.Empty); + if (__contentStyleImage.Headers.ContentDisposition != null) + { + __contentStyleImage.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.Prompt != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + } + if (request.NegativePrompt != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty), + name: "\"negative_prompt\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.StyleStrength != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.StyleStrength, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"style_strength\""); + + } + if (request.CompositionFidelity != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.CompositionFidelity, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"composition_fidelity\""); + + } + if (request.ChangeStrength != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.ChangeStrength, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"change_strength\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageControlStyleTransferAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStyleTransferAsBytes", + methodName: "CreateStableImageControlStyleTransferAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/style-transfer\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseHeadersRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStyleTransferAsBytes", + methodName: "CreateStableImageControlStyleTransferAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/style-transfer\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStyleTransferAsBytes", + methodName: "CreateStableImageControlStyleTransferAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/style-transfer\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + try + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageControlStyleTransferAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStyleTransferAsBytes", + methodName: "CreateStableImageControlStyleTransferAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/style-transfer\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStyleTransferAsBytes", + methodName: "CreateStableImageControlStyleTransferAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/style-transfer\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageControlStyleTransferResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageControlStyleTransferResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageControlStyleTransferResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageControlStyleTransferResponse5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageControlStyleTransferResponse5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageControlStyleTransferResponse5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateStableImageControlStyleTransferResponse6? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateStableImageControlStyleTransferResponse6.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateStableImageControlStyleTransferResponse6.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageControlStyleTransferResponse7? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageControlStyleTransferResponse7.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageControlStyleTransferResponse7.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageControlStyleTransferResponse8? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageControlStyleTransferResponse8.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageControlStyleTransferResponse8.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + try + { + __response.EnsureSuccessStatusCode(); + + var __content = await __response.Content.ReadAsStreamAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.ResponseStream(__response, __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + } + catch + { + __response.Dispose(); + throw; + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Style Transfer
+ /// Style Transfer applies visual characteristics from reference style images to target images.
+ /// While Style Guide extracts stylistic elements from an input image (control image) and uses it
+ /// to guide the creation of an output image based on the prompt, Style Transfer specifically
+ /// transforms existing content while preserving the original composition.
+ /// This tool helps create consistent content across multiple assets.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to
+ /// [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=YCrxdv5LzqJ9)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `init_image`
+ /// - `style_image`
+ /// The body may optionally include:
+ /// - `prompt`
+ /// - `negative_prompt`
+ /// - `style_strength`
+ /// - `composition_fidelity`
+ /// - `change_strength`
+ /// - `seed`
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1MP, with the same aspect ratio as the `init_image`.
+ /// ### Credits
+ /// Flat rate of 8 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/style-transfer",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "init_image": open("./chicken-portrait.png", "rb"),
+ /// "style_image": open("./glowbot.png", "rb")
+ /// },
+ /// data={
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./glow-chicken.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task> CreateStableImageControlStyleTransferAsBytesAsResponseAsync( + string contentType, + + global::StabilityAI.CreateStableImageControlStyleTransferRequest request, + global::StabilityAI.CreateStableImageControlStyleTransferAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + request = request ?? throw new global::System.ArgumentNullException(nameof(request)); + + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageControlStyleTransferAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageControlStyleTransferAsBytesSecurityRequirements, + operationName: "CreateStableImageControlStyleTransferAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/control/style-transfer", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/png"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + var __contentInitImage = new global::System.Net.Http.ByteArrayContent(request.InitImage ?? global::System.Array.Empty()); + __contentInitImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.InitImagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.InitImagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentInitImage, + name: "\"init_image\"", + fileName: request.InitImagename != null ? $"\"{request.InitImagename}\"" : string.Empty); + if (__contentInitImage.Headers.ContentDisposition != null) + { + __contentInitImage.Headers.ContentDisposition.FileNameStar = null; + } + + var __contentStyleImage = new global::System.Net.Http.ByteArrayContent(request.StyleImage ?? global::System.Array.Empty()); + __contentStyleImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.StyleImagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.StyleImagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentStyleImage, + name: "\"style_image\"", + fileName: request.StyleImagename != null ? $"\"{request.StyleImagename}\"" : string.Empty); + if (__contentStyleImage.Headers.ContentDisposition != null) + { + __contentStyleImage.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.Prompt != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + } + if (request.NegativePrompt != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty), + name: "\"negative_prompt\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.StyleStrength != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.StyleStrength, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"style_strength\""); + + } + if (request.CompositionFidelity != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.CompositionFidelity, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"composition_fidelity\""); + + } + if (request.ChangeStrength != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.ChangeStrength, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"change_strength\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageControlStyleTransferAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStyleTransferAsBytes", + methodName: "CreateStableImageControlStyleTransferAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/style-transfer\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStyleTransferAsBytes", + methodName: "CreateStableImageControlStyleTransferAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/style-transfer\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStyleTransferAsBytes", + methodName: "CreateStableImageControlStyleTransferAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/style-transfer\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageControlStyleTransferAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStyleTransferAsBytes", + methodName: "CreateStableImageControlStyleTransferAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/style-transfer\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStyleTransferAsBytes", + methodName: "CreateStableImageControlStyleTransferAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/style-transfer\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageControlStyleTransferResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageControlStyleTransferResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageControlStyleTransferResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageControlStyleTransferResponse5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageControlStyleTransferResponse5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageControlStyleTransferResponse5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateStableImageControlStyleTransferResponse6? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateStableImageControlStyleTransferResponse6.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateStableImageControlStyleTransferResponse6.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageControlStyleTransferResponse7? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageControlStyleTransferResponse7.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageControlStyleTransferResponse7.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageControlStyleTransferResponse8? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageControlStyleTransferResponse8.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageControlStyleTransferResponse8.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessCreateStableImageControlStyleTransferAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Style Transfer
+ /// Style Transfer applies visual characteristics from reference style images to target images.
+ /// While Style Guide extracts stylistic elements from an input image (control image) and uses it
+ /// to guide the creation of an output image based on the prompt, Style Transfer specifically
+ /// transforms existing content while preserving the original composition.
+ /// This tool helps create consistent content across multiple assets.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to
+ /// [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=YCrxdv5LzqJ9)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `init_image`
+ /// - `style_image`
+ /// The body may optionally include:
+ /// - `prompt`
+ /// - `negative_prompt`
+ /// - `style_strength`
+ /// - `composition_fidelity`
+ /// - `change_strength`
+ /// - `seed`
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1MP, with the same aspect ratio as the `init_image`.
+ /// ### Credits
+ /// Flat rate of 8 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// An image containing the subject you wish to restyle.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 64 and 16,383 pixels
+ /// - Height must be between 64 and 16,383 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// An image containing the subject you wish to restyle.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 64 and 16,383 pixels
+ /// - Height must be between 64 and 16,383 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// An image containing the new style.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 64 and 16,383 pixels
+ /// - Height must be between 64 and 16,383 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png + /// + /// + /// An image containing the new style.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 64 and 16,383 pixels
+ /// - Height must be between 64 and 16,383 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Sometimes referred to as _denoising_, this parameter controls how much influence the
+ /// `style_image` parameter has on the generated image. A value of 0 would yield an image that
+ /// is identical to the input. A value of 1 would be as if you passed in no image at all.
+ /// Default Value: 1 + /// + /// + /// How closely the output image's style resembles the input image's style.
+ /// Default Value: 0.9F + /// + /// + /// How much the original image should change
+ /// Default Value: 0.9F + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + public async global::System.Threading.Tasks.Task CreateStableImageControlStyleTransferAsBytesAsync( + string contentType, + byte[] initImage, + string initImagename, + byte[] styleImage, + string styleImagename, + global::StabilityAI.CreateStableImageControlStyleTransferAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + string? prompt = default, + string? negativePrompt = default, + double? seed = default, + double? styleStrength = default, + double? compositionFidelity = default, + double? changeStrength = default, + global::StabilityAI.CreateStableImageControlStyleTransferRequestOutputFormat? outputFormat = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + var __request = new global::StabilityAI.CreateStableImageControlStyleTransferRequest + { + InitImage = initImage, + InitImagename = initImagename, + StyleImage = styleImage, + StyleImagename = styleImagename, + Prompt = prompt, + NegativePrompt = negativePrompt, + Seed = seed, + StyleStrength = styleStrength, + CompositionFidelity = compositionFidelity, + ChangeStrength = changeStrength, + OutputFormat = outputFormat, + }; + + return await CreateStableImageControlStyleTransferAsBytesAsync( + contentType: contentType, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: __request, + requestOptions: requestOptions, + cancellationToken: cancellationToken).ConfigureAwait(false); + } + + /// + /// Style Transfer
+ /// Style Transfer applies visual characteristics from reference style images to target images.
+ /// While Style Guide extracts stylistic elements from an input image (control image) and uses it
+ /// to guide the creation of an output image based on the prompt, Style Transfer specifically
+ /// transforms existing content while preserving the original composition.
+ /// This tool helps create consistent content across multiple assets.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to
+ /// [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=YCrxdv5LzqJ9)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `init_image`
+ /// - `style_image`
+ /// The body may optionally include:
+ /// - `prompt`
+ /// - `negative_prompt`
+ /// - `style_strength`
+ /// - `composition_fidelity`
+ /// - `change_strength`
+ /// - `seed`
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1MP, with the same aspect ratio as the `init_image`.
+ /// ### Credits
+ /// Flat rate of 8 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// An image containing the subject you wish to restyle.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 64 and 16,383 pixels
+ /// - Height must be between 64 and 16,383 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// An image containing the subject you wish to restyle.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 64 and 16,383 pixels
+ /// - Height must be between 64 and 16,383 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// An image containing the new style.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 64 and 16,383 pixels
+ /// - Height must be between 64 and 16,383 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png + /// + /// + /// An image containing the new style.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 64 and 16,383 pixels
+ /// - Height must be between 64 and 16,383 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Sometimes referred to as _denoising_, this parameter controls how much influence the
+ /// `style_image` parameter has on the generated image. A value of 0 would yield an image that
+ /// is identical to the input. A value of 1 would be as if you passed in no image at all.
+ /// Default Value: 1 + /// + /// + /// How closely the output image's style resembles the input image's style.
+ /// Default Value: 0.9F + /// + /// + /// How much the original image should change
+ /// Default Value: 0.9F + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/style-transfer",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "init_image": open("./chicken-portrait.png", "rb"),
+ /// "style_image": open("./glowbot.png", "rb")
+ /// },
+ /// data={
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./glow-chicken.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateStableImageControlStyleTransferAsBytesAsync( + string contentType, + global::System.IO.Stream initImage, + string initImagename, + global::System.IO.Stream styleImage, + string styleImagename, + global::StabilityAI.CreateStableImageControlStyleTransferAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + string? prompt = default, + string? negativePrompt = default, + double? seed = default, + double? styleStrength = default, + double? compositionFidelity = default, + double? changeStrength = default, + global::StabilityAI.CreateStableImageControlStyleTransferRequestOutputFormat? outputFormat = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + + initImage = initImage ?? throw new global::System.ArgumentNullException(nameof(initImage)); + styleImage = styleImage ?? throw new global::System.ArgumentNullException(nameof(styleImage)); + var request = new global::StabilityAI.CreateStableImageControlStyleTransferRequest + { + InitImage = global::System.Array.Empty(), + InitImagename = initImagename, + StyleImage = global::System.Array.Empty(), + StyleImagename = styleImagename, + Prompt = prompt, + NegativePrompt = negativePrompt, + Seed = seed, + StyleStrength = styleStrength, + CompositionFidelity = compositionFidelity, + ChangeStrength = changeStrength, + OutputFormat = outputFormat, + }; + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageControlStyleTransferAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageControlStyleTransferAsBytesSecurityRequirements, + operationName: "CreateStableImageControlStyleTransferAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/control/style-transfer", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/png"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + var __contentInitImage = new global::System.Net.Http.StreamContent(initImage); + __contentInitImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.InitImagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.InitImagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentInitImage, + name: "\"init_image\"", + fileName: request.InitImagename != null ? $"\"{request.InitImagename}\"" : string.Empty); + if (__contentInitImage.Headers.ContentDisposition != null) + { + __contentInitImage.Headers.ContentDisposition.FileNameStar = null; + } + + var __contentStyleImage = new global::System.Net.Http.StreamContent(styleImage); + __contentStyleImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.StyleImagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.StyleImagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentStyleImage, + name: "\"style_image\"", + fileName: request.StyleImagename != null ? $"\"{request.StyleImagename}\"" : string.Empty); + if (__contentStyleImage.Headers.ContentDisposition != null) + { + __contentStyleImage.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.Prompt != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + } + if (request.NegativePrompt != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty), + name: "\"negative_prompt\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.StyleStrength != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.StyleStrength, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"style_strength\""); + + } + if (request.CompositionFidelity != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.CompositionFidelity, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"composition_fidelity\""); + + } + if (request.ChangeStrength != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.ChangeStrength, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"change_strength\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageControlStyleTransferAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStyleTransferAsBytes", + methodName: "CreateStableImageControlStyleTransferAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/style-transfer\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStyleTransferAsBytes", + methodName: "CreateStableImageControlStyleTransferAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/style-transfer\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStyleTransferAsBytes", + methodName: "CreateStableImageControlStyleTransferAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/style-transfer\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageControlStyleTransferAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStyleTransferAsBytes", + methodName: "CreateStableImageControlStyleTransferAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/style-transfer\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStyleTransferAsBytes", + methodName: "CreateStableImageControlStyleTransferAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/style-transfer\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageControlStyleTransferResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageControlStyleTransferResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageControlStyleTransferResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageControlStyleTransferResponse5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageControlStyleTransferResponse5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageControlStyleTransferResponse5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateStableImageControlStyleTransferResponse6? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateStableImageControlStyleTransferResponse6.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateStableImageControlStyleTransferResponse6.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageControlStyleTransferResponse7? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageControlStyleTransferResponse7.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageControlStyleTransferResponse7.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageControlStyleTransferResponse8? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageControlStyleTransferResponse8.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageControlStyleTransferResponse8.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessCreateStableImageControlStyleTransferAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return __content; + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return __content; + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Style Transfer
+ /// Style Transfer applies visual characteristics from reference style images to target images.
+ /// While Style Guide extracts stylistic elements from an input image (control image) and uses it
+ /// to guide the creation of an output image based on the prompt, Style Transfer specifically
+ /// transforms existing content while preserving the original composition.
+ /// This tool helps create consistent content across multiple assets.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to
+ /// [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=YCrxdv5LzqJ9)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `init_image`
+ /// - `style_image`
+ /// The body may optionally include:
+ /// - `prompt`
+ /// - `negative_prompt`
+ /// - `style_strength`
+ /// - `composition_fidelity`
+ /// - `change_strength`
+ /// - `seed`
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1MP, with the same aspect ratio as the `init_image`.
+ /// ### Credits
+ /// Flat rate of 8 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// An image containing the subject you wish to restyle.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 64 and 16,383 pixels
+ /// - Height must be between 64 and 16,383 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// An image containing the subject you wish to restyle.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 64 and 16,383 pixels
+ /// - Height must be between 64 and 16,383 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// An image containing the new style.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 64 and 16,383 pixels
+ /// - Height must be between 64 and 16,383 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png + /// + /// + /// An image containing the new style.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 64 and 16,383 pixels
+ /// - Height must be between 64 and 16,383 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Sometimes referred to as _denoising_, this parameter controls how much influence the
+ /// `style_image` parameter has on the generated image. A value of 0 would yield an image that
+ /// is identical to the input. A value of 1 would be as if you passed in no image at all.
+ /// Default Value: 1 + /// + /// + /// How closely the output image's style resembles the input image's style.
+ /// Default Value: 0.9F + /// + /// + /// How much the original image should change
+ /// Default Value: 0.9F + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/style-transfer",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "init_image": open("./chicken-portrait.png", "rb"),
+ /// "style_image": open("./glowbot.png", "rb")
+ /// },
+ /// data={
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./glow-chicken.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateStableImageControlStyleTransferAsBytesAsStreamAsync( + string contentType, + global::System.IO.Stream initImage, + string initImagename, + global::System.IO.Stream styleImage, + string styleImagename, + global::StabilityAI.CreateStableImageControlStyleTransferAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + string? prompt = default, + string? negativePrompt = default, + double? seed = default, + double? styleStrength = default, + double? compositionFidelity = default, + double? changeStrength = default, + global::StabilityAI.CreateStableImageControlStyleTransferRequestOutputFormat? outputFormat = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + + initImage = initImage ?? throw new global::System.ArgumentNullException(nameof(initImage)); + styleImage = styleImage ?? throw new global::System.ArgumentNullException(nameof(styleImage)); + var request = new global::StabilityAI.CreateStableImageControlStyleTransferRequest + { + InitImage = global::System.Array.Empty(), + InitImagename = initImagename, + StyleImage = global::System.Array.Empty(), + StyleImagename = styleImagename, + Prompt = prompt, + NegativePrompt = negativePrompt, + Seed = seed, + StyleStrength = styleStrength, + CompositionFidelity = compositionFidelity, + ChangeStrength = changeStrength, + OutputFormat = outputFormat, + }; + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageControlStyleTransferAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageControlStyleTransferAsBytesSecurityRequirements, + operationName: "CreateStableImageControlStyleTransferAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/control/style-transfer", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/png"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + var __contentInitImage = new global::System.Net.Http.StreamContent(initImage); + __contentInitImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.InitImagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.InitImagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentInitImage, + name: "\"init_image\"", + fileName: request.InitImagename != null ? $"\"{request.InitImagename}\"" : string.Empty); + if (__contentInitImage.Headers.ContentDisposition != null) + { + __contentInitImage.Headers.ContentDisposition.FileNameStar = null; + } + + var __contentStyleImage = new global::System.Net.Http.StreamContent(styleImage); + __contentStyleImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.StyleImagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.StyleImagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentStyleImage, + name: "\"style_image\"", + fileName: request.StyleImagename != null ? $"\"{request.StyleImagename}\"" : string.Empty); + if (__contentStyleImage.Headers.ContentDisposition != null) + { + __contentStyleImage.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.Prompt != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + } + if (request.NegativePrompt != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty), + name: "\"negative_prompt\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.StyleStrength != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.StyleStrength, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"style_strength\""); + + } + if (request.CompositionFidelity != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.CompositionFidelity, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"composition_fidelity\""); + + } + if (request.ChangeStrength != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.ChangeStrength, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"change_strength\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageControlStyleTransferAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStyleTransferAsBytes", + methodName: "CreateStableImageControlStyleTransferAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/style-transfer\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseHeadersRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStyleTransferAsBytes", + methodName: "CreateStableImageControlStyleTransferAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/style-transfer\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStyleTransferAsBytes", + methodName: "CreateStableImageControlStyleTransferAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/style-transfer\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + try + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageControlStyleTransferAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStyleTransferAsBytes", + methodName: "CreateStableImageControlStyleTransferAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/style-transfer\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStyleTransferAsBytes", + methodName: "CreateStableImageControlStyleTransferAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/style-transfer\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageControlStyleTransferResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageControlStyleTransferResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageControlStyleTransferResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageControlStyleTransferResponse5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageControlStyleTransferResponse5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageControlStyleTransferResponse5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateStableImageControlStyleTransferResponse6? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateStableImageControlStyleTransferResponse6.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateStableImageControlStyleTransferResponse6.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageControlStyleTransferResponse7? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageControlStyleTransferResponse7.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageControlStyleTransferResponse7.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageControlStyleTransferResponse8? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageControlStyleTransferResponse8.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageControlStyleTransferResponse8.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + try + { + __response.EnsureSuccessStatusCode(); + + var __content = await __response.Content.ReadAsStreamAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.ResponseStream(__response, __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + } + catch + { + __response.Dispose(); + throw; + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Style Transfer
+ /// Style Transfer applies visual characteristics from reference style images to target images.
+ /// While Style Guide extracts stylistic elements from an input image (control image) and uses it
+ /// to guide the creation of an output image based on the prompt, Style Transfer specifically
+ /// transforms existing content while preserving the original composition.
+ /// This tool helps create consistent content across multiple assets.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to
+ /// [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=YCrxdv5LzqJ9)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `init_image`
+ /// - `style_image`
+ /// The body may optionally include:
+ /// - `prompt`
+ /// - `negative_prompt`
+ /// - `style_strength`
+ /// - `composition_fidelity`
+ /// - `change_strength`
+ /// - `seed`
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1MP, with the same aspect ratio as the `init_image`.
+ /// ### Credits
+ /// Flat rate of 8 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// An image containing the subject you wish to restyle.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 64 and 16,383 pixels
+ /// - Height must be between 64 and 16,383 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// An image containing the subject you wish to restyle.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 64 and 16,383 pixels
+ /// - Height must be between 64 and 16,383 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// An image containing the new style.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 64 and 16,383 pixels
+ /// - Height must be between 64 and 16,383 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png + /// + /// + /// An image containing the new style.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 64 and 16,383 pixels
+ /// - Height must be between 64 and 16,383 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Sometimes referred to as _denoising_, this parameter controls how much influence the
+ /// `style_image` parameter has on the generated image. A value of 0 would yield an image that
+ /// is identical to the input. A value of 1 would be as if you passed in no image at all.
+ /// Default Value: 1 + /// + /// + /// How closely the output image's style resembles the input image's style.
+ /// Default Value: 0.9F + /// + /// + /// How much the original image should change
+ /// Default Value: 0.9F + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/style-transfer",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "init_image": open("./chicken-portrait.png", "rb"),
+ /// "style_image": open("./glowbot.png", "rb")
+ /// },
+ /// data={
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./glow-chicken.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task> CreateStableImageControlStyleTransferAsBytesAsResponseAsync( + string contentType, + global::System.IO.Stream initImage, + string initImagename, + global::System.IO.Stream styleImage, + string styleImagename, + global::StabilityAI.CreateStableImageControlStyleTransferAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + string? prompt = default, + string? negativePrompt = default, + double? seed = default, + double? styleStrength = default, + double? compositionFidelity = default, + double? changeStrength = default, + global::StabilityAI.CreateStableImageControlStyleTransferRequestOutputFormat? outputFormat = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + + initImage = initImage ?? throw new global::System.ArgumentNullException(nameof(initImage)); + styleImage = styleImage ?? throw new global::System.ArgumentNullException(nameof(styleImage)); + var request = new global::StabilityAI.CreateStableImageControlStyleTransferRequest + { + InitImage = global::System.Array.Empty(), + InitImagename = initImagename, + StyleImage = global::System.Array.Empty(), + StyleImagename = styleImagename, + Prompt = prompt, + NegativePrompt = negativePrompt, + Seed = seed, + StyleStrength = styleStrength, + CompositionFidelity = compositionFidelity, + ChangeStrength = changeStrength, + OutputFormat = outputFormat, + }; + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageControlStyleTransferAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageControlStyleTransferAsBytesSecurityRequirements, + operationName: "CreateStableImageControlStyleTransferAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/control/style-transfer", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/png"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + var __contentInitImage = new global::System.Net.Http.StreamContent(initImage); + __contentInitImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.InitImagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.InitImagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentInitImage, + name: "\"init_image\"", + fileName: request.InitImagename != null ? $"\"{request.InitImagename}\"" : string.Empty); + if (__contentInitImage.Headers.ContentDisposition != null) + { + __contentInitImage.Headers.ContentDisposition.FileNameStar = null; + } + + var __contentStyleImage = new global::System.Net.Http.StreamContent(styleImage); + __contentStyleImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.StyleImagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.StyleImagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentStyleImage, + name: "\"style_image\"", + fileName: request.StyleImagename != null ? $"\"{request.StyleImagename}\"" : string.Empty); + if (__contentStyleImage.Headers.ContentDisposition != null) + { + __contentStyleImage.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.Prompt != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + } + if (request.NegativePrompt != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty), + name: "\"negative_prompt\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.StyleStrength != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.StyleStrength, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"style_strength\""); + + } + if (request.CompositionFidelity != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.CompositionFidelity, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"composition_fidelity\""); + + } + if (request.ChangeStrength != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.ChangeStrength, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"change_strength\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageControlStyleTransferAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStyleTransferAsBytes", + methodName: "CreateStableImageControlStyleTransferAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/style-transfer\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStyleTransferAsBytes", + methodName: "CreateStableImageControlStyleTransferAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/style-transfer\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStyleTransferAsBytes", + methodName: "CreateStableImageControlStyleTransferAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/style-transfer\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageControlStyleTransferAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStyleTransferAsBytes", + methodName: "CreateStableImageControlStyleTransferAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/style-transfer\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageControlStyleTransferAsBytes", + methodName: "CreateStableImageControlStyleTransferAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/control/style-transfer\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageControlStyleTransferResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageControlStyleTransferResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageControlStyleTransferResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageControlStyleTransferResponse5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageControlStyleTransferResponse5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageControlStyleTransferResponse5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateStableImageControlStyleTransferResponse6? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateStableImageControlStyleTransferResponse6.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateStableImageControlStyleTransferResponse6.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageControlStyleTransferResponse7? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageControlStyleTransferResponse7.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageControlStyleTransferResponse7.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageControlStyleTransferResponse8? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageControlStyleTransferResponse8.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageControlStyleTransferResponse8.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessCreateStableImageControlStyleTransferAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + } +} \ No newline at end of file diff --git a/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditErase.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditErase.g.cs index a6b2f02..40c5c59 100644 --- a/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditErase.g.cs +++ b/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditErase.g.cs @@ -283,6 +283,10 @@ partial void ProcessCreateStableImageEditEraseResponseContent( __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || @@ -320,42 +324,6 @@ partial void ProcessCreateStableImageEditEraseResponseContent( var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"accept\""); - - } - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } var __contentImage = new global::System.Net.Http.ByteArrayContent(request.Image ?? global::System.Array.Empty()); __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( request.Imagename is null @@ -1307,6 +1275,10 @@ request.Maskname is null __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || @@ -1344,42 +1316,6 @@ request.Maskname is null var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"accept\""); - - } - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } var __contentImage = new global::System.Net.Http.StreamContent(image); __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( request.Imagename is null @@ -2170,6 +2106,10 @@ request.Maskname is null __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || @@ -2207,42 +2147,6 @@ request.Maskname is null var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"accept\""); - - } - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } var __contentImage = new global::System.Net.Http.StreamContent(image); __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( request.Imagename is null diff --git a/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditEraseAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditEraseAsBytes.g.cs new file mode 100644 index 0000000..5c0e7e1 --- /dev/null +++ b/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditEraseAsBytes.g.cs @@ -0,0 +1,4218 @@ + +#nullable enable + +namespace StabilityAI +{ + public partial class EditClient + { + + + private static readonly global::StabilityAI.EndPointSecurityRequirement s_CreateStableImageEditEraseAsBytesSecurityRequirement0 = + new global::StabilityAI.EndPointSecurityRequirement + { + Authorizations = new global::StabilityAI.EndPointAuthorizationRequirement[] + { new global::StabilityAI.EndPointAuthorizationRequirement + { + Type = "Http", + SchemeId = "HttpBearer", + Location = "Header", + Name = "Bearer", + FriendlyName = "Bearer", + }, + }, + }; + private static readonly global::StabilityAI.EndPointSecurityRequirement[] s_CreateStableImageEditEraseAsBytesSecurityRequirements = + new global::StabilityAI.EndPointSecurityRequirement[] + { s_CreateStableImageEditEraseAsBytesSecurityRequirement0, + }; + partial void PrepareCreateStableImageEditEraseAsBytesArguments( + global::System.Net.Http.HttpClient httpClient, + ref string contentType, + ref global::StabilityAI.CreateStableImageEditEraseAccept? accept, + ref string? stabilityClientId, + ref string? stabilityClientUserId, + ref string? stabilityClientVersion, + global::StabilityAI.CreateStableImageEditEraseRequest request); + partial void PrepareCreateStableImageEditEraseAsBytesRequest( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpRequestMessage httpRequestMessage, + string contentType, + global::StabilityAI.CreateStableImageEditEraseAccept? accept, + string? stabilityClientId, + string? stabilityClientUserId, + string? stabilityClientVersion, + global::StabilityAI.CreateStableImageEditEraseRequest request); + partial void ProcessCreateStableImageEditEraseAsBytesResponse( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpResponseMessage httpResponseMessage); + + partial void ProcessCreateStableImageEditEraseAsBytesResponseContent( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpResponseMessage httpResponseMessage, + ref byte[] content); + + /// + /// Erase
+ /// The Erase service removes unwanted objects, such as blemishes on portraits or items on desks, using image masks.
+ /// The mask is provided in one of two ways:
+ /// 1. Explicitly passing in a separate image via the `mask` parameter
+ /// 2. Derived from the alpha channel of the `image` parameter.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// Optionally, the body of the request may also include:
+ /// - `mask`
+ /// - `seed`
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/erase",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./kangaroo-on-the-beach.png", "rb"),
+ /// "mask": open("./mask-of-kangaroo.png", "rb"),
+ /// },
+ /// data={
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./just-the-beach.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateStableImageEditEraseAsBytesAsync( + string contentType, + + global::StabilityAI.CreateStableImageEditEraseRequest request, + global::StabilityAI.CreateStableImageEditEraseAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + var __response = await CreateStableImageEditEraseAsBytesAsResponseAsync( + contentType: contentType, + + request: request, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + requestOptions: requestOptions, + cancellationToken: cancellationToken + ).ConfigureAwait(false); + + return __response.Body; + } + /// + /// Erase
+ /// The Erase service removes unwanted objects, such as blemishes on portraits or items on desks, using image masks.
+ /// The mask is provided in one of two ways:
+ /// 1. Explicitly passing in a separate image via the `mask` parameter
+ /// 2. Derived from the alpha channel of the `image` parameter.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// Optionally, the body of the request may also include:
+ /// - `mask`
+ /// - `seed`
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/erase",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./kangaroo-on-the-beach.png", "rb"),
+ /// "mask": open("./mask-of-kangaroo.png", "rb"),
+ /// },
+ /// data={
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./just-the-beach.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateStableImageEditEraseAsBytesAsStreamAsync( + string contentType, + + global::StabilityAI.CreateStableImageEditEraseRequest request, + global::StabilityAI.CreateStableImageEditEraseAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + request = request ?? throw new global::System.ArgumentNullException(nameof(request)); + + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageEditEraseAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageEditEraseAsBytesSecurityRequirements, + operationName: "CreateStableImageEditEraseAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/edit/erase", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/jpeg"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + var __contentImage = new global::System.Net.Http.ByteArrayContent(request.Image ?? global::System.Array.Empty()); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.Mask != default) + { + + var __contentMask = new global::System.Net.Http.ByteArrayContent(request.Mask ?? global::System.Array.Empty()); + __contentMask.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Maskname is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Maskname) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentMask, + name: "\"mask\"", + fileName: request.Maskname != null ? $"\"{request.Maskname}\"" : string.Empty); + if (__contentMask.Headers.ContentDisposition != null) + { + __contentMask.Headers.ContentDisposition.FileNameStar = null; + } + + } + if (request.GrowMask != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.GrowMask, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"grow_mask\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageEditEraseAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditEraseAsBytes", + methodName: "CreateStableImageEditEraseAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/erase\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseHeadersRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditEraseAsBytes", + methodName: "CreateStableImageEditEraseAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/erase\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditEraseAsBytes", + methodName: "CreateStableImageEditEraseAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/erase\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + try + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageEditEraseAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditEraseAsBytes", + methodName: "CreateStableImageEditEraseAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/erase\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditEraseAsBytes", + methodName: "CreateStableImageEditEraseAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/erase\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageEditEraseResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageEditEraseResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageEditEraseResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageEditEraseResponse5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageEditEraseResponse5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageEditEraseResponse5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageEditEraseResponse6? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageEditEraseResponse6.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageEditEraseResponse6.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageEditEraseResponse7? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageEditEraseResponse7.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageEditEraseResponse7.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + try + { + __response.EnsureSuccessStatusCode(); + + var __content = await __response.Content.ReadAsStreamAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.ResponseStream(__response, __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + } + catch + { + __response.Dispose(); + throw; + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Erase
+ /// The Erase service removes unwanted objects, such as blemishes on portraits or items on desks, using image masks.
+ /// The mask is provided in one of two ways:
+ /// 1. Explicitly passing in a separate image via the `mask` parameter
+ /// 2. Derived from the alpha channel of the `image` parameter.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// Optionally, the body of the request may also include:
+ /// - `mask`
+ /// - `seed`
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/erase",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./kangaroo-on-the-beach.png", "rb"),
+ /// "mask": open("./mask-of-kangaroo.png", "rb"),
+ /// },
+ /// data={
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./just-the-beach.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task> CreateStableImageEditEraseAsBytesAsResponseAsync( + string contentType, + + global::StabilityAI.CreateStableImageEditEraseRequest request, + global::StabilityAI.CreateStableImageEditEraseAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + request = request ?? throw new global::System.ArgumentNullException(nameof(request)); + + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageEditEraseAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageEditEraseAsBytesSecurityRequirements, + operationName: "CreateStableImageEditEraseAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/edit/erase", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/jpeg"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + var __contentImage = new global::System.Net.Http.ByteArrayContent(request.Image ?? global::System.Array.Empty()); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.Mask != default) + { + + var __contentMask = new global::System.Net.Http.ByteArrayContent(request.Mask ?? global::System.Array.Empty()); + __contentMask.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Maskname is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Maskname) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentMask, + name: "\"mask\"", + fileName: request.Maskname != null ? $"\"{request.Maskname}\"" : string.Empty); + if (__contentMask.Headers.ContentDisposition != null) + { + __contentMask.Headers.ContentDisposition.FileNameStar = null; + } + + } + if (request.GrowMask != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.GrowMask, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"grow_mask\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageEditEraseAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditEraseAsBytes", + methodName: "CreateStableImageEditEraseAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/erase\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditEraseAsBytes", + methodName: "CreateStableImageEditEraseAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/erase\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditEraseAsBytes", + methodName: "CreateStableImageEditEraseAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/erase\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageEditEraseAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditEraseAsBytes", + methodName: "CreateStableImageEditEraseAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/erase\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditEraseAsBytes", + methodName: "CreateStableImageEditEraseAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/erase\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageEditEraseResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageEditEraseResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageEditEraseResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageEditEraseResponse5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageEditEraseResponse5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageEditEraseResponse5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageEditEraseResponse6? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageEditEraseResponse6.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageEditEraseResponse6.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageEditEraseResponse7? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageEditEraseResponse7.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageEditEraseResponse7.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessCreateStableImageEditEraseAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Erase
+ /// The Erase service removes unwanted objects, such as blemishes on portraits or items on desks, using image masks.
+ /// The mask is provided in one of two ways:
+ /// 1. Explicitly passing in a separate image via the `mask` parameter
+ /// 2. Derived from the alpha channel of the `image` parameter.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// Optionally, the body of the request may also include:
+ /// - `mask`
+ /// - `seed`
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// The image you wish to erase from.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png + /// + /// + /// The image you wish to erase from.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png + /// + /// + /// Controls the strength of the inpainting process on a per-pixel basis, either via a
+ /// second image (passed into this parameter) or via the alpha channel of the `image` parameter.
+ /// **Passing in a Mask**
+ /// The image passed to this parameter should be a black and white image that represents,
+ /// at any pixel, the strength of inpainting based on how dark or light the given pixel is.
+ /// Completely black pixels represent no inpainting strength while completely white pixels
+ /// represent maximum strength.
+ /// In the event the mask is a different size than the `image` parameter, it will be automatically resized.
+ /// **Alpha Channel Support**
+ /// If you don't provide an explicit mask, one will be derived from the alpha channel of the `image` parameter.
+ /// Transparent pixels will be inpainted while opaque pixels will be preserved.
+ /// In the event an `image` with an alpha channel is provided along with a `mask`, the `mask` will take precedence.
+ /// Example: ./some/image.png + /// + /// + /// Controls the strength of the inpainting process on a per-pixel basis, either via a
+ /// second image (passed into this parameter) or via the alpha channel of the `image` parameter.
+ /// **Passing in a Mask**
+ /// The image passed to this parameter should be a black and white image that represents,
+ /// at any pixel, the strength of inpainting based on how dark or light the given pixel is.
+ /// Completely black pixels represent no inpainting strength while completely white pixels
+ /// represent maximum strength.
+ /// In the event the mask is a different size than the `image` parameter, it will be automatically resized.
+ /// **Alpha Channel Support**
+ /// If you don't provide an explicit mask, one will be derived from the alpha channel of the `image` parameter.
+ /// Transparent pixels will be inpainted while opaque pixels will be preserved.
+ /// In the event an `image` with an alpha channel is provided along with a `mask`, the `mask` will take precedence.
+ /// Example: ./some/image.png + /// + /// + /// Grows the edges of the mask outward in all directions by the specified number of pixels. The expanded area around the mask will be blurred, which can help smooth the transition between inpainted content and the original image.
+ /// Try this parameter if you notice seams or rough edges around the inpainted content.
+ /// > Note: Excessive growth may obscure fine details in the mask and/or merge nearby masked regions.
+ /// Default Value: 5 + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + public async global::System.Threading.Tasks.Task CreateStableImageEditEraseAsBytesAsync( + string contentType, + byte[] image, + string imagename, + global::StabilityAI.CreateStableImageEditEraseAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + byte[]? mask = default, + string? maskname = default, + double? growMask = default, + double? seed = default, + global::StabilityAI.CreateStableImageEditEraseRequestOutputFormat? outputFormat = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + var __request = new global::StabilityAI.CreateStableImageEditEraseRequest + { + Image = image, + Imagename = imagename, + Mask = mask, + Maskname = maskname, + GrowMask = growMask, + Seed = seed, + OutputFormat = outputFormat, + }; + + return await CreateStableImageEditEraseAsBytesAsync( + contentType: contentType, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: __request, + requestOptions: requestOptions, + cancellationToken: cancellationToken).ConfigureAwait(false); + } + + /// + /// Erase
+ /// The Erase service removes unwanted objects, such as blemishes on portraits or items on desks, using image masks.
+ /// The mask is provided in one of two ways:
+ /// 1. Explicitly passing in a separate image via the `mask` parameter
+ /// 2. Derived from the alpha channel of the `image` parameter.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// Optionally, the body of the request may also include:
+ /// - `mask`
+ /// - `seed`
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// The image you wish to erase from.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png + /// + /// + /// The image you wish to erase from.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png + /// + /// + /// Controls the strength of the inpainting process on a per-pixel basis, either via a
+ /// second image (passed into this parameter) or via the alpha channel of the `image` parameter.
+ /// **Passing in a Mask**
+ /// The image passed to this parameter should be a black and white image that represents,
+ /// at any pixel, the strength of inpainting based on how dark or light the given pixel is.
+ /// Completely black pixels represent no inpainting strength while completely white pixels
+ /// represent maximum strength.
+ /// In the event the mask is a different size than the `image` parameter, it will be automatically resized.
+ /// **Alpha Channel Support**
+ /// If you don't provide an explicit mask, one will be derived from the alpha channel of the `image` parameter.
+ /// Transparent pixels will be inpainted while opaque pixels will be preserved.
+ /// In the event an `image` with an alpha channel is provided along with a `mask`, the `mask` will take precedence.
+ /// Example: ./some/image.png + /// + /// + /// Controls the strength of the inpainting process on a per-pixel basis, either via a
+ /// second image (passed into this parameter) or via the alpha channel of the `image` parameter.
+ /// **Passing in a Mask**
+ /// The image passed to this parameter should be a black and white image that represents,
+ /// at any pixel, the strength of inpainting based on how dark or light the given pixel is.
+ /// Completely black pixels represent no inpainting strength while completely white pixels
+ /// represent maximum strength.
+ /// In the event the mask is a different size than the `image` parameter, it will be automatically resized.
+ /// **Alpha Channel Support**
+ /// If you don't provide an explicit mask, one will be derived from the alpha channel of the `image` parameter.
+ /// Transparent pixels will be inpainted while opaque pixels will be preserved.
+ /// In the event an `image` with an alpha channel is provided along with a `mask`, the `mask` will take precedence.
+ /// Example: ./some/image.png + /// + /// + /// Grows the edges of the mask outward in all directions by the specified number of pixels. The expanded area around the mask will be blurred, which can help smooth the transition between inpainted content and the original image.
+ /// Try this parameter if you notice seams or rough edges around the inpainted content.
+ /// > Note: Excessive growth may obscure fine details in the mask and/or merge nearby masked regions.
+ /// Default Value: 5 + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/erase",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./kangaroo-on-the-beach.png", "rb"),
+ /// "mask": open("./mask-of-kangaroo.png", "rb"),
+ /// },
+ /// data={
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./just-the-beach.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateStableImageEditEraseAsBytesAsync( + string contentType, + global::System.IO.Stream image, + string imagename, + global::StabilityAI.CreateStableImageEditEraseAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::System.IO.Stream? mask = default, + string? maskname = default, + double? growMask = default, + double? seed = default, + global::StabilityAI.CreateStableImageEditEraseRequestOutputFormat? outputFormat = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + + image = image ?? throw new global::System.ArgumentNullException(nameof(image)); + var request = new global::StabilityAI.CreateStableImageEditEraseRequest + { + Image = global::System.Array.Empty(), + Imagename = imagename, + Mask = global::System.Array.Empty(), + Maskname = maskname, + GrowMask = growMask, + Seed = seed, + OutputFormat = outputFormat, + }; + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageEditEraseAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageEditEraseAsBytesSecurityRequirements, + operationName: "CreateStableImageEditEraseAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/edit/erase", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/jpeg"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + var __contentImage = new global::System.Net.Http.StreamContent(image); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + if (mask != default) + { + + var __contentMask = new global::System.Net.Http.StreamContent(mask); + __contentMask.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Maskname is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Maskname) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentMask, + name: "\"mask\"", + fileName: request.Maskname != null ? $"\"{request.Maskname}\"" : string.Empty); + if (__contentMask.Headers.ContentDisposition != null) + { + __contentMask.Headers.ContentDisposition.FileNameStar = null; + } + + } + if (request.GrowMask != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.GrowMask, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"grow_mask\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageEditEraseAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditEraseAsBytes", + methodName: "CreateStableImageEditEraseAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/erase\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditEraseAsBytes", + methodName: "CreateStableImageEditEraseAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/erase\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditEraseAsBytes", + methodName: "CreateStableImageEditEraseAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/erase\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageEditEraseAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditEraseAsBytes", + methodName: "CreateStableImageEditEraseAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/erase\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditEraseAsBytes", + methodName: "CreateStableImageEditEraseAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/erase\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageEditEraseResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageEditEraseResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageEditEraseResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageEditEraseResponse5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageEditEraseResponse5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageEditEraseResponse5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageEditEraseResponse6? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageEditEraseResponse6.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageEditEraseResponse6.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageEditEraseResponse7? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageEditEraseResponse7.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageEditEraseResponse7.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessCreateStableImageEditEraseAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return __content; + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return __content; + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Erase
+ /// The Erase service removes unwanted objects, such as blemishes on portraits or items on desks, using image masks.
+ /// The mask is provided in one of two ways:
+ /// 1. Explicitly passing in a separate image via the `mask` parameter
+ /// 2. Derived from the alpha channel of the `image` parameter.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// Optionally, the body of the request may also include:
+ /// - `mask`
+ /// - `seed`
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// The image you wish to erase from.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png + /// + /// + /// The image you wish to erase from.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png + /// + /// + /// Controls the strength of the inpainting process on a per-pixel basis, either via a
+ /// second image (passed into this parameter) or via the alpha channel of the `image` parameter.
+ /// **Passing in a Mask**
+ /// The image passed to this parameter should be a black and white image that represents,
+ /// at any pixel, the strength of inpainting based on how dark or light the given pixel is.
+ /// Completely black pixels represent no inpainting strength while completely white pixels
+ /// represent maximum strength.
+ /// In the event the mask is a different size than the `image` parameter, it will be automatically resized.
+ /// **Alpha Channel Support**
+ /// If you don't provide an explicit mask, one will be derived from the alpha channel of the `image` parameter.
+ /// Transparent pixels will be inpainted while opaque pixels will be preserved.
+ /// In the event an `image` with an alpha channel is provided along with a `mask`, the `mask` will take precedence.
+ /// Example: ./some/image.png + /// + /// + /// Controls the strength of the inpainting process on a per-pixel basis, either via a
+ /// second image (passed into this parameter) or via the alpha channel of the `image` parameter.
+ /// **Passing in a Mask**
+ /// The image passed to this parameter should be a black and white image that represents,
+ /// at any pixel, the strength of inpainting based on how dark or light the given pixel is.
+ /// Completely black pixels represent no inpainting strength while completely white pixels
+ /// represent maximum strength.
+ /// In the event the mask is a different size than the `image` parameter, it will be automatically resized.
+ /// **Alpha Channel Support**
+ /// If you don't provide an explicit mask, one will be derived from the alpha channel of the `image` parameter.
+ /// Transparent pixels will be inpainted while opaque pixels will be preserved.
+ /// In the event an `image` with an alpha channel is provided along with a `mask`, the `mask` will take precedence.
+ /// Example: ./some/image.png + /// + /// + /// Grows the edges of the mask outward in all directions by the specified number of pixels. The expanded area around the mask will be blurred, which can help smooth the transition between inpainted content and the original image.
+ /// Try this parameter if you notice seams or rough edges around the inpainted content.
+ /// > Note: Excessive growth may obscure fine details in the mask and/or merge nearby masked regions.
+ /// Default Value: 5 + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/erase",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./kangaroo-on-the-beach.png", "rb"),
+ /// "mask": open("./mask-of-kangaroo.png", "rb"),
+ /// },
+ /// data={
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./just-the-beach.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateStableImageEditEraseAsBytesAsStreamAsync( + string contentType, + global::System.IO.Stream image, + string imagename, + global::StabilityAI.CreateStableImageEditEraseAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::System.IO.Stream? mask = default, + string? maskname = default, + double? growMask = default, + double? seed = default, + global::StabilityAI.CreateStableImageEditEraseRequestOutputFormat? outputFormat = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + + image = image ?? throw new global::System.ArgumentNullException(nameof(image)); + var request = new global::StabilityAI.CreateStableImageEditEraseRequest + { + Image = global::System.Array.Empty(), + Imagename = imagename, + Mask = global::System.Array.Empty(), + Maskname = maskname, + GrowMask = growMask, + Seed = seed, + OutputFormat = outputFormat, + }; + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageEditEraseAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageEditEraseAsBytesSecurityRequirements, + operationName: "CreateStableImageEditEraseAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/edit/erase", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/jpeg"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + var __contentImage = new global::System.Net.Http.StreamContent(image); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + if (mask != default) + { + + var __contentMask = new global::System.Net.Http.StreamContent(mask); + __contentMask.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Maskname is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Maskname) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentMask, + name: "\"mask\"", + fileName: request.Maskname != null ? $"\"{request.Maskname}\"" : string.Empty); + if (__contentMask.Headers.ContentDisposition != null) + { + __contentMask.Headers.ContentDisposition.FileNameStar = null; + } + + } + if (request.GrowMask != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.GrowMask, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"grow_mask\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageEditEraseAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditEraseAsBytes", + methodName: "CreateStableImageEditEraseAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/erase\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseHeadersRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditEraseAsBytes", + methodName: "CreateStableImageEditEraseAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/erase\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditEraseAsBytes", + methodName: "CreateStableImageEditEraseAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/erase\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + try + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageEditEraseAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditEraseAsBytes", + methodName: "CreateStableImageEditEraseAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/erase\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditEraseAsBytes", + methodName: "CreateStableImageEditEraseAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/erase\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageEditEraseResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageEditEraseResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageEditEraseResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageEditEraseResponse5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageEditEraseResponse5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageEditEraseResponse5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageEditEraseResponse6? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageEditEraseResponse6.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageEditEraseResponse6.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageEditEraseResponse7? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageEditEraseResponse7.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageEditEraseResponse7.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + try + { + __response.EnsureSuccessStatusCode(); + + var __content = await __response.Content.ReadAsStreamAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.ResponseStream(__response, __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + } + catch + { + __response.Dispose(); + throw; + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Erase
+ /// The Erase service removes unwanted objects, such as blemishes on portraits or items on desks, using image masks.
+ /// The mask is provided in one of two ways:
+ /// 1. Explicitly passing in a separate image via the `mask` parameter
+ /// 2. Derived from the alpha channel of the `image` parameter.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// Optionally, the body of the request may also include:
+ /// - `mask`
+ /// - `seed`
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// The image you wish to erase from.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png + /// + /// + /// The image you wish to erase from.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png + /// + /// + /// Controls the strength of the inpainting process on a per-pixel basis, either via a
+ /// second image (passed into this parameter) or via the alpha channel of the `image` parameter.
+ /// **Passing in a Mask**
+ /// The image passed to this parameter should be a black and white image that represents,
+ /// at any pixel, the strength of inpainting based on how dark or light the given pixel is.
+ /// Completely black pixels represent no inpainting strength while completely white pixels
+ /// represent maximum strength.
+ /// In the event the mask is a different size than the `image` parameter, it will be automatically resized.
+ /// **Alpha Channel Support**
+ /// If you don't provide an explicit mask, one will be derived from the alpha channel of the `image` parameter.
+ /// Transparent pixels will be inpainted while opaque pixels will be preserved.
+ /// In the event an `image` with an alpha channel is provided along with a `mask`, the `mask` will take precedence.
+ /// Example: ./some/image.png + /// + /// + /// Controls the strength of the inpainting process on a per-pixel basis, either via a
+ /// second image (passed into this parameter) or via the alpha channel of the `image` parameter.
+ /// **Passing in a Mask**
+ /// The image passed to this parameter should be a black and white image that represents,
+ /// at any pixel, the strength of inpainting based on how dark or light the given pixel is.
+ /// Completely black pixels represent no inpainting strength while completely white pixels
+ /// represent maximum strength.
+ /// In the event the mask is a different size than the `image` parameter, it will be automatically resized.
+ /// **Alpha Channel Support**
+ /// If you don't provide an explicit mask, one will be derived from the alpha channel of the `image` parameter.
+ /// Transparent pixels will be inpainted while opaque pixels will be preserved.
+ /// In the event an `image` with an alpha channel is provided along with a `mask`, the `mask` will take precedence.
+ /// Example: ./some/image.png + /// + /// + /// Grows the edges of the mask outward in all directions by the specified number of pixels. The expanded area around the mask will be blurred, which can help smooth the transition between inpainted content and the original image.
+ /// Try this parameter if you notice seams or rough edges around the inpainted content.
+ /// > Note: Excessive growth may obscure fine details in the mask and/or merge nearby masked regions.
+ /// Default Value: 5 + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/erase",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./kangaroo-on-the-beach.png", "rb"),
+ /// "mask": open("./mask-of-kangaroo.png", "rb"),
+ /// },
+ /// data={
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./just-the-beach.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task> CreateStableImageEditEraseAsBytesAsResponseAsync( + string contentType, + global::System.IO.Stream image, + string imagename, + global::StabilityAI.CreateStableImageEditEraseAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::System.IO.Stream? mask = default, + string? maskname = default, + double? growMask = default, + double? seed = default, + global::StabilityAI.CreateStableImageEditEraseRequestOutputFormat? outputFormat = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + + image = image ?? throw new global::System.ArgumentNullException(nameof(image)); + var request = new global::StabilityAI.CreateStableImageEditEraseRequest + { + Image = global::System.Array.Empty(), + Imagename = imagename, + Mask = global::System.Array.Empty(), + Maskname = maskname, + GrowMask = growMask, + Seed = seed, + OutputFormat = outputFormat, + }; + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageEditEraseAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageEditEraseAsBytesSecurityRequirements, + operationName: "CreateStableImageEditEraseAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/edit/erase", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/jpeg"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + var __contentImage = new global::System.Net.Http.StreamContent(image); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + if (mask != default) + { + + var __contentMask = new global::System.Net.Http.StreamContent(mask); + __contentMask.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Maskname is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Maskname) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentMask, + name: "\"mask\"", + fileName: request.Maskname != null ? $"\"{request.Maskname}\"" : string.Empty); + if (__contentMask.Headers.ContentDisposition != null) + { + __contentMask.Headers.ContentDisposition.FileNameStar = null; + } + + } + if (request.GrowMask != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.GrowMask, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"grow_mask\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageEditEraseAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditEraseAsBytes", + methodName: "CreateStableImageEditEraseAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/erase\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditEraseAsBytes", + methodName: "CreateStableImageEditEraseAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/erase\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditEraseAsBytes", + methodName: "CreateStableImageEditEraseAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/erase\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageEditEraseAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditEraseAsBytes", + methodName: "CreateStableImageEditEraseAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/erase\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditEraseAsBytes", + methodName: "CreateStableImageEditEraseAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/erase\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageEditEraseResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageEditEraseResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageEditEraseResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageEditEraseResponse5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageEditEraseResponse5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageEditEraseResponse5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageEditEraseResponse6? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageEditEraseResponse6.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageEditEraseResponse6.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageEditEraseResponse7? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageEditEraseResponse7.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageEditEraseResponse7.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessCreateStableImageEditEraseAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + } +} \ No newline at end of file diff --git a/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditInpaint.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditInpaint.g.cs index 86cee7c..d973fe9 100644 --- a/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditInpaint.g.cs +++ b/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditInpaint.g.cs @@ -293,6 +293,10 @@ partial void ProcessCreateStableImageEditInpaintResponseContent( __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || @@ -330,42 +334,6 @@ partial void ProcessCreateStableImageEditInpaintResponseContent( var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"accept\""); - - } - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } var __contentImage = new global::System.Net.Http.ByteArrayContent(request.Image ?? global::System.Array.Empty()); __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( request.Imagename is null @@ -1425,6 +1393,10 @@ request.Maskname is null __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || @@ -1462,42 +1434,6 @@ request.Maskname is null var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"accept\""); - - } - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } var __contentImage = new global::System.Net.Http.StreamContent(image); __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( request.Imagename is null @@ -2371,6 +2307,10 @@ request.Maskname is null __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || @@ -2408,42 +2348,6 @@ request.Maskname is null var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"accept\""); - - } - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } var __contentImage = new global::System.Net.Http.StreamContent(image); __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( request.Imagename is null diff --git a/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditInpaintAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditInpaintAsBytes.g.cs new file mode 100644 index 0000000..93da1bc --- /dev/null +++ b/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditInpaintAsBytes.g.cs @@ -0,0 +1,4621 @@ + +#nullable enable + +namespace StabilityAI +{ + public partial class EditClient + { + + + private static readonly global::StabilityAI.EndPointSecurityRequirement s_CreateStableImageEditInpaintAsBytesSecurityRequirement0 = + new global::StabilityAI.EndPointSecurityRequirement + { + Authorizations = new global::StabilityAI.EndPointAuthorizationRequirement[] + { new global::StabilityAI.EndPointAuthorizationRequirement + { + Type = "Http", + SchemeId = "HttpBearer", + Location = "Header", + Name = "Bearer", + FriendlyName = "Bearer", + }, + }, + }; + private static readonly global::StabilityAI.EndPointSecurityRequirement[] s_CreateStableImageEditInpaintAsBytesSecurityRequirements = + new global::StabilityAI.EndPointSecurityRequirement[] + { s_CreateStableImageEditInpaintAsBytesSecurityRequirement0, + }; + partial void PrepareCreateStableImageEditInpaintAsBytesArguments( + global::System.Net.Http.HttpClient httpClient, + ref string contentType, + ref global::StabilityAI.CreateStableImageEditInpaintAccept? accept, + ref string? stabilityClientId, + ref string? stabilityClientUserId, + ref string? stabilityClientVersion, + global::StabilityAI.CreateStableImageEditInpaintRequest request); + partial void PrepareCreateStableImageEditInpaintAsBytesRequest( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpRequestMessage httpRequestMessage, + string contentType, + global::StabilityAI.CreateStableImageEditInpaintAccept? accept, + string? stabilityClientId, + string? stabilityClientUserId, + string? stabilityClientVersion, + global::StabilityAI.CreateStableImageEditInpaintRequest request); + partial void ProcessCreateStableImageEditInpaintAsBytesResponse( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpResponseMessage httpResponseMessage); + + partial void ProcessCreateStableImageEditInpaintAsBytesResponseContent( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpResponseMessage httpResponseMessage, + ref byte[] content); + + /// + /// Inpaint
+ /// Intelligently modify images by filling in or replacing specified areas with new content based
+ /// on the content of a "mask" image.
+ /// The "mask" is provided in one of two ways:
+ /// 1. Explicitly passing in a separate image via the `mask` parameter
+ /// 2. Derived from the alpha channel of the `image` parameter.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// - `prompt`
+ /// Optionally, the body of the request may also include:
+ /// - `mask`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/inpaint",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./dog-wearing-vr-goggles.png", "rb"),
+ /// "mask": open("./mask.png", "rb"),
+ /// },
+ /// data={
+ /// "prompt": "dog wearing black glasses",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./dog-wearing-black-glasses.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateStableImageEditInpaintAsBytesAsync( + string contentType, + + global::StabilityAI.CreateStableImageEditInpaintRequest request, + global::StabilityAI.CreateStableImageEditInpaintAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + var __response = await CreateStableImageEditInpaintAsBytesAsResponseAsync( + contentType: contentType, + + request: request, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + requestOptions: requestOptions, + cancellationToken: cancellationToken + ).ConfigureAwait(false); + + return __response.Body; + } + /// + /// Inpaint
+ /// Intelligently modify images by filling in or replacing specified areas with new content based
+ /// on the content of a "mask" image.
+ /// The "mask" is provided in one of two ways:
+ /// 1. Explicitly passing in a separate image via the `mask` parameter
+ /// 2. Derived from the alpha channel of the `image` parameter.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// - `prompt`
+ /// Optionally, the body of the request may also include:
+ /// - `mask`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/inpaint",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./dog-wearing-vr-goggles.png", "rb"),
+ /// "mask": open("./mask.png", "rb"),
+ /// },
+ /// data={
+ /// "prompt": "dog wearing black glasses",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./dog-wearing-black-glasses.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateStableImageEditInpaintAsBytesAsStreamAsync( + string contentType, + + global::StabilityAI.CreateStableImageEditInpaintRequest request, + global::StabilityAI.CreateStableImageEditInpaintAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + request = request ?? throw new global::System.ArgumentNullException(nameof(request)); + + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageEditInpaintAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageEditInpaintAsBytesSecurityRequirements, + operationName: "CreateStableImageEditInpaintAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/edit/inpaint", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/jpeg"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + var __contentImage = new global::System.Net.Http.ByteArrayContent(request.Image ?? global::System.Array.Empty()); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + if (request.NegativePrompt != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty), + name: "\"negative_prompt\""); + + } + if (request.Mask != default) + { + + var __contentMask = new global::System.Net.Http.ByteArrayContent(request.Mask ?? global::System.Array.Empty()); + __contentMask.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Maskname is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Maskname) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentMask, + name: "\"mask\"", + fileName: request.Maskname != null ? $"\"{request.Maskname}\"" : string.Empty); + if (__contentMask.Headers.ContentDisposition != null) + { + __contentMask.Headers.ContentDisposition.FileNameStar = null; + } + + } + if (request.GrowMask != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.GrowMask, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"grow_mask\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + if (request.StylePreset != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.StylePreset).HasValue ? (request.StylePreset).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"style_preset\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageEditInpaintAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditInpaintAsBytes", + methodName: "CreateStableImageEditInpaintAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseHeadersRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditInpaintAsBytes", + methodName: "CreateStableImageEditInpaintAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditInpaintAsBytes", + methodName: "CreateStableImageEditInpaintAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + try + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageEditInpaintAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditInpaintAsBytes", + methodName: "CreateStableImageEditInpaintAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditInpaintAsBytes", + methodName: "CreateStableImageEditInpaintAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageEditInpaintResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageEditInpaintResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageEditInpaintResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageEditInpaintResponse5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageEditInpaintResponse5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageEditInpaintResponse5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateStableImageEditInpaintResponse6? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateStableImageEditInpaintResponse6.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateStableImageEditInpaintResponse6.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageEditInpaintResponse7? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageEditInpaintResponse7.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageEditInpaintResponse7.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageEditInpaintResponse8? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageEditInpaintResponse8.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageEditInpaintResponse8.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + try + { + __response.EnsureSuccessStatusCode(); + + var __content = await __response.Content.ReadAsStreamAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.ResponseStream(__response, __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + } + catch + { + __response.Dispose(); + throw; + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Inpaint
+ /// Intelligently modify images by filling in or replacing specified areas with new content based
+ /// on the content of a "mask" image.
+ /// The "mask" is provided in one of two ways:
+ /// 1. Explicitly passing in a separate image via the `mask` parameter
+ /// 2. Derived from the alpha channel of the `image` parameter.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// - `prompt`
+ /// Optionally, the body of the request may also include:
+ /// - `mask`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/inpaint",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./dog-wearing-vr-goggles.png", "rb"),
+ /// "mask": open("./mask.png", "rb"),
+ /// },
+ /// data={
+ /// "prompt": "dog wearing black glasses",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./dog-wearing-black-glasses.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task> CreateStableImageEditInpaintAsBytesAsResponseAsync( + string contentType, + + global::StabilityAI.CreateStableImageEditInpaintRequest request, + global::StabilityAI.CreateStableImageEditInpaintAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + request = request ?? throw new global::System.ArgumentNullException(nameof(request)); + + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageEditInpaintAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageEditInpaintAsBytesSecurityRequirements, + operationName: "CreateStableImageEditInpaintAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/edit/inpaint", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/jpeg"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + var __contentImage = new global::System.Net.Http.ByteArrayContent(request.Image ?? global::System.Array.Empty()); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + if (request.NegativePrompt != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty), + name: "\"negative_prompt\""); + + } + if (request.Mask != default) + { + + var __contentMask = new global::System.Net.Http.ByteArrayContent(request.Mask ?? global::System.Array.Empty()); + __contentMask.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Maskname is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Maskname) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentMask, + name: "\"mask\"", + fileName: request.Maskname != null ? $"\"{request.Maskname}\"" : string.Empty); + if (__contentMask.Headers.ContentDisposition != null) + { + __contentMask.Headers.ContentDisposition.FileNameStar = null; + } + + } + if (request.GrowMask != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.GrowMask, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"grow_mask\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + if (request.StylePreset != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.StylePreset).HasValue ? (request.StylePreset).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"style_preset\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageEditInpaintAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditInpaintAsBytes", + methodName: "CreateStableImageEditInpaintAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditInpaintAsBytes", + methodName: "CreateStableImageEditInpaintAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditInpaintAsBytes", + methodName: "CreateStableImageEditInpaintAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageEditInpaintAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditInpaintAsBytes", + methodName: "CreateStableImageEditInpaintAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditInpaintAsBytes", + methodName: "CreateStableImageEditInpaintAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageEditInpaintResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageEditInpaintResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageEditInpaintResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageEditInpaintResponse5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageEditInpaintResponse5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageEditInpaintResponse5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateStableImageEditInpaintResponse6? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateStableImageEditInpaintResponse6.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateStableImageEditInpaintResponse6.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageEditInpaintResponse7? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageEditInpaintResponse7.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageEditInpaintResponse7.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageEditInpaintResponse8? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageEditInpaintResponse8.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageEditInpaintResponse8.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessCreateStableImageEditInpaintAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Inpaint
+ /// Intelligently modify images by filling in or replacing specified areas with new content based
+ /// on the content of a "mask" image.
+ /// The "mask" is provided in one of two ways:
+ /// 1. Explicitly passing in a separate image via the `mask` parameter
+ /// 2. Derived from the alpha channel of the `image` parameter.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// - `prompt`
+ /// Optionally, the body of the request may also include:
+ /// - `mask`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// The image you wish to inpaint.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png + /// + /// + /// The image you wish to inpaint.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// Controls the strength of the inpainting process on a per-pixel basis, either via a
+ /// second image (passed into this parameter) or via the alpha channel of the `image` parameter.
+ /// **Passing in a Mask**
+ /// The image passed to this parameter should be a black and white image that represents,
+ /// at any pixel, the strength of inpainting based on how dark or light the given pixel is.
+ /// Completely black pixels represent no inpainting strength while completely white pixels
+ /// represent maximum strength.
+ /// In the event the mask is a different size than the `image` parameter, it will be automatically resized.
+ /// **Alpha Channel Support**
+ /// If you don't provide an explicit mask, one will be derived from the alpha channel of the `image` parameter.
+ /// Transparent pixels will be inpainted while opaque pixels will be preserved.
+ /// In the event an `image` with an alpha channel is provided along with a `mask`, the `mask` will take precedence.
+ /// Example: ./some/image.png + /// + /// + /// Controls the strength of the inpainting process on a per-pixel basis, either via a
+ /// second image (passed into this parameter) or via the alpha channel of the `image` parameter.
+ /// **Passing in a Mask**
+ /// The image passed to this parameter should be a black and white image that represents,
+ /// at any pixel, the strength of inpainting based on how dark or light the given pixel is.
+ /// Completely black pixels represent no inpainting strength while completely white pixels
+ /// represent maximum strength.
+ /// In the event the mask is a different size than the `image` parameter, it will be automatically resized.
+ /// **Alpha Channel Support**
+ /// If you don't provide an explicit mask, one will be derived from the alpha channel of the `image` parameter.
+ /// Transparent pixels will be inpainted while opaque pixels will be preserved.
+ /// In the event an `image` with an alpha channel is provided along with a `mask`, the `mask` will take precedence.
+ /// Example: ./some/image.png + /// + /// + /// Grows the edges of the mask outward in all directions by the specified number of pixels. The expanded area around the mask will be blurred, which can help smooth the transition between inpainted content and the original image.
+ /// Try this parameter if you notice seams or rough edges around the inpainted content.
+ /// > Note: Excessive growth may obscure fine details in the mask and/or merge nearby masked regions.
+ /// Default Value: 5 + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + public async global::System.Threading.Tasks.Task CreateStableImageEditInpaintAsBytesAsync( + string contentType, + byte[] image, + string imagename, + string prompt, + global::StabilityAI.CreateStableImageEditInpaintAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + string? negativePrompt = default, + byte[]? mask = default, + string? maskname = default, + double? growMask = default, + double? seed = default, + global::StabilityAI.CreateStableImageEditInpaintRequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageEditInpaintRequestStylePreset? stylePreset = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + var __request = new global::StabilityAI.CreateStableImageEditInpaintRequest + { + Image = image, + Imagename = imagename, + Prompt = prompt, + NegativePrompt = negativePrompt, + Mask = mask, + Maskname = maskname, + GrowMask = growMask, + Seed = seed, + OutputFormat = outputFormat, + StylePreset = stylePreset, + }; + + return await CreateStableImageEditInpaintAsBytesAsync( + contentType: contentType, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: __request, + requestOptions: requestOptions, + cancellationToken: cancellationToken).ConfigureAwait(false); + } + + /// + /// Inpaint
+ /// Intelligently modify images by filling in or replacing specified areas with new content based
+ /// on the content of a "mask" image.
+ /// The "mask" is provided in one of two ways:
+ /// 1. Explicitly passing in a separate image via the `mask` parameter
+ /// 2. Derived from the alpha channel of the `image` parameter.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// - `prompt`
+ /// Optionally, the body of the request may also include:
+ /// - `mask`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// The image you wish to inpaint.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png + /// + /// + /// The image you wish to inpaint.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// Controls the strength of the inpainting process on a per-pixel basis, either via a
+ /// second image (passed into this parameter) or via the alpha channel of the `image` parameter.
+ /// **Passing in a Mask**
+ /// The image passed to this parameter should be a black and white image that represents,
+ /// at any pixel, the strength of inpainting based on how dark or light the given pixel is.
+ /// Completely black pixels represent no inpainting strength while completely white pixels
+ /// represent maximum strength.
+ /// In the event the mask is a different size than the `image` parameter, it will be automatically resized.
+ /// **Alpha Channel Support**
+ /// If you don't provide an explicit mask, one will be derived from the alpha channel of the `image` parameter.
+ /// Transparent pixels will be inpainted while opaque pixels will be preserved.
+ /// In the event an `image` with an alpha channel is provided along with a `mask`, the `mask` will take precedence.
+ /// Example: ./some/image.png + /// + /// + /// Controls the strength of the inpainting process on a per-pixel basis, either via a
+ /// second image (passed into this parameter) or via the alpha channel of the `image` parameter.
+ /// **Passing in a Mask**
+ /// The image passed to this parameter should be a black and white image that represents,
+ /// at any pixel, the strength of inpainting based on how dark or light the given pixel is.
+ /// Completely black pixels represent no inpainting strength while completely white pixels
+ /// represent maximum strength.
+ /// In the event the mask is a different size than the `image` parameter, it will be automatically resized.
+ /// **Alpha Channel Support**
+ /// If you don't provide an explicit mask, one will be derived from the alpha channel of the `image` parameter.
+ /// Transparent pixels will be inpainted while opaque pixels will be preserved.
+ /// In the event an `image` with an alpha channel is provided along with a `mask`, the `mask` will take precedence.
+ /// Example: ./some/image.png + /// + /// + /// Grows the edges of the mask outward in all directions by the specified number of pixels. The expanded area around the mask will be blurred, which can help smooth the transition between inpainted content and the original image.
+ /// Try this parameter if you notice seams or rough edges around the inpainted content.
+ /// > Note: Excessive growth may obscure fine details in the mask and/or merge nearby masked regions.
+ /// Default Value: 5 + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/inpaint",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./dog-wearing-vr-goggles.png", "rb"),
+ /// "mask": open("./mask.png", "rb"),
+ /// },
+ /// data={
+ /// "prompt": "dog wearing black glasses",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./dog-wearing-black-glasses.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateStableImageEditInpaintAsBytesAsync( + string contentType, + global::System.IO.Stream image, + string imagename, + string prompt, + global::StabilityAI.CreateStableImageEditInpaintAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + string? negativePrompt = default, + global::System.IO.Stream? mask = default, + string? maskname = default, + double? growMask = default, + double? seed = default, + global::StabilityAI.CreateStableImageEditInpaintRequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageEditInpaintRequestStylePreset? stylePreset = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + + image = image ?? throw new global::System.ArgumentNullException(nameof(image)); + var request = new global::StabilityAI.CreateStableImageEditInpaintRequest + { + Image = global::System.Array.Empty(), + Imagename = imagename, + Prompt = prompt, + NegativePrompt = negativePrompt, + Mask = global::System.Array.Empty(), + Maskname = maskname, + GrowMask = growMask, + Seed = seed, + OutputFormat = outputFormat, + StylePreset = stylePreset, + }; + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageEditInpaintAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageEditInpaintAsBytesSecurityRequirements, + operationName: "CreateStableImageEditInpaintAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/edit/inpaint", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/jpeg"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + var __contentImage = new global::System.Net.Http.StreamContent(image); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + if (request.NegativePrompt != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty), + name: "\"negative_prompt\""); + + } + if (mask != default) + { + + var __contentMask = new global::System.Net.Http.StreamContent(mask); + __contentMask.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Maskname is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Maskname) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentMask, + name: "\"mask\"", + fileName: request.Maskname != null ? $"\"{request.Maskname}\"" : string.Empty); + if (__contentMask.Headers.ContentDisposition != null) + { + __contentMask.Headers.ContentDisposition.FileNameStar = null; + } + + } + if (request.GrowMask != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.GrowMask, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"grow_mask\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + if (request.StylePreset != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.StylePreset).HasValue ? (request.StylePreset).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"style_preset\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageEditInpaintAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditInpaintAsBytes", + methodName: "CreateStableImageEditInpaintAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditInpaintAsBytes", + methodName: "CreateStableImageEditInpaintAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditInpaintAsBytes", + methodName: "CreateStableImageEditInpaintAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageEditInpaintAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditInpaintAsBytes", + methodName: "CreateStableImageEditInpaintAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditInpaintAsBytes", + methodName: "CreateStableImageEditInpaintAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageEditInpaintResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageEditInpaintResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageEditInpaintResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageEditInpaintResponse5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageEditInpaintResponse5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageEditInpaintResponse5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateStableImageEditInpaintResponse6? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateStableImageEditInpaintResponse6.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateStableImageEditInpaintResponse6.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageEditInpaintResponse7? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageEditInpaintResponse7.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageEditInpaintResponse7.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageEditInpaintResponse8? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageEditInpaintResponse8.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageEditInpaintResponse8.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessCreateStableImageEditInpaintAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return __content; + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return __content; + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Inpaint
+ /// Intelligently modify images by filling in or replacing specified areas with new content based
+ /// on the content of a "mask" image.
+ /// The "mask" is provided in one of two ways:
+ /// 1. Explicitly passing in a separate image via the `mask` parameter
+ /// 2. Derived from the alpha channel of the `image` parameter.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// - `prompt`
+ /// Optionally, the body of the request may also include:
+ /// - `mask`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// The image you wish to inpaint.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png + /// + /// + /// The image you wish to inpaint.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// Controls the strength of the inpainting process on a per-pixel basis, either via a
+ /// second image (passed into this parameter) or via the alpha channel of the `image` parameter.
+ /// **Passing in a Mask**
+ /// The image passed to this parameter should be a black and white image that represents,
+ /// at any pixel, the strength of inpainting based on how dark or light the given pixel is.
+ /// Completely black pixels represent no inpainting strength while completely white pixels
+ /// represent maximum strength.
+ /// In the event the mask is a different size than the `image` parameter, it will be automatically resized.
+ /// **Alpha Channel Support**
+ /// If you don't provide an explicit mask, one will be derived from the alpha channel of the `image` parameter.
+ /// Transparent pixels will be inpainted while opaque pixels will be preserved.
+ /// In the event an `image` with an alpha channel is provided along with a `mask`, the `mask` will take precedence.
+ /// Example: ./some/image.png + /// + /// + /// Controls the strength of the inpainting process on a per-pixel basis, either via a
+ /// second image (passed into this parameter) or via the alpha channel of the `image` parameter.
+ /// **Passing in a Mask**
+ /// The image passed to this parameter should be a black and white image that represents,
+ /// at any pixel, the strength of inpainting based on how dark or light the given pixel is.
+ /// Completely black pixels represent no inpainting strength while completely white pixels
+ /// represent maximum strength.
+ /// In the event the mask is a different size than the `image` parameter, it will be automatically resized.
+ /// **Alpha Channel Support**
+ /// If you don't provide an explicit mask, one will be derived from the alpha channel of the `image` parameter.
+ /// Transparent pixels will be inpainted while opaque pixels will be preserved.
+ /// In the event an `image` with an alpha channel is provided along with a `mask`, the `mask` will take precedence.
+ /// Example: ./some/image.png + /// + /// + /// Grows the edges of the mask outward in all directions by the specified number of pixels. The expanded area around the mask will be blurred, which can help smooth the transition between inpainted content and the original image.
+ /// Try this parameter if you notice seams or rough edges around the inpainted content.
+ /// > Note: Excessive growth may obscure fine details in the mask and/or merge nearby masked regions.
+ /// Default Value: 5 + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/inpaint",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./dog-wearing-vr-goggles.png", "rb"),
+ /// "mask": open("./mask.png", "rb"),
+ /// },
+ /// data={
+ /// "prompt": "dog wearing black glasses",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./dog-wearing-black-glasses.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateStableImageEditInpaintAsBytesAsStreamAsync( + string contentType, + global::System.IO.Stream image, + string imagename, + string prompt, + global::StabilityAI.CreateStableImageEditInpaintAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + string? negativePrompt = default, + global::System.IO.Stream? mask = default, + string? maskname = default, + double? growMask = default, + double? seed = default, + global::StabilityAI.CreateStableImageEditInpaintRequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageEditInpaintRequestStylePreset? stylePreset = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + + image = image ?? throw new global::System.ArgumentNullException(nameof(image)); + var request = new global::StabilityAI.CreateStableImageEditInpaintRequest + { + Image = global::System.Array.Empty(), + Imagename = imagename, + Prompt = prompt, + NegativePrompt = negativePrompt, + Mask = global::System.Array.Empty(), + Maskname = maskname, + GrowMask = growMask, + Seed = seed, + OutputFormat = outputFormat, + StylePreset = stylePreset, + }; + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageEditInpaintAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageEditInpaintAsBytesSecurityRequirements, + operationName: "CreateStableImageEditInpaintAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/edit/inpaint", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/jpeg"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + var __contentImage = new global::System.Net.Http.StreamContent(image); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + if (request.NegativePrompt != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty), + name: "\"negative_prompt\""); + + } + if (mask != default) + { + + var __contentMask = new global::System.Net.Http.StreamContent(mask); + __contentMask.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Maskname is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Maskname) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentMask, + name: "\"mask\"", + fileName: request.Maskname != null ? $"\"{request.Maskname}\"" : string.Empty); + if (__contentMask.Headers.ContentDisposition != null) + { + __contentMask.Headers.ContentDisposition.FileNameStar = null; + } + + } + if (request.GrowMask != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.GrowMask, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"grow_mask\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + if (request.StylePreset != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.StylePreset).HasValue ? (request.StylePreset).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"style_preset\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageEditInpaintAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditInpaintAsBytes", + methodName: "CreateStableImageEditInpaintAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseHeadersRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditInpaintAsBytes", + methodName: "CreateStableImageEditInpaintAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditInpaintAsBytes", + methodName: "CreateStableImageEditInpaintAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + try + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageEditInpaintAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditInpaintAsBytes", + methodName: "CreateStableImageEditInpaintAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditInpaintAsBytes", + methodName: "CreateStableImageEditInpaintAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageEditInpaintResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageEditInpaintResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageEditInpaintResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageEditInpaintResponse5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageEditInpaintResponse5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageEditInpaintResponse5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateStableImageEditInpaintResponse6? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateStableImageEditInpaintResponse6.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateStableImageEditInpaintResponse6.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageEditInpaintResponse7? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageEditInpaintResponse7.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageEditInpaintResponse7.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageEditInpaintResponse8? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageEditInpaintResponse8.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageEditInpaintResponse8.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + try + { + __response.EnsureSuccessStatusCode(); + + var __content = await __response.Content.ReadAsStreamAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.ResponseStream(__response, __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + } + catch + { + __response.Dispose(); + throw; + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Inpaint
+ /// Intelligently modify images by filling in or replacing specified areas with new content based
+ /// on the content of a "mask" image.
+ /// The "mask" is provided in one of two ways:
+ /// 1. Explicitly passing in a separate image via the `mask` parameter
+ /// 2. Derived from the alpha channel of the `image` parameter.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// - `prompt`
+ /// Optionally, the body of the request may also include:
+ /// - `mask`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// The image you wish to inpaint.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png + /// + /// + /// The image you wish to inpaint.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// Controls the strength of the inpainting process on a per-pixel basis, either via a
+ /// second image (passed into this parameter) or via the alpha channel of the `image` parameter.
+ /// **Passing in a Mask**
+ /// The image passed to this parameter should be a black and white image that represents,
+ /// at any pixel, the strength of inpainting based on how dark or light the given pixel is.
+ /// Completely black pixels represent no inpainting strength while completely white pixels
+ /// represent maximum strength.
+ /// In the event the mask is a different size than the `image` parameter, it will be automatically resized.
+ /// **Alpha Channel Support**
+ /// If you don't provide an explicit mask, one will be derived from the alpha channel of the `image` parameter.
+ /// Transparent pixels will be inpainted while opaque pixels will be preserved.
+ /// In the event an `image` with an alpha channel is provided along with a `mask`, the `mask` will take precedence.
+ /// Example: ./some/image.png + /// + /// + /// Controls the strength of the inpainting process on a per-pixel basis, either via a
+ /// second image (passed into this parameter) or via the alpha channel of the `image` parameter.
+ /// **Passing in a Mask**
+ /// The image passed to this parameter should be a black and white image that represents,
+ /// at any pixel, the strength of inpainting based on how dark or light the given pixel is.
+ /// Completely black pixels represent no inpainting strength while completely white pixels
+ /// represent maximum strength.
+ /// In the event the mask is a different size than the `image` parameter, it will be automatically resized.
+ /// **Alpha Channel Support**
+ /// If you don't provide an explicit mask, one will be derived from the alpha channel of the `image` parameter.
+ /// Transparent pixels will be inpainted while opaque pixels will be preserved.
+ /// In the event an `image` with an alpha channel is provided along with a `mask`, the `mask` will take precedence.
+ /// Example: ./some/image.png + /// + /// + /// Grows the edges of the mask outward in all directions by the specified number of pixels. The expanded area around the mask will be blurred, which can help smooth the transition between inpainted content and the original image.
+ /// Try this parameter if you notice seams or rough edges around the inpainted content.
+ /// > Note: Excessive growth may obscure fine details in the mask and/or merge nearby masked regions.
+ /// Default Value: 5 + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/inpaint",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./dog-wearing-vr-goggles.png", "rb"),
+ /// "mask": open("./mask.png", "rb"),
+ /// },
+ /// data={
+ /// "prompt": "dog wearing black glasses",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./dog-wearing-black-glasses.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task> CreateStableImageEditInpaintAsBytesAsResponseAsync( + string contentType, + global::System.IO.Stream image, + string imagename, + string prompt, + global::StabilityAI.CreateStableImageEditInpaintAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + string? negativePrompt = default, + global::System.IO.Stream? mask = default, + string? maskname = default, + double? growMask = default, + double? seed = default, + global::StabilityAI.CreateStableImageEditInpaintRequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageEditInpaintRequestStylePreset? stylePreset = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + + image = image ?? throw new global::System.ArgumentNullException(nameof(image)); + var request = new global::StabilityAI.CreateStableImageEditInpaintRequest + { + Image = global::System.Array.Empty(), + Imagename = imagename, + Prompt = prompt, + NegativePrompt = negativePrompt, + Mask = global::System.Array.Empty(), + Maskname = maskname, + GrowMask = growMask, + Seed = seed, + OutputFormat = outputFormat, + StylePreset = stylePreset, + }; + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageEditInpaintAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageEditInpaintAsBytesSecurityRequirements, + operationName: "CreateStableImageEditInpaintAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/edit/inpaint", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/jpeg"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + var __contentImage = new global::System.Net.Http.StreamContent(image); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + if (request.NegativePrompt != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty), + name: "\"negative_prompt\""); + + } + if (mask != default) + { + + var __contentMask = new global::System.Net.Http.StreamContent(mask); + __contentMask.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Maskname is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Maskname) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentMask, + name: "\"mask\"", + fileName: request.Maskname != null ? $"\"{request.Maskname}\"" : string.Empty); + if (__contentMask.Headers.ContentDisposition != null) + { + __contentMask.Headers.ContentDisposition.FileNameStar = null; + } + + } + if (request.GrowMask != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.GrowMask, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"grow_mask\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + if (request.StylePreset != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.StylePreset).HasValue ? (request.StylePreset).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"style_preset\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageEditInpaintAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditInpaintAsBytes", + methodName: "CreateStableImageEditInpaintAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditInpaintAsBytes", + methodName: "CreateStableImageEditInpaintAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditInpaintAsBytes", + methodName: "CreateStableImageEditInpaintAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageEditInpaintAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditInpaintAsBytes", + methodName: "CreateStableImageEditInpaintAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditInpaintAsBytes", + methodName: "CreateStableImageEditInpaintAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageEditInpaintResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageEditInpaintResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageEditInpaintResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageEditInpaintResponse5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageEditInpaintResponse5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageEditInpaintResponse5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateStableImageEditInpaintResponse6? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateStableImageEditInpaintResponse6.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateStableImageEditInpaintResponse6.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageEditInpaintResponse7? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageEditInpaintResponse7.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageEditInpaintResponse7.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageEditInpaintResponse8? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageEditInpaintResponse8.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageEditInpaintResponse8.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessCreateStableImageEditInpaintAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + } +} \ No newline at end of file diff --git a/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditOutpaint.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditOutpaint.g.cs index 0fa6fde..6cbb81e 100644 --- a/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditOutpaint.g.cs +++ b/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditOutpaint.g.cs @@ -297,6 +297,10 @@ partial void ProcessCreateStableImageEditOutpaintResponseContent( __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || @@ -334,42 +338,6 @@ partial void ProcessCreateStableImageEditOutpaintResponseContent( var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"accept\""); - - } - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } var __contentImage = new global::System.Net.Http.ByteArrayContent(request.Image ?? global::System.Array.Empty()); __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( request.Imagename is null @@ -1381,6 +1349,10 @@ request.Imagename is null __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || @@ -1418,42 +1390,6 @@ request.Imagename is null var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"accept\""); - - } - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } var __contentImage = new global::System.Net.Http.StreamContent(image); __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( request.Imagename is null @@ -2296,6 +2232,10 @@ request.Imagename is null __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || @@ -2333,42 +2273,6 @@ request.Imagename is null var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"accept\""); - - } - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } var __contentImage = new global::System.Net.Http.StreamContent(image); __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( request.Imagename is null diff --git a/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditOutpaintAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditOutpaintAsBytes.g.cs new file mode 100644 index 0000000..860427e --- /dev/null +++ b/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditOutpaintAsBytes.g.cs @@ -0,0 +1,4489 @@ + +#nullable enable + +namespace StabilityAI +{ + public partial class EditClient + { + + + private static readonly global::StabilityAI.EndPointSecurityRequirement s_CreateStableImageEditOutpaintAsBytesSecurityRequirement0 = + new global::StabilityAI.EndPointSecurityRequirement + { + Authorizations = new global::StabilityAI.EndPointAuthorizationRequirement[] + { new global::StabilityAI.EndPointAuthorizationRequirement + { + Type = "Http", + SchemeId = "HttpBearer", + Location = "Header", + Name = "Bearer", + FriendlyName = "Bearer", + }, + }, + }; + private static readonly global::StabilityAI.EndPointSecurityRequirement[] s_CreateStableImageEditOutpaintAsBytesSecurityRequirements = + new global::StabilityAI.EndPointSecurityRequirement[] + { s_CreateStableImageEditOutpaintAsBytesSecurityRequirement0, + }; + partial void PrepareCreateStableImageEditOutpaintAsBytesArguments( + global::System.Net.Http.HttpClient httpClient, + ref string contentType, + ref global::StabilityAI.CreateStableImageEditOutpaintAccept? accept, + ref string? stabilityClientId, + ref string? stabilityClientUserId, + ref string? stabilityClientVersion, + global::StabilityAI.CreateStableImageEditOutpaintRequest request); + partial void PrepareCreateStableImageEditOutpaintAsBytesRequest( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpRequestMessage httpRequestMessage, + string contentType, + global::StabilityAI.CreateStableImageEditOutpaintAccept? accept, + string? stabilityClientId, + string? stabilityClientUserId, + string? stabilityClientVersion, + global::StabilityAI.CreateStableImageEditOutpaintRequest request); + partial void ProcessCreateStableImageEditOutpaintAsBytesResponse( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpResponseMessage httpResponseMessage); + + partial void ProcessCreateStableImageEditOutpaintAsBytesResponseContent( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpResponseMessage httpResponseMessage, + ref byte[] content); + + /// + /// Outpaint
+ /// The Outpaint service inserts additional content in an image to fill in the space in any direction.
+ /// Compared to other automated or manual attempts to expand the content in an image, the Outpaint service
+ /// should minimize artifacts and signs that the original image has been edited.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=bZ2yK7VQSgLw)
+ /// ### How to use
+ /// Please invoke this endpoint with a POST request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// Along with _at least one_ outpaint direction:
+ /// - `left`
+ /// - `right`
+ /// - `up`
+ /// - `down`
+ /// > **Note:** for best quality use outpaint direction values smaller or equal to your source image dimensions.
+ /// Each of these parameters should be set to a number between 0 and 2000, representing the number of pixels to outpaint in that direction.
+ /// Optionally, the body of the request may also include:
+ /// - `prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `creativity`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// Flat rate of 4 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/outpaint",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./husky-in-a-field.png", "rb")
+ /// },
+ /// data={
+ /// "left": 200,
+ /// "down": 200,
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./husky-in-a-huge-field.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateStableImageEditOutpaintAsBytesAsync( + string contentType, + + global::StabilityAI.CreateStableImageEditOutpaintRequest request, + global::StabilityAI.CreateStableImageEditOutpaintAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + var __response = await CreateStableImageEditOutpaintAsBytesAsResponseAsync( + contentType: contentType, + + request: request, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + requestOptions: requestOptions, + cancellationToken: cancellationToken + ).ConfigureAwait(false); + + return __response.Body; + } + /// + /// Outpaint
+ /// The Outpaint service inserts additional content in an image to fill in the space in any direction.
+ /// Compared to other automated or manual attempts to expand the content in an image, the Outpaint service
+ /// should minimize artifacts and signs that the original image has been edited.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=bZ2yK7VQSgLw)
+ /// ### How to use
+ /// Please invoke this endpoint with a POST request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// Along with _at least one_ outpaint direction:
+ /// - `left`
+ /// - `right`
+ /// - `up`
+ /// - `down`
+ /// > **Note:** for best quality use outpaint direction values smaller or equal to your source image dimensions.
+ /// Each of these parameters should be set to a number between 0 and 2000, representing the number of pixels to outpaint in that direction.
+ /// Optionally, the body of the request may also include:
+ /// - `prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `creativity`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// Flat rate of 4 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/outpaint",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./husky-in-a-field.png", "rb")
+ /// },
+ /// data={
+ /// "left": 200,
+ /// "down": 200,
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./husky-in-a-huge-field.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateStableImageEditOutpaintAsBytesAsStreamAsync( + string contentType, + + global::StabilityAI.CreateStableImageEditOutpaintRequest request, + global::StabilityAI.CreateStableImageEditOutpaintAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + request = request ?? throw new global::System.ArgumentNullException(nameof(request)); + + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageEditOutpaintAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageEditOutpaintAsBytesSecurityRequirements, + operationName: "CreateStableImageEditOutpaintAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/edit/outpaint", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/png"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + var __contentImage = new global::System.Net.Http.ByteArrayContent(request.Image ?? global::System.Array.Empty()); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.Left != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Left, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"left\""); + + } + if (request.Right != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Right, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"right\""); + + } + if (request.Up != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Up, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"up\""); + + } + if (request.Down != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Down, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"down\""); + + } + if (request.Creativity != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Creativity.ToString() ?? string.Empty), + name: "\"creativity\""); + + } + if (request.Prompt != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + if (request.StylePreset != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.StylePreset).HasValue ? (request.StylePreset).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"style_preset\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageEditOutpaintAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditOutpaintAsBytes", + methodName: "CreateStableImageEditOutpaintAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/outpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseHeadersRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditOutpaintAsBytes", + methodName: "CreateStableImageEditOutpaintAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/outpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditOutpaintAsBytes", + methodName: "CreateStableImageEditOutpaintAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/outpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + try + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageEditOutpaintAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditOutpaintAsBytes", + methodName: "CreateStableImageEditOutpaintAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/outpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditOutpaintAsBytes", + methodName: "CreateStableImageEditOutpaintAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/outpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageEditOutpaintResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageEditOutpaintResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageEditOutpaintResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageEditOutpaintResponse5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageEditOutpaintResponse5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageEditOutpaintResponse5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateStableImageEditOutpaintResponse6? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateStableImageEditOutpaintResponse6.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateStableImageEditOutpaintResponse6.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageEditOutpaintResponse7? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageEditOutpaintResponse7.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageEditOutpaintResponse7.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageEditOutpaintResponse8? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageEditOutpaintResponse8.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageEditOutpaintResponse8.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + try + { + __response.EnsureSuccessStatusCode(); + + var __content = await __response.Content.ReadAsStreamAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.ResponseStream(__response, __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + } + catch + { + __response.Dispose(); + throw; + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Outpaint
+ /// The Outpaint service inserts additional content in an image to fill in the space in any direction.
+ /// Compared to other automated or manual attempts to expand the content in an image, the Outpaint service
+ /// should minimize artifacts and signs that the original image has been edited.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=bZ2yK7VQSgLw)
+ /// ### How to use
+ /// Please invoke this endpoint with a POST request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// Along with _at least one_ outpaint direction:
+ /// - `left`
+ /// - `right`
+ /// - `up`
+ /// - `down`
+ /// > **Note:** for best quality use outpaint direction values smaller or equal to your source image dimensions.
+ /// Each of these parameters should be set to a number between 0 and 2000, representing the number of pixels to outpaint in that direction.
+ /// Optionally, the body of the request may also include:
+ /// - `prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `creativity`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// Flat rate of 4 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/outpaint",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./husky-in-a-field.png", "rb")
+ /// },
+ /// data={
+ /// "left": 200,
+ /// "down": 200,
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./husky-in-a-huge-field.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task> CreateStableImageEditOutpaintAsBytesAsResponseAsync( + string contentType, + + global::StabilityAI.CreateStableImageEditOutpaintRequest request, + global::StabilityAI.CreateStableImageEditOutpaintAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + request = request ?? throw new global::System.ArgumentNullException(nameof(request)); + + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageEditOutpaintAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageEditOutpaintAsBytesSecurityRequirements, + operationName: "CreateStableImageEditOutpaintAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/edit/outpaint", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/png"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + var __contentImage = new global::System.Net.Http.ByteArrayContent(request.Image ?? global::System.Array.Empty()); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.Left != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Left, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"left\""); + + } + if (request.Right != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Right, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"right\""); + + } + if (request.Up != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Up, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"up\""); + + } + if (request.Down != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Down, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"down\""); + + } + if (request.Creativity != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Creativity.ToString() ?? string.Empty), + name: "\"creativity\""); + + } + if (request.Prompt != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + if (request.StylePreset != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.StylePreset).HasValue ? (request.StylePreset).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"style_preset\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageEditOutpaintAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditOutpaintAsBytes", + methodName: "CreateStableImageEditOutpaintAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/outpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditOutpaintAsBytes", + methodName: "CreateStableImageEditOutpaintAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/outpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditOutpaintAsBytes", + methodName: "CreateStableImageEditOutpaintAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/outpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageEditOutpaintAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditOutpaintAsBytes", + methodName: "CreateStableImageEditOutpaintAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/outpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditOutpaintAsBytes", + methodName: "CreateStableImageEditOutpaintAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/outpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageEditOutpaintResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageEditOutpaintResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageEditOutpaintResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageEditOutpaintResponse5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageEditOutpaintResponse5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageEditOutpaintResponse5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateStableImageEditOutpaintResponse6? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateStableImageEditOutpaintResponse6.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateStableImageEditOutpaintResponse6.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageEditOutpaintResponse7? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageEditOutpaintResponse7.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageEditOutpaintResponse7.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageEditOutpaintResponse8? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageEditOutpaintResponse8.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageEditOutpaintResponse8.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessCreateStableImageEditOutpaintAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Outpaint
+ /// The Outpaint service inserts additional content in an image to fill in the space in any direction.
+ /// Compared to other automated or manual attempts to expand the content in an image, the Outpaint service
+ /// should minimize artifacts and signs that the original image has been edited.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=bZ2yK7VQSgLw)
+ /// ### How to use
+ /// Please invoke this endpoint with a POST request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// Along with _at least one_ outpaint direction:
+ /// - `left`
+ /// - `right`
+ /// - `up`
+ /// - `down`
+ /// > **Note:** for best quality use outpaint direction values smaller or equal to your source image dimensions.
+ /// Each of these parameters should be set to a number between 0 and 2000, representing the number of pixels to outpaint in that direction.
+ /// Optionally, the body of the request may also include:
+ /// - `prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `creativity`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// Flat rate of 4 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// The image you wish to outpaint.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// The image you wish to outpaint.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// The number of pixels to outpaint on the left side of the image. At least one outpainting direction must be supplied with a non-zero value.
+ /// Default Value: 0 + /// + /// + /// The number of pixels to outpaint on the right side of the image. At least one outpainting direction must be supplied with a non-zero value.
+ /// Default Value: 0 + /// + /// + /// The number of pixels to outpaint on the top of the image. At least one outpainting direction must be supplied with a non-zero value.
+ /// Default Value: 0 + /// + /// + /// The number of pixels to outpaint on the bottom of the image. At least one outpainting direction must be supplied with a non-zero value.
+ /// Default Value: 0 + /// + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + public async global::System.Threading.Tasks.Task CreateStableImageEditOutpaintAsBytesAsync( + string contentType, + byte[] image, + string imagename, + global::StabilityAI.CreateStableImageEditOutpaintAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + int? left = default, + int? right = default, + int? up = default, + int? down = default, + global::StabilityAI.AllOf? creativity = default, + string? prompt = default, + double? seed = default, + global::StabilityAI.CreateStableImageEditOutpaintRequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageEditOutpaintRequestStylePreset? stylePreset = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + var __request = new global::StabilityAI.CreateStableImageEditOutpaintRequest + { + Image = image, + Imagename = imagename, + Left = left, + Right = right, + Up = up, + Down = down, + Creativity = creativity, + Prompt = prompt, + Seed = seed, + OutputFormat = outputFormat, + StylePreset = stylePreset, + }; + + return await CreateStableImageEditOutpaintAsBytesAsync( + contentType: contentType, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: __request, + requestOptions: requestOptions, + cancellationToken: cancellationToken).ConfigureAwait(false); + } + + /// + /// Outpaint
+ /// The Outpaint service inserts additional content in an image to fill in the space in any direction.
+ /// Compared to other automated or manual attempts to expand the content in an image, the Outpaint service
+ /// should minimize artifacts and signs that the original image has been edited.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=bZ2yK7VQSgLw)
+ /// ### How to use
+ /// Please invoke this endpoint with a POST request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// Along with _at least one_ outpaint direction:
+ /// - `left`
+ /// - `right`
+ /// - `up`
+ /// - `down`
+ /// > **Note:** for best quality use outpaint direction values smaller or equal to your source image dimensions.
+ /// Each of these parameters should be set to a number between 0 and 2000, representing the number of pixels to outpaint in that direction.
+ /// Optionally, the body of the request may also include:
+ /// - `prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `creativity`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// Flat rate of 4 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// The image you wish to outpaint.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// The image you wish to outpaint.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// The number of pixels to outpaint on the left side of the image. At least one outpainting direction must be supplied with a non-zero value.
+ /// Default Value: 0 + /// + /// + /// The number of pixels to outpaint on the right side of the image. At least one outpainting direction must be supplied with a non-zero value.
+ /// Default Value: 0 + /// + /// + /// The number of pixels to outpaint on the top of the image. At least one outpainting direction must be supplied with a non-zero value.
+ /// Default Value: 0 + /// + /// + /// The number of pixels to outpaint on the bottom of the image. At least one outpainting direction must be supplied with a non-zero value.
+ /// Default Value: 0 + /// + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/outpaint",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./husky-in-a-field.png", "rb")
+ /// },
+ /// data={
+ /// "left": 200,
+ /// "down": 200,
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./husky-in-a-huge-field.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateStableImageEditOutpaintAsBytesAsync( + string contentType, + global::System.IO.Stream image, + string imagename, + global::StabilityAI.CreateStableImageEditOutpaintAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + int? left = default, + int? right = default, + int? up = default, + int? down = default, + global::StabilityAI.AllOf? creativity = default, + string? prompt = default, + double? seed = default, + global::StabilityAI.CreateStableImageEditOutpaintRequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageEditOutpaintRequestStylePreset? stylePreset = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + + image = image ?? throw new global::System.ArgumentNullException(nameof(image)); + var request = new global::StabilityAI.CreateStableImageEditOutpaintRequest + { + Image = global::System.Array.Empty(), + Imagename = imagename, + Left = left, + Right = right, + Up = up, + Down = down, + Creativity = creativity, + Prompt = prompt, + Seed = seed, + OutputFormat = outputFormat, + StylePreset = stylePreset, + }; + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageEditOutpaintAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageEditOutpaintAsBytesSecurityRequirements, + operationName: "CreateStableImageEditOutpaintAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/edit/outpaint", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/png"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + var __contentImage = new global::System.Net.Http.StreamContent(image); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.Left != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Left, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"left\""); + + } + if (request.Right != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Right, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"right\""); + + } + if (request.Up != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Up, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"up\""); + + } + if (request.Down != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Down, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"down\""); + + } + if (request.Creativity != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Creativity.ToString() ?? string.Empty), + name: "\"creativity\""); + + } + if (request.Prompt != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + if (request.StylePreset != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.StylePreset).HasValue ? (request.StylePreset).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"style_preset\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageEditOutpaintAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditOutpaintAsBytes", + methodName: "CreateStableImageEditOutpaintAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/outpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditOutpaintAsBytes", + methodName: "CreateStableImageEditOutpaintAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/outpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditOutpaintAsBytes", + methodName: "CreateStableImageEditOutpaintAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/outpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageEditOutpaintAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditOutpaintAsBytes", + methodName: "CreateStableImageEditOutpaintAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/outpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditOutpaintAsBytes", + methodName: "CreateStableImageEditOutpaintAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/outpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageEditOutpaintResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageEditOutpaintResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageEditOutpaintResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageEditOutpaintResponse5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageEditOutpaintResponse5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageEditOutpaintResponse5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateStableImageEditOutpaintResponse6? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateStableImageEditOutpaintResponse6.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateStableImageEditOutpaintResponse6.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageEditOutpaintResponse7? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageEditOutpaintResponse7.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageEditOutpaintResponse7.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageEditOutpaintResponse8? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageEditOutpaintResponse8.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageEditOutpaintResponse8.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessCreateStableImageEditOutpaintAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return __content; + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return __content; + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Outpaint
+ /// The Outpaint service inserts additional content in an image to fill in the space in any direction.
+ /// Compared to other automated or manual attempts to expand the content in an image, the Outpaint service
+ /// should minimize artifacts and signs that the original image has been edited.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=bZ2yK7VQSgLw)
+ /// ### How to use
+ /// Please invoke this endpoint with a POST request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// Along with _at least one_ outpaint direction:
+ /// - `left`
+ /// - `right`
+ /// - `up`
+ /// - `down`
+ /// > **Note:** for best quality use outpaint direction values smaller or equal to your source image dimensions.
+ /// Each of these parameters should be set to a number between 0 and 2000, representing the number of pixels to outpaint in that direction.
+ /// Optionally, the body of the request may also include:
+ /// - `prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `creativity`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// Flat rate of 4 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// The image you wish to outpaint.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// The image you wish to outpaint.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// The number of pixels to outpaint on the left side of the image. At least one outpainting direction must be supplied with a non-zero value.
+ /// Default Value: 0 + /// + /// + /// The number of pixels to outpaint on the right side of the image. At least one outpainting direction must be supplied with a non-zero value.
+ /// Default Value: 0 + /// + /// + /// The number of pixels to outpaint on the top of the image. At least one outpainting direction must be supplied with a non-zero value.
+ /// Default Value: 0 + /// + /// + /// The number of pixels to outpaint on the bottom of the image. At least one outpainting direction must be supplied with a non-zero value.
+ /// Default Value: 0 + /// + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/outpaint",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./husky-in-a-field.png", "rb")
+ /// },
+ /// data={
+ /// "left": 200,
+ /// "down": 200,
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./husky-in-a-huge-field.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateStableImageEditOutpaintAsBytesAsStreamAsync( + string contentType, + global::System.IO.Stream image, + string imagename, + global::StabilityAI.CreateStableImageEditOutpaintAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + int? left = default, + int? right = default, + int? up = default, + int? down = default, + global::StabilityAI.AllOf? creativity = default, + string? prompt = default, + double? seed = default, + global::StabilityAI.CreateStableImageEditOutpaintRequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageEditOutpaintRequestStylePreset? stylePreset = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + + image = image ?? throw new global::System.ArgumentNullException(nameof(image)); + var request = new global::StabilityAI.CreateStableImageEditOutpaintRequest + { + Image = global::System.Array.Empty(), + Imagename = imagename, + Left = left, + Right = right, + Up = up, + Down = down, + Creativity = creativity, + Prompt = prompt, + Seed = seed, + OutputFormat = outputFormat, + StylePreset = stylePreset, + }; + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageEditOutpaintAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageEditOutpaintAsBytesSecurityRequirements, + operationName: "CreateStableImageEditOutpaintAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/edit/outpaint", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/png"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + var __contentImage = new global::System.Net.Http.StreamContent(image); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.Left != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Left, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"left\""); + + } + if (request.Right != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Right, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"right\""); + + } + if (request.Up != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Up, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"up\""); + + } + if (request.Down != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Down, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"down\""); + + } + if (request.Creativity != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Creativity.ToString() ?? string.Empty), + name: "\"creativity\""); + + } + if (request.Prompt != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + if (request.StylePreset != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.StylePreset).HasValue ? (request.StylePreset).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"style_preset\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageEditOutpaintAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditOutpaintAsBytes", + methodName: "CreateStableImageEditOutpaintAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/outpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseHeadersRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditOutpaintAsBytes", + methodName: "CreateStableImageEditOutpaintAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/outpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditOutpaintAsBytes", + methodName: "CreateStableImageEditOutpaintAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/outpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + try + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageEditOutpaintAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditOutpaintAsBytes", + methodName: "CreateStableImageEditOutpaintAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/outpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditOutpaintAsBytes", + methodName: "CreateStableImageEditOutpaintAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/outpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageEditOutpaintResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageEditOutpaintResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageEditOutpaintResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageEditOutpaintResponse5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageEditOutpaintResponse5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageEditOutpaintResponse5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateStableImageEditOutpaintResponse6? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateStableImageEditOutpaintResponse6.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateStableImageEditOutpaintResponse6.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageEditOutpaintResponse7? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageEditOutpaintResponse7.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageEditOutpaintResponse7.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageEditOutpaintResponse8? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageEditOutpaintResponse8.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageEditOutpaintResponse8.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + try + { + __response.EnsureSuccessStatusCode(); + + var __content = await __response.Content.ReadAsStreamAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.ResponseStream(__response, __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + } + catch + { + __response.Dispose(); + throw; + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Outpaint
+ /// The Outpaint service inserts additional content in an image to fill in the space in any direction.
+ /// Compared to other automated or manual attempts to expand the content in an image, the Outpaint service
+ /// should minimize artifacts and signs that the original image has been edited.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=bZ2yK7VQSgLw)
+ /// ### How to use
+ /// Please invoke this endpoint with a POST request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// Along with _at least one_ outpaint direction:
+ /// - `left`
+ /// - `right`
+ /// - `up`
+ /// - `down`
+ /// > **Note:** for best quality use outpaint direction values smaller or equal to your source image dimensions.
+ /// Each of these parameters should be set to a number between 0 and 2000, representing the number of pixels to outpaint in that direction.
+ /// Optionally, the body of the request may also include:
+ /// - `prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `creativity`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// Flat rate of 4 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// The image you wish to outpaint.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// The image you wish to outpaint.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// The number of pixels to outpaint on the left side of the image. At least one outpainting direction must be supplied with a non-zero value.
+ /// Default Value: 0 + /// + /// + /// The number of pixels to outpaint on the right side of the image. At least one outpainting direction must be supplied with a non-zero value.
+ /// Default Value: 0 + /// + /// + /// The number of pixels to outpaint on the top of the image. At least one outpainting direction must be supplied with a non-zero value.
+ /// Default Value: 0 + /// + /// + /// The number of pixels to outpaint on the bottom of the image. At least one outpainting direction must be supplied with a non-zero value.
+ /// Default Value: 0 + /// + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/outpaint",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./husky-in-a-field.png", "rb")
+ /// },
+ /// data={
+ /// "left": 200,
+ /// "down": 200,
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./husky-in-a-huge-field.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task> CreateStableImageEditOutpaintAsBytesAsResponseAsync( + string contentType, + global::System.IO.Stream image, + string imagename, + global::StabilityAI.CreateStableImageEditOutpaintAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + int? left = default, + int? right = default, + int? up = default, + int? down = default, + global::StabilityAI.AllOf? creativity = default, + string? prompt = default, + double? seed = default, + global::StabilityAI.CreateStableImageEditOutpaintRequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageEditOutpaintRequestStylePreset? stylePreset = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + + image = image ?? throw new global::System.ArgumentNullException(nameof(image)); + var request = new global::StabilityAI.CreateStableImageEditOutpaintRequest + { + Image = global::System.Array.Empty(), + Imagename = imagename, + Left = left, + Right = right, + Up = up, + Down = down, + Creativity = creativity, + Prompt = prompt, + Seed = seed, + OutputFormat = outputFormat, + StylePreset = stylePreset, + }; + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageEditOutpaintAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageEditOutpaintAsBytesSecurityRequirements, + operationName: "CreateStableImageEditOutpaintAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/edit/outpaint", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/png"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + var __contentImage = new global::System.Net.Http.StreamContent(image); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.Left != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Left, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"left\""); + + } + if (request.Right != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Right, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"right\""); + + } + if (request.Up != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Up, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"up\""); + + } + if (request.Down != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Down, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"down\""); + + } + if (request.Creativity != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Creativity.ToString() ?? string.Empty), + name: "\"creativity\""); + + } + if (request.Prompt != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + if (request.StylePreset != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.StylePreset).HasValue ? (request.StylePreset).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"style_preset\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageEditOutpaintAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditOutpaintAsBytes", + methodName: "CreateStableImageEditOutpaintAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/outpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditOutpaintAsBytes", + methodName: "CreateStableImageEditOutpaintAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/outpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditOutpaintAsBytes", + methodName: "CreateStableImageEditOutpaintAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/outpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageEditOutpaintAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditOutpaintAsBytes", + methodName: "CreateStableImageEditOutpaintAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/outpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditOutpaintAsBytes", + methodName: "CreateStableImageEditOutpaintAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/outpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageEditOutpaintResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageEditOutpaintResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageEditOutpaintResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageEditOutpaintResponse5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageEditOutpaintResponse5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageEditOutpaintResponse5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateStableImageEditOutpaintResponse6? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateStableImageEditOutpaintResponse6.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateStableImageEditOutpaintResponse6.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageEditOutpaintResponse7? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageEditOutpaintResponse7.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageEditOutpaintResponse7.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageEditOutpaintResponse8? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageEditOutpaintResponse8.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageEditOutpaintResponse8.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessCreateStableImageEditOutpaintAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + } +} \ No newline at end of file diff --git a/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditRemoveBackground.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditRemoveBackground.g.cs index a8f3408..94245f6 100644 --- a/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditRemoveBackground.g.cs +++ b/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditRemoveBackground.g.cs @@ -271,6 +271,10 @@ partial void ProcessCreateStableImageEditRemoveBackgroundResponseContent( __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || @@ -308,42 +312,6 @@ partial void ProcessCreateStableImageEditRemoveBackgroundResponseContent( var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"accept\""); - - } - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } var __contentImage = new global::System.Net.Http.ByteArrayContent(request.Image ?? global::System.Array.Empty()); __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( request.Imagename is null @@ -1130,6 +1098,10 @@ request.Imagename is null __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || @@ -1167,42 +1139,6 @@ request.Imagename is null var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"accept\""); - - } - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } var __contentImage = new global::System.Net.Http.StreamContent(image); __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( request.Imagename is null @@ -1881,6 +1817,10 @@ request.Imagename is null __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || @@ -1918,42 +1858,6 @@ request.Imagename is null var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"accept\""); - - } - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } var __contentImage = new global::System.Net.Http.StreamContent(image); __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( request.Imagename is null diff --git a/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditRemoveBackgroundAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditRemoveBackgroundAsBytes.g.cs new file mode 100644 index 0000000..e83a18a --- /dev/null +++ b/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditRemoveBackgroundAsBytes.g.cs @@ -0,0 +1,3695 @@ + +#nullable enable + +namespace StabilityAI +{ + public partial class EditClient + { + + + private static readonly global::StabilityAI.EndPointSecurityRequirement s_CreateStableImageEditRemoveBackgroundAsBytesSecurityRequirement0 = + new global::StabilityAI.EndPointSecurityRequirement + { + Authorizations = new global::StabilityAI.EndPointAuthorizationRequirement[] + { new global::StabilityAI.EndPointAuthorizationRequirement + { + Type = "Http", + SchemeId = "HttpBearer", + Location = "Header", + Name = "Bearer", + FriendlyName = "Bearer", + }, + }, + }; + private static readonly global::StabilityAI.EndPointSecurityRequirement[] s_CreateStableImageEditRemoveBackgroundAsBytesSecurityRequirements = + new global::StabilityAI.EndPointSecurityRequirement[] + { s_CreateStableImageEditRemoveBackgroundAsBytesSecurityRequirement0, + }; + partial void PrepareCreateStableImageEditRemoveBackgroundAsBytesArguments( + global::System.Net.Http.HttpClient httpClient, + ref string contentType, + ref global::StabilityAI.CreateStableImageEditRemoveBackgroundAccept? accept, + ref string? stabilityClientId, + ref string? stabilityClientUserId, + ref string? stabilityClientVersion, + global::StabilityAI.CreateStableImageEditRemoveBackgroundRequest request); + partial void PrepareCreateStableImageEditRemoveBackgroundAsBytesRequest( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpRequestMessage httpRequestMessage, + string contentType, + global::StabilityAI.CreateStableImageEditRemoveBackgroundAccept? accept, + string? stabilityClientId, + string? stabilityClientUserId, + string? stabilityClientVersion, + global::StabilityAI.CreateStableImageEditRemoveBackgroundRequest request); + partial void ProcessCreateStableImageEditRemoveBackgroundAsBytesResponse( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpResponseMessage httpResponseMessage); + + partial void ProcessCreateStableImageEditRemoveBackgroundAsBytesResponseContent( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpResponseMessage httpResponseMessage, + ref byte[] content); + + /// + /// Remove Background
+ /// The Remove Background service accurately segments the foreground from an image and implements
+ /// and removes the background.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=VHofb3LAVmqi)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ ///
+ /// The body of the request must include:
+ /// - `image`
+ /// Optionally, the body of the request may also include:
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/remove-background",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./husky-in-a-field.png", "rb")
+ /// },
+ /// data={
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./husky.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateStableImageEditRemoveBackgroundAsBytesAsync( + string contentType, + + global::StabilityAI.CreateStableImageEditRemoveBackgroundRequest request, + global::StabilityAI.CreateStableImageEditRemoveBackgroundAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + var __response = await CreateStableImageEditRemoveBackgroundAsBytesAsResponseAsync( + contentType: contentType, + + request: request, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + requestOptions: requestOptions, + cancellationToken: cancellationToken + ).ConfigureAwait(false); + + return __response.Body; + } + /// + /// Remove Background
+ /// The Remove Background service accurately segments the foreground from an image and implements
+ /// and removes the background.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=VHofb3LAVmqi)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ ///
+ /// The body of the request must include:
+ /// - `image`
+ /// Optionally, the body of the request may also include:
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/remove-background",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./husky-in-a-field.png", "rb")
+ /// },
+ /// data={
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./husky.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateStableImageEditRemoveBackgroundAsBytesAsStreamAsync( + string contentType, + + global::StabilityAI.CreateStableImageEditRemoveBackgroundRequest request, + global::StabilityAI.CreateStableImageEditRemoveBackgroundAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + request = request ?? throw new global::System.ArgumentNullException(nameof(request)); + + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageEditRemoveBackgroundAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageEditRemoveBackgroundAsBytesSecurityRequirements, + operationName: "CreateStableImageEditRemoveBackgroundAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/edit/remove-background", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/png"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + var __contentImage = new global::System.Net.Http.ByteArrayContent(request.Image ?? global::System.Array.Empty()); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageEditRemoveBackgroundAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditRemoveBackgroundAsBytes", + methodName: "CreateStableImageEditRemoveBackgroundAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/remove-background\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseHeadersRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditRemoveBackgroundAsBytes", + methodName: "CreateStableImageEditRemoveBackgroundAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/remove-background\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditRemoveBackgroundAsBytes", + methodName: "CreateStableImageEditRemoveBackgroundAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/remove-background\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + try + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageEditRemoveBackgroundAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditRemoveBackgroundAsBytes", + methodName: "CreateStableImageEditRemoveBackgroundAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/remove-background\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditRemoveBackgroundAsBytes", + methodName: "CreateStableImageEditRemoveBackgroundAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/remove-background\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse3? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse3.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse3.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse4? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse4.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse4.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse5? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse5.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse5.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse6? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse6.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse6.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + try + { + __response.EnsureSuccessStatusCode(); + + var __content = await __response.Content.ReadAsStreamAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.ResponseStream(__response, __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + } + catch + { + __response.Dispose(); + throw; + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Remove Background
+ /// The Remove Background service accurately segments the foreground from an image and implements
+ /// and removes the background.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=VHofb3LAVmqi)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ ///
+ /// The body of the request must include:
+ /// - `image`
+ /// Optionally, the body of the request may also include:
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/remove-background",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./husky-in-a-field.png", "rb")
+ /// },
+ /// data={
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./husky.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task> CreateStableImageEditRemoveBackgroundAsBytesAsResponseAsync( + string contentType, + + global::StabilityAI.CreateStableImageEditRemoveBackgroundRequest request, + global::StabilityAI.CreateStableImageEditRemoveBackgroundAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + request = request ?? throw new global::System.ArgumentNullException(nameof(request)); + + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageEditRemoveBackgroundAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageEditRemoveBackgroundAsBytesSecurityRequirements, + operationName: "CreateStableImageEditRemoveBackgroundAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/edit/remove-background", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/png"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + var __contentImage = new global::System.Net.Http.ByteArrayContent(request.Image ?? global::System.Array.Empty()); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageEditRemoveBackgroundAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditRemoveBackgroundAsBytes", + methodName: "CreateStableImageEditRemoveBackgroundAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/remove-background\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditRemoveBackgroundAsBytes", + methodName: "CreateStableImageEditRemoveBackgroundAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/remove-background\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditRemoveBackgroundAsBytes", + methodName: "CreateStableImageEditRemoveBackgroundAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/remove-background\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageEditRemoveBackgroundAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditRemoveBackgroundAsBytes", + methodName: "CreateStableImageEditRemoveBackgroundAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/remove-background\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditRemoveBackgroundAsBytes", + methodName: "CreateStableImageEditRemoveBackgroundAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/remove-background\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse3? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse3.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse3.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse4? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse4.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse4.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse5? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse5.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse5.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse6? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse6.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse6.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessCreateStableImageEditRemoveBackgroundAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Remove Background
+ /// The Remove Background service accurately segments the foreground from an image and implements
+ /// and removes the background.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=VHofb3LAVmqi)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ ///
+ /// The body of the request must include:
+ /// - `image`
+ /// Optionally, the body of the request may also include:
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// The image whose background you wish to remove.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 4,194,304 pixels
+ /// Example: ./some/image.png + /// + /// + /// The image whose background you wish to remove.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 4,194,304 pixels
+ /// Example: ./some/image.png + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + public async global::System.Threading.Tasks.Task CreateStableImageEditRemoveBackgroundAsBytesAsync( + string contentType, + byte[] image, + string imagename, + global::StabilityAI.CreateStableImageEditRemoveBackgroundAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.CreateStableImageEditRemoveBackgroundRequestOutputFormat? outputFormat = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + var __request = new global::StabilityAI.CreateStableImageEditRemoveBackgroundRequest + { + Image = image, + Imagename = imagename, + OutputFormat = outputFormat, + }; + + return await CreateStableImageEditRemoveBackgroundAsBytesAsync( + contentType: contentType, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: __request, + requestOptions: requestOptions, + cancellationToken: cancellationToken).ConfigureAwait(false); + } + + /// + /// Remove Background
+ /// The Remove Background service accurately segments the foreground from an image and implements
+ /// and removes the background.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=VHofb3LAVmqi)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ ///
+ /// The body of the request must include:
+ /// - `image`
+ /// Optionally, the body of the request may also include:
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// The image whose background you wish to remove.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 4,194,304 pixels
+ /// Example: ./some/image.png + /// + /// + /// The image whose background you wish to remove.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 4,194,304 pixels
+ /// Example: ./some/image.png + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/remove-background",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./husky-in-a-field.png", "rb")
+ /// },
+ /// data={
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./husky.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateStableImageEditRemoveBackgroundAsBytesAsync( + string contentType, + global::System.IO.Stream image, + string imagename, + global::StabilityAI.CreateStableImageEditRemoveBackgroundAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.CreateStableImageEditRemoveBackgroundRequestOutputFormat? outputFormat = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + + image = image ?? throw new global::System.ArgumentNullException(nameof(image)); + var request = new global::StabilityAI.CreateStableImageEditRemoveBackgroundRequest + { + Image = global::System.Array.Empty(), + Imagename = imagename, + OutputFormat = outputFormat, + }; + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageEditRemoveBackgroundAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageEditRemoveBackgroundAsBytesSecurityRequirements, + operationName: "CreateStableImageEditRemoveBackgroundAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/edit/remove-background", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/png"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + var __contentImage = new global::System.Net.Http.StreamContent(image); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageEditRemoveBackgroundAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditRemoveBackgroundAsBytes", + methodName: "CreateStableImageEditRemoveBackgroundAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/remove-background\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditRemoveBackgroundAsBytes", + methodName: "CreateStableImageEditRemoveBackgroundAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/remove-background\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditRemoveBackgroundAsBytes", + methodName: "CreateStableImageEditRemoveBackgroundAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/remove-background\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageEditRemoveBackgroundAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditRemoveBackgroundAsBytes", + methodName: "CreateStableImageEditRemoveBackgroundAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/remove-background\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditRemoveBackgroundAsBytes", + methodName: "CreateStableImageEditRemoveBackgroundAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/remove-background\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse3? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse3.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse3.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse4? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse4.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse4.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse5? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse5.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse5.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse6? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse6.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse6.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessCreateStableImageEditRemoveBackgroundAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return __content; + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return __content; + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Remove Background
+ /// The Remove Background service accurately segments the foreground from an image and implements
+ /// and removes the background.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=VHofb3LAVmqi)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ ///
+ /// The body of the request must include:
+ /// - `image`
+ /// Optionally, the body of the request may also include:
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// The image whose background you wish to remove.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 4,194,304 pixels
+ /// Example: ./some/image.png + /// + /// + /// The image whose background you wish to remove.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 4,194,304 pixels
+ /// Example: ./some/image.png + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/remove-background",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./husky-in-a-field.png", "rb")
+ /// },
+ /// data={
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./husky.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateStableImageEditRemoveBackgroundAsBytesAsStreamAsync( + string contentType, + global::System.IO.Stream image, + string imagename, + global::StabilityAI.CreateStableImageEditRemoveBackgroundAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.CreateStableImageEditRemoveBackgroundRequestOutputFormat? outputFormat = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + + image = image ?? throw new global::System.ArgumentNullException(nameof(image)); + var request = new global::StabilityAI.CreateStableImageEditRemoveBackgroundRequest + { + Image = global::System.Array.Empty(), + Imagename = imagename, + OutputFormat = outputFormat, + }; + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageEditRemoveBackgroundAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageEditRemoveBackgroundAsBytesSecurityRequirements, + operationName: "CreateStableImageEditRemoveBackgroundAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/edit/remove-background", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/png"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + var __contentImage = new global::System.Net.Http.StreamContent(image); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageEditRemoveBackgroundAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditRemoveBackgroundAsBytes", + methodName: "CreateStableImageEditRemoveBackgroundAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/remove-background\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseHeadersRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditRemoveBackgroundAsBytes", + methodName: "CreateStableImageEditRemoveBackgroundAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/remove-background\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditRemoveBackgroundAsBytes", + methodName: "CreateStableImageEditRemoveBackgroundAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/remove-background\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + try + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageEditRemoveBackgroundAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditRemoveBackgroundAsBytes", + methodName: "CreateStableImageEditRemoveBackgroundAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/remove-background\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditRemoveBackgroundAsBytes", + methodName: "CreateStableImageEditRemoveBackgroundAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/remove-background\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse3? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse3.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse3.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse4? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse4.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse4.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse5? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse5.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse5.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse6? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse6.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse6.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + try + { + __response.EnsureSuccessStatusCode(); + + var __content = await __response.Content.ReadAsStreamAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.ResponseStream(__response, __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + } + catch + { + __response.Dispose(); + throw; + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Remove Background
+ /// The Remove Background service accurately segments the foreground from an image and implements
+ /// and removes the background.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=VHofb3LAVmqi)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ ///
+ /// The body of the request must include:
+ /// - `image`
+ /// Optionally, the body of the request may also include:
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// The image whose background you wish to remove.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 4,194,304 pixels
+ /// Example: ./some/image.png + /// + /// + /// The image whose background you wish to remove.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 4,194,304 pixels
+ /// Example: ./some/image.png + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/remove-background",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./husky-in-a-field.png", "rb")
+ /// },
+ /// data={
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./husky.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task> CreateStableImageEditRemoveBackgroundAsBytesAsResponseAsync( + string contentType, + global::System.IO.Stream image, + string imagename, + global::StabilityAI.CreateStableImageEditRemoveBackgroundAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.CreateStableImageEditRemoveBackgroundRequestOutputFormat? outputFormat = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + + image = image ?? throw new global::System.ArgumentNullException(nameof(image)); + var request = new global::StabilityAI.CreateStableImageEditRemoveBackgroundRequest + { + Image = global::System.Array.Empty(), + Imagename = imagename, + OutputFormat = outputFormat, + }; + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageEditRemoveBackgroundAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageEditRemoveBackgroundAsBytesSecurityRequirements, + operationName: "CreateStableImageEditRemoveBackgroundAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/edit/remove-background", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/png"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + var __contentImage = new global::System.Net.Http.StreamContent(image); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageEditRemoveBackgroundAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditRemoveBackgroundAsBytes", + methodName: "CreateStableImageEditRemoveBackgroundAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/remove-background\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditRemoveBackgroundAsBytes", + methodName: "CreateStableImageEditRemoveBackgroundAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/remove-background\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditRemoveBackgroundAsBytes", + methodName: "CreateStableImageEditRemoveBackgroundAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/remove-background\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageEditRemoveBackgroundAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditRemoveBackgroundAsBytes", + methodName: "CreateStableImageEditRemoveBackgroundAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/remove-background\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditRemoveBackgroundAsBytes", + methodName: "CreateStableImageEditRemoveBackgroundAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/remove-background\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse3? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse3.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse3.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse4? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse4.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse4.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse5? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse5.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse5.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse6? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse6.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageEditRemoveBackgroundResponse6.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessCreateStableImageEditRemoveBackgroundAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + } +} \ No newline at end of file diff --git a/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditReplaceBackgroundAndRelight.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditReplaceBackgroundAndRelight.g.cs index ea999b2..ebaced8 100644 --- a/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditReplaceBackgroundAndRelight.g.cs +++ b/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditReplaceBackgroundAndRelight.g.cs @@ -320,34 +320,6 @@ partial void ProcessCreateStableImageEditReplaceBackgroundAndRelightResponseCont var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } var __contentSubjectImage = new global::System.Net.Http.ByteArrayContent(request.SubjectImage ?? global::System.Array.Empty()); __contentSubjectImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( request.SubjectImagename is null @@ -1622,34 +1594,6 @@ request.LightReferencename is null var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } var __contentSubjectImage = new global::System.Net.Http.StreamContent(subjectImage); __contentSubjectImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( request.SubjectImagename is null @@ -2683,34 +2627,6 @@ request.LightReferencename is null var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } var __contentSubjectImage = new global::System.Net.Http.StreamContent(subjectImage); __contentSubjectImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( request.SubjectImagename is null diff --git a/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditSearchAndRecolor.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditSearchAndRecolor.g.cs index e67dafe..a30d8cf 100644 --- a/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditSearchAndRecolor.g.cs +++ b/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditSearchAndRecolor.g.cs @@ -291,6 +291,10 @@ partial void ProcessCreateStableImageEditSearchAndRecolorResponseContent( __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || @@ -328,42 +332,6 @@ partial void ProcessCreateStableImageEditSearchAndRecolorResponseContent( var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"accept\""); - - } - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } var __contentImage = new global::System.Net.Http.ByteArrayContent(request.Image ?? global::System.Array.Empty()); __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( request.Imagename is null @@ -1331,6 +1299,10 @@ request.Imagename is null __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || @@ -1368,42 +1340,6 @@ request.Imagename is null var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"accept\""); - - } - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } var __contentImage = new global::System.Net.Http.StreamContent(image); __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( request.Imagename is null @@ -2212,6 +2148,10 @@ request.Imagename is null __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || @@ -2249,42 +2189,6 @@ request.Imagename is null var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"accept\""); - - } - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } var __contentImage = new global::System.Net.Http.StreamContent(image); __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( request.Imagename is null diff --git a/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditSearchAndRecolorAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditSearchAndRecolorAsBytes.g.cs new file mode 100644 index 0000000..4e573a3 --- /dev/null +++ b/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditSearchAndRecolorAsBytes.g.cs @@ -0,0 +1,4320 @@ + +#nullable enable + +namespace StabilityAI +{ + public partial class EditClient + { + + + private static readonly global::StabilityAI.EndPointSecurityRequirement s_CreateStableImageEditSearchAndRecolorAsBytesSecurityRequirement0 = + new global::StabilityAI.EndPointSecurityRequirement + { + Authorizations = new global::StabilityAI.EndPointAuthorizationRequirement[] + { new global::StabilityAI.EndPointAuthorizationRequirement + { + Type = "Http", + SchemeId = "HttpBearer", + Location = "Header", + Name = "Bearer", + FriendlyName = "Bearer", + }, + }, + }; + private static readonly global::StabilityAI.EndPointSecurityRequirement[] s_CreateStableImageEditSearchAndRecolorAsBytesSecurityRequirements = + new global::StabilityAI.EndPointSecurityRequirement[] + { s_CreateStableImageEditSearchAndRecolorAsBytesSecurityRequirement0, + }; + partial void PrepareCreateStableImageEditSearchAndRecolorAsBytesArguments( + global::System.Net.Http.HttpClient httpClient, + ref string contentType, + ref global::StabilityAI.CreateStableImageEditSearchAndRecolorAccept? accept, + ref string? stabilityClientId, + ref string? stabilityClientUserId, + ref string? stabilityClientVersion, + global::StabilityAI.CreateStableImageEditSearchAndRecolorRequest request); + partial void PrepareCreateStableImageEditSearchAndRecolorAsBytesRequest( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpRequestMessage httpRequestMessage, + string contentType, + global::StabilityAI.CreateStableImageEditSearchAndRecolorAccept? accept, + string? stabilityClientId, + string? stabilityClientUserId, + string? stabilityClientVersion, + global::StabilityAI.CreateStableImageEditSearchAndRecolorRequest request); + partial void ProcessCreateStableImageEditSearchAndRecolorAsBytesResponse( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpResponseMessage httpResponseMessage); + + partial void ProcessCreateStableImageEditSearchAndRecolorAsBytesResponseContent( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpResponseMessage httpResponseMessage, + ref byte[] content); + + /// + /// Search and Recolor
+ /// The Search and Recolor service provides the ability to change the color of a specific object in an image using a prompt.
+ /// This service is a specific version of inpainting that does not require a mask. The Search and Recolor
+ /// service will automatically segment the object and recolor it using the colors requested in the prompt.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=mtgSh4Stj3l)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// - `select_prompt`
+ /// The body may optionally include:
+ /// - `grow_mask`
+ /// - `seed`
+ /// - `negative_prompt`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will match the resolution of the input image.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/search-and-recolor",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./red-car.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a yellow car",
+ /// "select_prompt": "car",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./yellow-car.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateStableImageEditSearchAndRecolorAsBytesAsync( + string contentType, + + global::StabilityAI.CreateStableImageEditSearchAndRecolorRequest request, + global::StabilityAI.CreateStableImageEditSearchAndRecolorAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + var __response = await CreateStableImageEditSearchAndRecolorAsBytesAsResponseAsync( + contentType: contentType, + + request: request, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + requestOptions: requestOptions, + cancellationToken: cancellationToken + ).ConfigureAwait(false); + + return __response.Body; + } + /// + /// Search and Recolor
+ /// The Search and Recolor service provides the ability to change the color of a specific object in an image using a prompt.
+ /// This service is a specific version of inpainting that does not require a mask. The Search and Recolor
+ /// service will automatically segment the object and recolor it using the colors requested in the prompt.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=mtgSh4Stj3l)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// - `select_prompt`
+ /// The body may optionally include:
+ /// - `grow_mask`
+ /// - `seed`
+ /// - `negative_prompt`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will match the resolution of the input image.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/search-and-recolor",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./red-car.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a yellow car",
+ /// "select_prompt": "car",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./yellow-car.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateStableImageEditSearchAndRecolorAsBytesAsStreamAsync( + string contentType, + + global::StabilityAI.CreateStableImageEditSearchAndRecolorRequest request, + global::StabilityAI.CreateStableImageEditSearchAndRecolorAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + request = request ?? throw new global::System.ArgumentNullException(nameof(request)); + + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageEditSearchAndRecolorAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageEditSearchAndRecolorAsBytesSecurityRequirements, + operationName: "CreateStableImageEditSearchAndRecolorAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/edit/search-and-recolor", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/jpeg"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + var __contentImage = new global::System.Net.Http.ByteArrayContent(request.Image ?? global::System.Array.Empty()); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.SelectPrompt ?? string.Empty), + name: "\"select_prompt\""); + + if (request.NegativePrompt != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty), + name: "\"negative_prompt\""); + + } + if (request.GrowMask != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.GrowMask, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"grow_mask\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + if (request.StylePreset != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.StylePreset).HasValue ? (request.StylePreset).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"style_preset\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageEditSearchAndRecolorAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditSearchAndRecolorAsBytes", + methodName: "CreateStableImageEditSearchAndRecolorAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/search-and-recolor\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseHeadersRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditSearchAndRecolorAsBytes", + methodName: "CreateStableImageEditSearchAndRecolorAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/search-and-recolor\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditSearchAndRecolorAsBytes", + methodName: "CreateStableImageEditSearchAndRecolorAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/search-and-recolor\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + try + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageEditSearchAndRecolorAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditSearchAndRecolorAsBytes", + methodName: "CreateStableImageEditSearchAndRecolorAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/search-and-recolor\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditSearchAndRecolorAsBytes", + methodName: "CreateStableImageEditSearchAndRecolorAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/search-and-recolor\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse6? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse6.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse6.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse7? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse7.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse7.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse8? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse8.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse8.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + try + { + __response.EnsureSuccessStatusCode(); + + var __content = await __response.Content.ReadAsStreamAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.ResponseStream(__response, __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + } + catch + { + __response.Dispose(); + throw; + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Search and Recolor
+ /// The Search and Recolor service provides the ability to change the color of a specific object in an image using a prompt.
+ /// This service is a specific version of inpainting that does not require a mask. The Search and Recolor
+ /// service will automatically segment the object and recolor it using the colors requested in the prompt.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=mtgSh4Stj3l)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// - `select_prompt`
+ /// The body may optionally include:
+ /// - `grow_mask`
+ /// - `seed`
+ /// - `negative_prompt`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will match the resolution of the input image.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/search-and-recolor",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./red-car.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a yellow car",
+ /// "select_prompt": "car",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./yellow-car.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task> CreateStableImageEditSearchAndRecolorAsBytesAsResponseAsync( + string contentType, + + global::StabilityAI.CreateStableImageEditSearchAndRecolorRequest request, + global::StabilityAI.CreateStableImageEditSearchAndRecolorAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + request = request ?? throw new global::System.ArgumentNullException(nameof(request)); + + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageEditSearchAndRecolorAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageEditSearchAndRecolorAsBytesSecurityRequirements, + operationName: "CreateStableImageEditSearchAndRecolorAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/edit/search-and-recolor", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/jpeg"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + var __contentImage = new global::System.Net.Http.ByteArrayContent(request.Image ?? global::System.Array.Empty()); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.SelectPrompt ?? string.Empty), + name: "\"select_prompt\""); + + if (request.NegativePrompt != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty), + name: "\"negative_prompt\""); + + } + if (request.GrowMask != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.GrowMask, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"grow_mask\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + if (request.StylePreset != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.StylePreset).HasValue ? (request.StylePreset).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"style_preset\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageEditSearchAndRecolorAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditSearchAndRecolorAsBytes", + methodName: "CreateStableImageEditSearchAndRecolorAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/search-and-recolor\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditSearchAndRecolorAsBytes", + methodName: "CreateStableImageEditSearchAndRecolorAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/search-and-recolor\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditSearchAndRecolorAsBytes", + methodName: "CreateStableImageEditSearchAndRecolorAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/search-and-recolor\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageEditSearchAndRecolorAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditSearchAndRecolorAsBytes", + methodName: "CreateStableImageEditSearchAndRecolorAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/search-and-recolor\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditSearchAndRecolorAsBytes", + methodName: "CreateStableImageEditSearchAndRecolorAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/search-and-recolor\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse6? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse6.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse6.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse7? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse7.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse7.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse8? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse8.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse8.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessCreateStableImageEditSearchAndRecolorAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Search and Recolor
+ /// The Search and Recolor service provides the ability to change the color of a specific object in an image using a prompt.
+ /// This service is a specific version of inpainting that does not require a mask. The Search and Recolor
+ /// service will automatically segment the object and recolor it using the colors requested in the prompt.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=mtgSh4Stj3l)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// - `select_prompt`
+ /// The body may optionally include:
+ /// - `grow_mask`
+ /// - `seed`
+ /// - `negative_prompt`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will match the resolution of the input image.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// An image containing content you wish to recolor.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// An image containing content you wish to recolor.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// Short description of what to search for in the `image`.
+ /// Example: glasses + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// Grows the edges of the mask outward in all directions by the specified number of pixels. The expanded area around the mask will be blurred, which can help smooth the transition between inpainted content and the original image.
+ /// Try this parameter if you notice seams or rough edges around the inpainted content.
+ /// > Note: Excessive growth may obscure fine details in the mask and/or merge nearby masked regions.
+ /// Default Value: 3 + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + public async global::System.Threading.Tasks.Task CreateStableImageEditSearchAndRecolorAsBytesAsync( + string contentType, + byte[] image, + string imagename, + string prompt, + string selectPrompt, + global::StabilityAI.CreateStableImageEditSearchAndRecolorAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + string? negativePrompt = default, + double? growMask = default, + double? seed = default, + global::StabilityAI.CreateStableImageEditSearchAndRecolorRequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageEditSearchAndRecolorRequestStylePreset? stylePreset = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + var __request = new global::StabilityAI.CreateStableImageEditSearchAndRecolorRequest + { + Image = image, + Imagename = imagename, + Prompt = prompt, + SelectPrompt = selectPrompt, + NegativePrompt = negativePrompt, + GrowMask = growMask, + Seed = seed, + OutputFormat = outputFormat, + StylePreset = stylePreset, + }; + + return await CreateStableImageEditSearchAndRecolorAsBytesAsync( + contentType: contentType, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: __request, + requestOptions: requestOptions, + cancellationToken: cancellationToken).ConfigureAwait(false); + } + + /// + /// Search and Recolor
+ /// The Search and Recolor service provides the ability to change the color of a specific object in an image using a prompt.
+ /// This service is a specific version of inpainting that does not require a mask. The Search and Recolor
+ /// service will automatically segment the object and recolor it using the colors requested in the prompt.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=mtgSh4Stj3l)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// - `select_prompt`
+ /// The body may optionally include:
+ /// - `grow_mask`
+ /// - `seed`
+ /// - `negative_prompt`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will match the resolution of the input image.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// An image containing content you wish to recolor.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// An image containing content you wish to recolor.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// Short description of what to search for in the `image`.
+ /// Example: glasses + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// Grows the edges of the mask outward in all directions by the specified number of pixels. The expanded area around the mask will be blurred, which can help smooth the transition between inpainted content and the original image.
+ /// Try this parameter if you notice seams or rough edges around the inpainted content.
+ /// > Note: Excessive growth may obscure fine details in the mask and/or merge nearby masked regions.
+ /// Default Value: 3 + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/search-and-recolor",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./red-car.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a yellow car",
+ /// "select_prompt": "car",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./yellow-car.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateStableImageEditSearchAndRecolorAsBytesAsync( + string contentType, + global::System.IO.Stream image, + string imagename, + string prompt, + string selectPrompt, + global::StabilityAI.CreateStableImageEditSearchAndRecolorAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + string? negativePrompt = default, + double? growMask = default, + double? seed = default, + global::StabilityAI.CreateStableImageEditSearchAndRecolorRequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageEditSearchAndRecolorRequestStylePreset? stylePreset = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + + image = image ?? throw new global::System.ArgumentNullException(nameof(image)); + var request = new global::StabilityAI.CreateStableImageEditSearchAndRecolorRequest + { + Image = global::System.Array.Empty(), + Imagename = imagename, + Prompt = prompt, + SelectPrompt = selectPrompt, + NegativePrompt = negativePrompt, + GrowMask = growMask, + Seed = seed, + OutputFormat = outputFormat, + StylePreset = stylePreset, + }; + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageEditSearchAndRecolorAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageEditSearchAndRecolorAsBytesSecurityRequirements, + operationName: "CreateStableImageEditSearchAndRecolorAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/edit/search-and-recolor", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/jpeg"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + var __contentImage = new global::System.Net.Http.StreamContent(image); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.SelectPrompt ?? string.Empty), + name: "\"select_prompt\""); + + if (request.NegativePrompt != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty), + name: "\"negative_prompt\""); + + } + if (request.GrowMask != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.GrowMask, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"grow_mask\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + if (request.StylePreset != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.StylePreset).HasValue ? (request.StylePreset).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"style_preset\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageEditSearchAndRecolorAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditSearchAndRecolorAsBytes", + methodName: "CreateStableImageEditSearchAndRecolorAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/search-and-recolor\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditSearchAndRecolorAsBytes", + methodName: "CreateStableImageEditSearchAndRecolorAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/search-and-recolor\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditSearchAndRecolorAsBytes", + methodName: "CreateStableImageEditSearchAndRecolorAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/search-and-recolor\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageEditSearchAndRecolorAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditSearchAndRecolorAsBytes", + methodName: "CreateStableImageEditSearchAndRecolorAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/search-and-recolor\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditSearchAndRecolorAsBytes", + methodName: "CreateStableImageEditSearchAndRecolorAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/search-and-recolor\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse6? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse6.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse6.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse7? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse7.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse7.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse8? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse8.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse8.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessCreateStableImageEditSearchAndRecolorAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return __content; + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return __content; + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Search and Recolor
+ /// The Search and Recolor service provides the ability to change the color of a specific object in an image using a prompt.
+ /// This service is a specific version of inpainting that does not require a mask. The Search and Recolor
+ /// service will automatically segment the object and recolor it using the colors requested in the prompt.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=mtgSh4Stj3l)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// - `select_prompt`
+ /// The body may optionally include:
+ /// - `grow_mask`
+ /// - `seed`
+ /// - `negative_prompt`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will match the resolution of the input image.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// An image containing content you wish to recolor.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// An image containing content you wish to recolor.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// Short description of what to search for in the `image`.
+ /// Example: glasses + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// Grows the edges of the mask outward in all directions by the specified number of pixels. The expanded area around the mask will be blurred, which can help smooth the transition between inpainted content and the original image.
+ /// Try this parameter if you notice seams or rough edges around the inpainted content.
+ /// > Note: Excessive growth may obscure fine details in the mask and/or merge nearby masked regions.
+ /// Default Value: 3 + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/search-and-recolor",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./red-car.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a yellow car",
+ /// "select_prompt": "car",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./yellow-car.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateStableImageEditSearchAndRecolorAsBytesAsStreamAsync( + string contentType, + global::System.IO.Stream image, + string imagename, + string prompt, + string selectPrompt, + global::StabilityAI.CreateStableImageEditSearchAndRecolorAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + string? negativePrompt = default, + double? growMask = default, + double? seed = default, + global::StabilityAI.CreateStableImageEditSearchAndRecolorRequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageEditSearchAndRecolorRequestStylePreset? stylePreset = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + + image = image ?? throw new global::System.ArgumentNullException(nameof(image)); + var request = new global::StabilityAI.CreateStableImageEditSearchAndRecolorRequest + { + Image = global::System.Array.Empty(), + Imagename = imagename, + Prompt = prompt, + SelectPrompt = selectPrompt, + NegativePrompt = negativePrompt, + GrowMask = growMask, + Seed = seed, + OutputFormat = outputFormat, + StylePreset = stylePreset, + }; + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageEditSearchAndRecolorAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageEditSearchAndRecolorAsBytesSecurityRequirements, + operationName: "CreateStableImageEditSearchAndRecolorAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/edit/search-and-recolor", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/jpeg"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + var __contentImage = new global::System.Net.Http.StreamContent(image); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.SelectPrompt ?? string.Empty), + name: "\"select_prompt\""); + + if (request.NegativePrompt != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty), + name: "\"negative_prompt\""); + + } + if (request.GrowMask != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.GrowMask, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"grow_mask\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + if (request.StylePreset != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.StylePreset).HasValue ? (request.StylePreset).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"style_preset\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageEditSearchAndRecolorAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditSearchAndRecolorAsBytes", + methodName: "CreateStableImageEditSearchAndRecolorAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/search-and-recolor\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseHeadersRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditSearchAndRecolorAsBytes", + methodName: "CreateStableImageEditSearchAndRecolorAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/search-and-recolor\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditSearchAndRecolorAsBytes", + methodName: "CreateStableImageEditSearchAndRecolorAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/search-and-recolor\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + try + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageEditSearchAndRecolorAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditSearchAndRecolorAsBytes", + methodName: "CreateStableImageEditSearchAndRecolorAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/search-and-recolor\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditSearchAndRecolorAsBytes", + methodName: "CreateStableImageEditSearchAndRecolorAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/search-and-recolor\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse6? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse6.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse6.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse7? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse7.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse7.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse8? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse8.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse8.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + try + { + __response.EnsureSuccessStatusCode(); + + var __content = await __response.Content.ReadAsStreamAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.ResponseStream(__response, __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + } + catch + { + __response.Dispose(); + throw; + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Search and Recolor
+ /// The Search and Recolor service provides the ability to change the color of a specific object in an image using a prompt.
+ /// This service is a specific version of inpainting that does not require a mask. The Search and Recolor
+ /// service will automatically segment the object and recolor it using the colors requested in the prompt.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=mtgSh4Stj3l)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// - `select_prompt`
+ /// The body may optionally include:
+ /// - `grow_mask`
+ /// - `seed`
+ /// - `negative_prompt`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will match the resolution of the input image.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// An image containing content you wish to recolor.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// An image containing content you wish to recolor.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// Short description of what to search for in the `image`.
+ /// Example: glasses + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// Grows the edges of the mask outward in all directions by the specified number of pixels. The expanded area around the mask will be blurred, which can help smooth the transition between inpainted content and the original image.
+ /// Try this parameter if you notice seams or rough edges around the inpainted content.
+ /// > Note: Excessive growth may obscure fine details in the mask and/or merge nearby masked regions.
+ /// Default Value: 3 + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/search-and-recolor",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./red-car.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a yellow car",
+ /// "select_prompt": "car",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./yellow-car.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task> CreateStableImageEditSearchAndRecolorAsBytesAsResponseAsync( + string contentType, + global::System.IO.Stream image, + string imagename, + string prompt, + string selectPrompt, + global::StabilityAI.CreateStableImageEditSearchAndRecolorAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + string? negativePrompt = default, + double? growMask = default, + double? seed = default, + global::StabilityAI.CreateStableImageEditSearchAndRecolorRequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageEditSearchAndRecolorRequestStylePreset? stylePreset = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + + image = image ?? throw new global::System.ArgumentNullException(nameof(image)); + var request = new global::StabilityAI.CreateStableImageEditSearchAndRecolorRequest + { + Image = global::System.Array.Empty(), + Imagename = imagename, + Prompt = prompt, + SelectPrompt = selectPrompt, + NegativePrompt = negativePrompt, + GrowMask = growMask, + Seed = seed, + OutputFormat = outputFormat, + StylePreset = stylePreset, + }; + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageEditSearchAndRecolorAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageEditSearchAndRecolorAsBytesSecurityRequirements, + operationName: "CreateStableImageEditSearchAndRecolorAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/edit/search-and-recolor", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/jpeg"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + var __contentImage = new global::System.Net.Http.StreamContent(image); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.SelectPrompt ?? string.Empty), + name: "\"select_prompt\""); + + if (request.NegativePrompt != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty), + name: "\"negative_prompt\""); + + } + if (request.GrowMask != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.GrowMask, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"grow_mask\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + if (request.StylePreset != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.StylePreset).HasValue ? (request.StylePreset).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"style_preset\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageEditSearchAndRecolorAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditSearchAndRecolorAsBytes", + methodName: "CreateStableImageEditSearchAndRecolorAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/search-and-recolor\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditSearchAndRecolorAsBytes", + methodName: "CreateStableImageEditSearchAndRecolorAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/search-and-recolor\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditSearchAndRecolorAsBytes", + methodName: "CreateStableImageEditSearchAndRecolorAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/search-and-recolor\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageEditSearchAndRecolorAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditSearchAndRecolorAsBytes", + methodName: "CreateStableImageEditSearchAndRecolorAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/search-and-recolor\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditSearchAndRecolorAsBytes", + methodName: "CreateStableImageEditSearchAndRecolorAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/search-and-recolor\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse6? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse6.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse6.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse7? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse7.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse7.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse8? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse8.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageEditSearchAndRecolorResponse8.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessCreateStableImageEditSearchAndRecolorAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + } +} \ No newline at end of file diff --git a/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditSearchAndReplace.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditSearchAndReplace.g.cs index 2812bea..280794d 100644 --- a/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditSearchAndReplace.g.cs +++ b/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditSearchAndReplace.g.cs @@ -289,6 +289,10 @@ partial void ProcessCreateStableImageEditSearchAndReplaceResponseContent( __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || @@ -326,42 +330,6 @@ partial void ProcessCreateStableImageEditSearchAndReplaceResponseContent( var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"accept\""); - - } - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } var __contentImage = new global::System.Net.Http.ByteArrayContent(request.Image ?? global::System.Array.Empty()); __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( request.Imagename is null @@ -1327,6 +1295,10 @@ request.Imagename is null __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || @@ -1364,42 +1336,6 @@ request.Imagename is null var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"accept\""); - - } - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } var __contentImage = new global::System.Net.Http.StreamContent(image); __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( request.Imagename is null @@ -2207,6 +2143,10 @@ request.Imagename is null __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || @@ -2244,42 +2184,6 @@ request.Imagename is null var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"accept\""); - - } - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } var __contentImage = new global::System.Net.Http.StreamContent(image); __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( request.Imagename is null diff --git a/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditSearchAndReplaceAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditSearchAndReplaceAsBytes.g.cs new file mode 100644 index 0000000..103de92 --- /dev/null +++ b/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditSearchAndReplaceAsBytes.g.cs @@ -0,0 +1,4313 @@ + +#nullable enable + +namespace StabilityAI +{ + public partial class EditClient + { + + + private static readonly global::StabilityAI.EndPointSecurityRequirement s_CreateStableImageEditSearchAndReplaceAsBytesSecurityRequirement0 = + new global::StabilityAI.EndPointSecurityRequirement + { + Authorizations = new global::StabilityAI.EndPointAuthorizationRequirement[] + { new global::StabilityAI.EndPointAuthorizationRequirement + { + Type = "Http", + SchemeId = "HttpBearer", + Location = "Header", + Name = "Bearer", + FriendlyName = "Bearer", + }, + }, + }; + private static readonly global::StabilityAI.EndPointSecurityRequirement[] s_CreateStableImageEditSearchAndReplaceAsBytesSecurityRequirements = + new global::StabilityAI.EndPointSecurityRequirement[] + { s_CreateStableImageEditSearchAndReplaceAsBytesSecurityRequirement0, + }; + partial void PrepareCreateStableImageEditSearchAndReplaceAsBytesArguments( + global::System.Net.Http.HttpClient httpClient, + ref string contentType, + ref global::StabilityAI.CreateStableImageEditSearchAndReplaceAccept? accept, + ref string? stabilityClientId, + ref string? stabilityClientUserId, + ref string? stabilityClientVersion, + global::StabilityAI.CreateStableImageEditSearchAndReplaceRequest request); + partial void PrepareCreateStableImageEditSearchAndReplaceAsBytesRequest( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpRequestMessage httpRequestMessage, + string contentType, + global::StabilityAI.CreateStableImageEditSearchAndReplaceAccept? accept, + string? stabilityClientId, + string? stabilityClientUserId, + string? stabilityClientVersion, + global::StabilityAI.CreateStableImageEditSearchAndReplaceRequest request); + partial void ProcessCreateStableImageEditSearchAndReplaceAsBytesResponse( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpResponseMessage httpResponseMessage); + + partial void ProcessCreateStableImageEditSearchAndReplaceAsBytesResponseContent( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpResponseMessage httpResponseMessage, + ref byte[] content); + + /// + /// Search and Replace
+ /// The Search and Replace service is a specific version of inpainting that does not require a mask.
+ /// Instead, users can leverage a `search_prompt` to identify an object in simple language to be replaced.
+ /// The service will automatically segment the object and replace it with the object requested in the prompt.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=0lDpGa2jAmAs)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// - `search_prompt`
+ /// The body may optionally include:
+ /// - `seed`
+ /// - `negative_prompt`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/search-and-replace",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./husky-in-a-field.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "golden retriever in a field",
+ /// "search_prompt": "dog",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./golden-retriever-in-a-field.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateStableImageEditSearchAndReplaceAsBytesAsync( + string contentType, + + global::StabilityAI.CreateStableImageEditSearchAndReplaceRequest request, + global::StabilityAI.CreateStableImageEditSearchAndReplaceAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + var __response = await CreateStableImageEditSearchAndReplaceAsBytesAsResponseAsync( + contentType: contentType, + + request: request, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + requestOptions: requestOptions, + cancellationToken: cancellationToken + ).ConfigureAwait(false); + + return __response.Body; + } + /// + /// Search and Replace
+ /// The Search and Replace service is a specific version of inpainting that does not require a mask.
+ /// Instead, users can leverage a `search_prompt` to identify an object in simple language to be replaced.
+ /// The service will automatically segment the object and replace it with the object requested in the prompt.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=0lDpGa2jAmAs)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// - `search_prompt`
+ /// The body may optionally include:
+ /// - `seed`
+ /// - `negative_prompt`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/search-and-replace",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./husky-in-a-field.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "golden retriever in a field",
+ /// "search_prompt": "dog",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./golden-retriever-in-a-field.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateStableImageEditSearchAndReplaceAsBytesAsStreamAsync( + string contentType, + + global::StabilityAI.CreateStableImageEditSearchAndReplaceRequest request, + global::StabilityAI.CreateStableImageEditSearchAndReplaceAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + request = request ?? throw new global::System.ArgumentNullException(nameof(request)); + + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageEditSearchAndReplaceAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageEditSearchAndReplaceAsBytesSecurityRequirements, + operationName: "CreateStableImageEditSearchAndReplaceAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/edit/search-and-replace", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/jpeg"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + var __contentImage = new global::System.Net.Http.ByteArrayContent(request.Image ?? global::System.Array.Empty()); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.SearchPrompt ?? string.Empty), + name: "\"search_prompt\""); + + if (request.NegativePrompt != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty), + name: "\"negative_prompt\""); + + } + if (request.GrowMask != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.GrowMask, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"grow_mask\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + if (request.StylePreset != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.StylePreset).HasValue ? (request.StylePreset).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"style_preset\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageEditSearchAndReplaceAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditSearchAndReplaceAsBytes", + methodName: "CreateStableImageEditSearchAndReplaceAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/search-and-replace\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseHeadersRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditSearchAndReplaceAsBytes", + methodName: "CreateStableImageEditSearchAndReplaceAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/search-and-replace\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditSearchAndReplaceAsBytes", + methodName: "CreateStableImageEditSearchAndReplaceAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/search-and-replace\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + try + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageEditSearchAndReplaceAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditSearchAndReplaceAsBytes", + methodName: "CreateStableImageEditSearchAndReplaceAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/search-and-replace\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditSearchAndReplaceAsBytes", + methodName: "CreateStableImageEditSearchAndReplaceAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/search-and-replace\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse6? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse6.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse6.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse7? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse7.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse7.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse8? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse8.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse8.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + try + { + __response.EnsureSuccessStatusCode(); + + var __content = await __response.Content.ReadAsStreamAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.ResponseStream(__response, __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + } + catch + { + __response.Dispose(); + throw; + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Search and Replace
+ /// The Search and Replace service is a specific version of inpainting that does not require a mask.
+ /// Instead, users can leverage a `search_prompt` to identify an object in simple language to be replaced.
+ /// The service will automatically segment the object and replace it with the object requested in the prompt.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=0lDpGa2jAmAs)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// - `search_prompt`
+ /// The body may optionally include:
+ /// - `seed`
+ /// - `negative_prompt`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/search-and-replace",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./husky-in-a-field.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "golden retriever in a field",
+ /// "search_prompt": "dog",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./golden-retriever-in-a-field.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task> CreateStableImageEditSearchAndReplaceAsBytesAsResponseAsync( + string contentType, + + global::StabilityAI.CreateStableImageEditSearchAndReplaceRequest request, + global::StabilityAI.CreateStableImageEditSearchAndReplaceAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + request = request ?? throw new global::System.ArgumentNullException(nameof(request)); + + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageEditSearchAndReplaceAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageEditSearchAndReplaceAsBytesSecurityRequirements, + operationName: "CreateStableImageEditSearchAndReplaceAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/edit/search-and-replace", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/jpeg"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + var __contentImage = new global::System.Net.Http.ByteArrayContent(request.Image ?? global::System.Array.Empty()); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.SearchPrompt ?? string.Empty), + name: "\"search_prompt\""); + + if (request.NegativePrompt != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty), + name: "\"negative_prompt\""); + + } + if (request.GrowMask != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.GrowMask, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"grow_mask\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + if (request.StylePreset != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.StylePreset).HasValue ? (request.StylePreset).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"style_preset\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageEditSearchAndReplaceAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditSearchAndReplaceAsBytes", + methodName: "CreateStableImageEditSearchAndReplaceAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/search-and-replace\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditSearchAndReplaceAsBytes", + methodName: "CreateStableImageEditSearchAndReplaceAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/search-and-replace\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditSearchAndReplaceAsBytes", + methodName: "CreateStableImageEditSearchAndReplaceAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/search-and-replace\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageEditSearchAndReplaceAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditSearchAndReplaceAsBytes", + methodName: "CreateStableImageEditSearchAndReplaceAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/search-and-replace\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditSearchAndReplaceAsBytes", + methodName: "CreateStableImageEditSearchAndReplaceAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/search-and-replace\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse6? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse6.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse6.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse7? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse7.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse7.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse8? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse8.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse8.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessCreateStableImageEditSearchAndReplaceAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Search and Replace
+ /// The Search and Replace service is a specific version of inpainting that does not require a mask.
+ /// Instead, users can leverage a `search_prompt` to identify an object in simple language to be replaced.
+ /// The service will automatically segment the object and replace it with the object requested in the prompt.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=0lDpGa2jAmAs)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// - `search_prompt`
+ /// The body may optionally include:
+ /// - `seed`
+ /// - `negative_prompt`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// An image containing content you wish to replace.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// An image containing content you wish to replace.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// Short description of what to inpaint in the `image`.
+ /// Example: glasses + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// Grows the edges of the mask outward in all directions by the specified number of pixels. The expanded area around the mask will be blurred, which can help smooth the transition between inpainted content and the original image.
+ /// Try this parameter if you notice seams or rough edges around the inpainted content.
+ /// > Note: Excessive growth may obscure fine details in the mask and/or merge nearby masked regions.
+ /// Default Value: 3 + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + public async global::System.Threading.Tasks.Task CreateStableImageEditSearchAndReplaceAsBytesAsync( + string contentType, + byte[] image, + string imagename, + string prompt, + string searchPrompt, + global::StabilityAI.CreateStableImageEditSearchAndReplaceAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + string? negativePrompt = default, + double? growMask = default, + double? seed = default, + global::StabilityAI.CreateStableImageEditSearchAndReplaceRequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageEditSearchAndReplaceRequestStylePreset? stylePreset = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + var __request = new global::StabilityAI.CreateStableImageEditSearchAndReplaceRequest + { + Image = image, + Imagename = imagename, + Prompt = prompt, + SearchPrompt = searchPrompt, + NegativePrompt = negativePrompt, + GrowMask = growMask, + Seed = seed, + OutputFormat = outputFormat, + StylePreset = stylePreset, + }; + + return await CreateStableImageEditSearchAndReplaceAsBytesAsync( + contentType: contentType, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: __request, + requestOptions: requestOptions, + cancellationToken: cancellationToken).ConfigureAwait(false); + } + + /// + /// Search and Replace
+ /// The Search and Replace service is a specific version of inpainting that does not require a mask.
+ /// Instead, users can leverage a `search_prompt` to identify an object in simple language to be replaced.
+ /// The service will automatically segment the object and replace it with the object requested in the prompt.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=0lDpGa2jAmAs)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// - `search_prompt`
+ /// The body may optionally include:
+ /// - `seed`
+ /// - `negative_prompt`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// An image containing content you wish to replace.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// An image containing content you wish to replace.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// Short description of what to inpaint in the `image`.
+ /// Example: glasses + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// Grows the edges of the mask outward in all directions by the specified number of pixels. The expanded area around the mask will be blurred, which can help smooth the transition between inpainted content and the original image.
+ /// Try this parameter if you notice seams or rough edges around the inpainted content.
+ /// > Note: Excessive growth may obscure fine details in the mask and/or merge nearby masked regions.
+ /// Default Value: 3 + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/search-and-replace",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./husky-in-a-field.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "golden retriever in a field",
+ /// "search_prompt": "dog",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./golden-retriever-in-a-field.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateStableImageEditSearchAndReplaceAsBytesAsync( + string contentType, + global::System.IO.Stream image, + string imagename, + string prompt, + string searchPrompt, + global::StabilityAI.CreateStableImageEditSearchAndReplaceAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + string? negativePrompt = default, + double? growMask = default, + double? seed = default, + global::StabilityAI.CreateStableImageEditSearchAndReplaceRequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageEditSearchAndReplaceRequestStylePreset? stylePreset = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + + image = image ?? throw new global::System.ArgumentNullException(nameof(image)); + var request = new global::StabilityAI.CreateStableImageEditSearchAndReplaceRequest + { + Image = global::System.Array.Empty(), + Imagename = imagename, + Prompt = prompt, + SearchPrompt = searchPrompt, + NegativePrompt = negativePrompt, + GrowMask = growMask, + Seed = seed, + OutputFormat = outputFormat, + StylePreset = stylePreset, + }; + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageEditSearchAndReplaceAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageEditSearchAndReplaceAsBytesSecurityRequirements, + operationName: "CreateStableImageEditSearchAndReplaceAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/edit/search-and-replace", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/jpeg"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + var __contentImage = new global::System.Net.Http.StreamContent(image); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.SearchPrompt ?? string.Empty), + name: "\"search_prompt\""); + + if (request.NegativePrompt != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty), + name: "\"negative_prompt\""); + + } + if (request.GrowMask != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.GrowMask, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"grow_mask\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + if (request.StylePreset != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.StylePreset).HasValue ? (request.StylePreset).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"style_preset\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageEditSearchAndReplaceAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditSearchAndReplaceAsBytes", + methodName: "CreateStableImageEditSearchAndReplaceAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/search-and-replace\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditSearchAndReplaceAsBytes", + methodName: "CreateStableImageEditSearchAndReplaceAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/search-and-replace\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditSearchAndReplaceAsBytes", + methodName: "CreateStableImageEditSearchAndReplaceAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/search-and-replace\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageEditSearchAndReplaceAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditSearchAndReplaceAsBytes", + methodName: "CreateStableImageEditSearchAndReplaceAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/search-and-replace\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditSearchAndReplaceAsBytes", + methodName: "CreateStableImageEditSearchAndReplaceAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/search-and-replace\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse6? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse6.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse6.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse7? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse7.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse7.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse8? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse8.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse8.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessCreateStableImageEditSearchAndReplaceAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return __content; + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return __content; + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Search and Replace
+ /// The Search and Replace service is a specific version of inpainting that does not require a mask.
+ /// Instead, users can leverage a `search_prompt` to identify an object in simple language to be replaced.
+ /// The service will automatically segment the object and replace it with the object requested in the prompt.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=0lDpGa2jAmAs)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// - `search_prompt`
+ /// The body may optionally include:
+ /// - `seed`
+ /// - `negative_prompt`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// An image containing content you wish to replace.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// An image containing content you wish to replace.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// Short description of what to inpaint in the `image`.
+ /// Example: glasses + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// Grows the edges of the mask outward in all directions by the specified number of pixels. The expanded area around the mask will be blurred, which can help smooth the transition between inpainted content and the original image.
+ /// Try this parameter if you notice seams or rough edges around the inpainted content.
+ /// > Note: Excessive growth may obscure fine details in the mask and/or merge nearby masked regions.
+ /// Default Value: 3 + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/search-and-replace",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./husky-in-a-field.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "golden retriever in a field",
+ /// "search_prompt": "dog",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./golden-retriever-in-a-field.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateStableImageEditSearchAndReplaceAsBytesAsStreamAsync( + string contentType, + global::System.IO.Stream image, + string imagename, + string prompt, + string searchPrompt, + global::StabilityAI.CreateStableImageEditSearchAndReplaceAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + string? negativePrompt = default, + double? growMask = default, + double? seed = default, + global::StabilityAI.CreateStableImageEditSearchAndReplaceRequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageEditSearchAndReplaceRequestStylePreset? stylePreset = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + + image = image ?? throw new global::System.ArgumentNullException(nameof(image)); + var request = new global::StabilityAI.CreateStableImageEditSearchAndReplaceRequest + { + Image = global::System.Array.Empty(), + Imagename = imagename, + Prompt = prompt, + SearchPrompt = searchPrompt, + NegativePrompt = negativePrompt, + GrowMask = growMask, + Seed = seed, + OutputFormat = outputFormat, + StylePreset = stylePreset, + }; + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageEditSearchAndReplaceAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageEditSearchAndReplaceAsBytesSecurityRequirements, + operationName: "CreateStableImageEditSearchAndReplaceAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/edit/search-and-replace", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/jpeg"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + var __contentImage = new global::System.Net.Http.StreamContent(image); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.SearchPrompt ?? string.Empty), + name: "\"search_prompt\""); + + if (request.NegativePrompt != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty), + name: "\"negative_prompt\""); + + } + if (request.GrowMask != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.GrowMask, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"grow_mask\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + if (request.StylePreset != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.StylePreset).HasValue ? (request.StylePreset).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"style_preset\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageEditSearchAndReplaceAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditSearchAndReplaceAsBytes", + methodName: "CreateStableImageEditSearchAndReplaceAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/search-and-replace\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseHeadersRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditSearchAndReplaceAsBytes", + methodName: "CreateStableImageEditSearchAndReplaceAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/search-and-replace\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditSearchAndReplaceAsBytes", + methodName: "CreateStableImageEditSearchAndReplaceAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/search-and-replace\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + try + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageEditSearchAndReplaceAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditSearchAndReplaceAsBytes", + methodName: "CreateStableImageEditSearchAndReplaceAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/search-and-replace\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditSearchAndReplaceAsBytes", + methodName: "CreateStableImageEditSearchAndReplaceAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/search-and-replace\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse6? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse6.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse6.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse7? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse7.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse7.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse8? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse8.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse8.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + try + { + __response.EnsureSuccessStatusCode(); + + var __content = await __response.Content.ReadAsStreamAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.ResponseStream(__response, __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + } + catch + { + __response.Dispose(); + throw; + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Search and Replace
+ /// The Search and Replace service is a specific version of inpainting that does not require a mask.
+ /// Instead, users can leverage a `search_prompt` to identify an object in simple language to be replaced.
+ /// The service will automatically segment the object and replace it with the object requested in the prompt.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=0lDpGa2jAmAs)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// - `search_prompt`
+ /// The body may optionally include:
+ /// - `seed`
+ /// - `negative_prompt`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// An image containing content you wish to replace.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// An image containing content you wish to replace.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// Short description of what to inpaint in the `image`.
+ /// Example: glasses + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// Grows the edges of the mask outward in all directions by the specified number of pixels. The expanded area around the mask will be blurred, which can help smooth the transition between inpainted content and the original image.
+ /// Try this parameter if you notice seams or rough edges around the inpainted content.
+ /// > Note: Excessive growth may obscure fine details in the mask and/or merge nearby masked regions.
+ /// Default Value: 3 + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/search-and-replace",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./husky-in-a-field.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "golden retriever in a field",
+ /// "search_prompt": "dog",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./golden-retriever-in-a-field.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task> CreateStableImageEditSearchAndReplaceAsBytesAsResponseAsync( + string contentType, + global::System.IO.Stream image, + string imagename, + string prompt, + string searchPrompt, + global::StabilityAI.CreateStableImageEditSearchAndReplaceAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + string? negativePrompt = default, + double? growMask = default, + double? seed = default, + global::StabilityAI.CreateStableImageEditSearchAndReplaceRequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageEditSearchAndReplaceRequestStylePreset? stylePreset = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + + image = image ?? throw new global::System.ArgumentNullException(nameof(image)); + var request = new global::StabilityAI.CreateStableImageEditSearchAndReplaceRequest + { + Image = global::System.Array.Empty(), + Imagename = imagename, + Prompt = prompt, + SearchPrompt = searchPrompt, + NegativePrompt = negativePrompt, + GrowMask = growMask, + Seed = seed, + OutputFormat = outputFormat, + StylePreset = stylePreset, + }; + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageEditSearchAndReplaceAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageEditSearchAndReplaceAsBytesSecurityRequirements, + operationName: "CreateStableImageEditSearchAndReplaceAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/edit/search-and-replace", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/jpeg"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + var __contentImage = new global::System.Net.Http.StreamContent(image); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.SearchPrompt ?? string.Empty), + name: "\"search_prompt\""); + + if (request.NegativePrompt != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty), + name: "\"negative_prompt\""); + + } + if (request.GrowMask != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.GrowMask, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"grow_mask\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + if (request.StylePreset != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.StylePreset).HasValue ? (request.StylePreset).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"style_preset\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageEditSearchAndReplaceAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditSearchAndReplaceAsBytes", + methodName: "CreateStableImageEditSearchAndReplaceAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/search-and-replace\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditSearchAndReplaceAsBytes", + methodName: "CreateStableImageEditSearchAndReplaceAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/search-and-replace\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditSearchAndReplaceAsBytes", + methodName: "CreateStableImageEditSearchAndReplaceAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/search-and-replace\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageEditSearchAndReplaceAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditSearchAndReplaceAsBytes", + methodName: "CreateStableImageEditSearchAndReplaceAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/search-and-replace\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageEditSearchAndReplaceAsBytes", + methodName: "CreateStableImageEditSearchAndReplaceAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/edit/search-and-replace\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse6? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse6.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse6.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse7? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse7.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse7.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse8? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse8.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageEditSearchAndReplaceResponse8.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessCreateStableImageEditSearchAndReplaceAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + } +} \ No newline at end of file diff --git a/src/libs/StabilityAI/Generated/StabilityAI.GenerateClient.CreateStableImageGenerateCore.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.GenerateClient.CreateStableImageGenerateCore.g.cs index e24a134..92a0217 100644 --- a/src/libs/StabilityAI/Generated/StabilityAI.GenerateClient.CreateStableImageGenerateCore.g.cs +++ b/src/libs/StabilityAI/Generated/StabilityAI.GenerateClient.CreateStableImageGenerateCore.g.cs @@ -279,6 +279,10 @@ partial void ProcessCreateStableImageGenerateCoreResponseContent( __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || @@ -316,42 +320,6 @@ partial void ProcessCreateStableImageGenerateCoreResponseContent( var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"accept\""); - - } - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } __httpRequestContent.Add( content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), name: "\"prompt\""); diff --git a/src/libs/StabilityAI/Generated/StabilityAI.GenerateClient.CreateStableImageGenerateCoreAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.GenerateClient.CreateStableImageGenerateCoreAsBytes.g.cs new file mode 100644 index 0000000..da0f248 --- /dev/null +++ b/src/libs/StabilityAI/Generated/StabilityAI.GenerateClient.CreateStableImageGenerateCoreAsBytes.g.cs @@ -0,0 +1,1602 @@ + +#nullable enable + +namespace StabilityAI +{ + public partial class GenerateClient + { + + + private static readonly global::StabilityAI.EndPointSecurityRequirement s_CreateStableImageGenerateCoreAsBytesSecurityRequirement0 = + new global::StabilityAI.EndPointSecurityRequirement + { + Authorizations = new global::StabilityAI.EndPointAuthorizationRequirement[] + { new global::StabilityAI.EndPointAuthorizationRequirement + { + Type = "Http", + SchemeId = "HttpBearer", + Location = "Header", + Name = "Bearer", + FriendlyName = "Bearer", + }, + }, + }; + private static readonly global::StabilityAI.EndPointSecurityRequirement[] s_CreateStableImageGenerateCoreAsBytesSecurityRequirements = + new global::StabilityAI.EndPointSecurityRequirement[] + { s_CreateStableImageGenerateCoreAsBytesSecurityRequirement0, + }; + partial void PrepareCreateStableImageGenerateCoreAsBytesArguments( + global::System.Net.Http.HttpClient httpClient, + ref string contentType, + ref global::StabilityAI.CreateStableImageGenerateCoreAccept? accept, + ref string? stabilityClientId, + ref string? stabilityClientUserId, + ref string? stabilityClientVersion, + global::StabilityAI.CreateStableImageGenerateCoreRequest request); + partial void PrepareCreateStableImageGenerateCoreAsBytesRequest( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpRequestMessage httpRequestMessage, + string contentType, + global::StabilityAI.CreateStableImageGenerateCoreAccept? accept, + string? stabilityClientId, + string? stabilityClientUserId, + string? stabilityClientVersion, + global::StabilityAI.CreateStableImageGenerateCoreRequest request); + partial void ProcessCreateStableImageGenerateCoreAsBytesResponse( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpResponseMessage httpResponseMessage); + + partial void ProcessCreateStableImageGenerateCoreAsBytesResponseContent( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpResponseMessage httpResponseMessage, + ref byte[] content); + + /// + /// Stable Image Core
+ /// Our primary service for text-to-image generation, Stable Image Core represents the best quality achievable at high
+ /// speed. No prompt engineering is required! Try asking for a style, a scene, or a character, and see what you get.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=yXhs626oZdr1)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `aspect_ratio`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `style_preset`
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1.5 megapixels.
+ /// ### Credits
+ /// Flat rate of 3 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/generate/core",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={"none": ''},
+ /// data={
+ /// "prompt": "Lighthouse on a cliff overlooking the ocean",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./lighthouse.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateStableImageGenerateCoreAsBytesAsync( + string contentType, + + global::StabilityAI.CreateStableImageGenerateCoreRequest request, + global::StabilityAI.CreateStableImageGenerateCoreAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + var __response = await CreateStableImageGenerateCoreAsBytesAsResponseAsync( + contentType: contentType, + + request: request, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + requestOptions: requestOptions, + cancellationToken: cancellationToken + ).ConfigureAwait(false); + + return __response.Body; + } + /// + /// Stable Image Core
+ /// Our primary service for text-to-image generation, Stable Image Core represents the best quality achievable at high
+ /// speed. No prompt engineering is required! Try asking for a style, a scene, or a character, and see what you get.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=yXhs626oZdr1)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `aspect_ratio`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `style_preset`
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1.5 megapixels.
+ /// ### Credits
+ /// Flat rate of 3 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/generate/core",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={"none": ''},
+ /// data={
+ /// "prompt": "Lighthouse on a cliff overlooking the ocean",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./lighthouse.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateStableImageGenerateCoreAsBytesAsStreamAsync( + string contentType, + + global::StabilityAI.CreateStableImageGenerateCoreRequest request, + global::StabilityAI.CreateStableImageGenerateCoreAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + request = request ?? throw new global::System.ArgumentNullException(nameof(request)); + + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageGenerateCoreAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageGenerateCoreAsBytesSecurityRequirements, + operationName: "CreateStableImageGenerateCoreAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/generate/core", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/png"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + if (request.AspectRatio != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.AspectRatio).HasValue ? (request.AspectRatio).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"aspect_ratio\""); + + } + if (request.NegativePrompt != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty), + name: "\"negative_prompt\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.StylePreset != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.StylePreset).HasValue ? (request.StylePreset).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"style_preset\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageGenerateCoreAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageGenerateCoreAsBytes", + methodName: "CreateStableImageGenerateCoreAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/generate/core\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseHeadersRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageGenerateCoreAsBytes", + methodName: "CreateStableImageGenerateCoreAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/generate/core\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageGenerateCoreAsBytes", + methodName: "CreateStableImageGenerateCoreAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/generate/core\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + try + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageGenerateCoreAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageGenerateCoreAsBytes", + methodName: "CreateStableImageGenerateCoreAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/generate/core\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageGenerateCoreAsBytes", + methodName: "CreateStableImageGenerateCoreAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/generate/core\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageGenerateCoreResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageGenerateCoreResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageGenerateCoreResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateStableImageGenerateCoreResponse5? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateStableImageGenerateCoreResponse5.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateStableImageGenerateCoreResponse5.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageGenerateCoreResponse6? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageGenerateCoreResponse6.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageGenerateCoreResponse6.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageGenerateCoreResponse7? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageGenerateCoreResponse7.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageGenerateCoreResponse7.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + try + { + __response.EnsureSuccessStatusCode(); + + var __content = await __response.Content.ReadAsStreamAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.ResponseStream(__response, __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + } + catch + { + __response.Dispose(); + throw; + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Stable Image Core
+ /// Our primary service for text-to-image generation, Stable Image Core represents the best quality achievable at high
+ /// speed. No prompt engineering is required! Try asking for a style, a scene, or a character, and see what you get.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=yXhs626oZdr1)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `aspect_ratio`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `style_preset`
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1.5 megapixels.
+ /// ### Credits
+ /// Flat rate of 3 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/generate/core",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={"none": ''},
+ /// data={
+ /// "prompt": "Lighthouse on a cliff overlooking the ocean",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./lighthouse.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task> CreateStableImageGenerateCoreAsBytesAsResponseAsync( + string contentType, + + global::StabilityAI.CreateStableImageGenerateCoreRequest request, + global::StabilityAI.CreateStableImageGenerateCoreAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + request = request ?? throw new global::System.ArgumentNullException(nameof(request)); + + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageGenerateCoreAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageGenerateCoreAsBytesSecurityRequirements, + operationName: "CreateStableImageGenerateCoreAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/generate/core", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/png"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + if (request.AspectRatio != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.AspectRatio).HasValue ? (request.AspectRatio).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"aspect_ratio\""); + + } + if (request.NegativePrompt != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty), + name: "\"negative_prompt\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.StylePreset != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.StylePreset).HasValue ? (request.StylePreset).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"style_preset\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageGenerateCoreAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageGenerateCoreAsBytes", + methodName: "CreateStableImageGenerateCoreAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/generate/core\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageGenerateCoreAsBytes", + methodName: "CreateStableImageGenerateCoreAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/generate/core\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageGenerateCoreAsBytes", + methodName: "CreateStableImageGenerateCoreAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/generate/core\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageGenerateCoreAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageGenerateCoreAsBytes", + methodName: "CreateStableImageGenerateCoreAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/generate/core\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageGenerateCoreAsBytes", + methodName: "CreateStableImageGenerateCoreAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/generate/core\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageGenerateCoreResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageGenerateCoreResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageGenerateCoreResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateStableImageGenerateCoreResponse5? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateStableImageGenerateCoreResponse5.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateStableImageGenerateCoreResponse5.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageGenerateCoreResponse6? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageGenerateCoreResponse6.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageGenerateCoreResponse6.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageGenerateCoreResponse7? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageGenerateCoreResponse7.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageGenerateCoreResponse7.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessCreateStableImageGenerateCoreAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Stable Image Core
+ /// Our primary service for text-to-image generation, Stable Image Core represents the best quality achievable at high
+ /// speed. No prompt engineering is required! Try asking for a style, a scene, or a character, and see what you get.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=yXhs626oZdr1)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `aspect_ratio`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `style_preset`
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1.5 megapixels.
+ /// ### Credits
+ /// Flat rate of 3 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// Controls the aspect ratio of the generated image.
+ /// Default Value: 1:1 + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Guides the image model towards a particular style. + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + public async global::System.Threading.Tasks.Task CreateStableImageGenerateCoreAsBytesAsync( + string contentType, + string prompt, + global::StabilityAI.CreateStableImageGenerateCoreAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.CreateStableImageGenerateCoreRequestAspectRatio? aspectRatio = default, + string? negativePrompt = default, + double? seed = default, + global::StabilityAI.CreateStableImageGenerateCoreRequestStylePreset? stylePreset = default, + global::StabilityAI.CreateStableImageGenerateCoreRequestOutputFormat? outputFormat = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + var __request = new global::StabilityAI.CreateStableImageGenerateCoreRequest + { + Prompt = prompt, + AspectRatio = aspectRatio, + NegativePrompt = negativePrompt, + Seed = seed, + StylePreset = stylePreset, + OutputFormat = outputFormat, + }; + + return await CreateStableImageGenerateCoreAsBytesAsync( + contentType: contentType, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: __request, + requestOptions: requestOptions, + cancellationToken: cancellationToken).ConfigureAwait(false); + } + } +} \ No newline at end of file diff --git a/src/libs/StabilityAI/Generated/StabilityAI.GenerateClient.CreateStableImageGenerateSd3.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.GenerateClient.CreateStableImageGenerateSd3.g.cs index b337647..875c357 100644 --- a/src/libs/StabilityAI/Generated/StabilityAI.GenerateClient.CreateStableImageGenerateSd3.g.cs +++ b/src/libs/StabilityAI/Generated/StabilityAI.GenerateClient.CreateStableImageGenerateSd3.g.cs @@ -341,6 +341,10 @@ partial void ProcessCreateStableImageGenerateSd3ResponseContent( __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || @@ -378,42 +382,6 @@ partial void ProcessCreateStableImageGenerateSd3ResponseContent( var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"accept\""); - - } - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } __httpRequestContent.Add( content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), name: "\"prompt\""); diff --git a/src/libs/StabilityAI/Generated/StabilityAI.GenerateClient.CreateStableImageGenerateSd3AsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.GenerateClient.CreateStableImageGenerateSd3AsBytes.g.cs new file mode 100644 index 0000000..0a943e4 --- /dev/null +++ b/src/libs/StabilityAI/Generated/StabilityAI.GenerateClient.CreateStableImageGenerateSd3AsBytes.g.cs @@ -0,0 +1,2003 @@ + +#nullable enable + +namespace StabilityAI +{ + public partial class GenerateClient + { + + + private static readonly global::StabilityAI.EndPointSecurityRequirement s_CreateStableImageGenerateSd3AsBytesSecurityRequirement0 = + new global::StabilityAI.EndPointSecurityRequirement + { + Authorizations = new global::StabilityAI.EndPointAuthorizationRequirement[] + { new global::StabilityAI.EndPointAuthorizationRequirement + { + Type = "Http", + SchemeId = "HttpBearer", + Location = "Header", + Name = "Bearer", + FriendlyName = "Bearer", + }, + }, + }; + private static readonly global::StabilityAI.EndPointSecurityRequirement[] s_CreateStableImageGenerateSd3AsBytesSecurityRequirements = + new global::StabilityAI.EndPointSecurityRequirement[] + { s_CreateStableImageGenerateSd3AsBytesSecurityRequirement0, + }; + partial void PrepareCreateStableImageGenerateSd3AsBytesArguments( + global::System.Net.Http.HttpClient httpClient, + ref string contentType, + ref global::StabilityAI.CreateStableImageGenerateSd3Accept? accept, + ref string? stabilityClientId, + ref string? stabilityClientUserId, + ref string? stabilityClientVersion, + global::StabilityAI.CreateStableImageGenerateSd3Request request); + partial void PrepareCreateStableImageGenerateSd3AsBytesRequest( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpRequestMessage httpRequestMessage, + string contentType, + global::StabilityAI.CreateStableImageGenerateSd3Accept? accept, + string? stabilityClientId, + string? stabilityClientUserId, + string? stabilityClientVersion, + global::StabilityAI.CreateStableImageGenerateSd3Request request); + partial void ProcessCreateStableImageGenerateSd3AsBytesResponse( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpResponseMessage httpResponseMessage); + + partial void ProcessCreateStableImageGenerateSd3AsBytesResponseContent( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpResponseMessage httpResponseMessage, + ref byte[] content); + + /// + /// Stable Diffusion 3.5
+ /// Generate using Stable Diffusion 3.5 models, Stability AI latest base model:
+ /// - **Stable Diffusion 3.5 Large**: At 8 billion parameters, with superior quality and
+ /// prompt adherence, this base model is the most powerful in the Stable Diffusion
+ /// family. This model is ideal for professional use cases at 1 megapixel resolution.
+ /// - **Stable Diffusion 3.5 Large Turbo**: A distilled version of Stable Diffusion 3.5 Large.
+ /// SD3.5 Large Turbo generates high-quality images with exceptional prompt adherence
+ /// in just 4 steps, making it considerably faster than Stable Diffusion 3.5 Large.
+ /// - **Stable Diffusion 3.5 Medium**: With 2.5 billion parameters, the model delivers an
+ /// optimal balance between prompt accuracy and image quality, making it an efficient
+ /// choice for fast high-performance image generation.
+ /// - **Stable Diffusion 3.5 Flash**: A distilled version of Stable Diffusion 3.5 Medium.
+ /// SD3.5 Flash generates high-quality images with a 4 step process instead of 40, making
+ /// it faster than Stable Diffusion 3.5 Medium.
+ /// Read more about the model capabilities [here](https://stability.ai/news/introducing-stable-diffusion-3-5).
+ /// As of April 17, 2025, we have deprecated the Stable Diffusion 3.0 APIs and will be automatically
+ /// re-routing calls to Stable Diffusion 3.0 models to Stable Diffusion 3.5 APIs at no extra cost.
+ /// You can read more in the [release notes](/docs/release-notes#api-deprecation-notice).
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/SD3_API.ipynb)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`. The accept header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// #### **Generating with a prompt**
+ /// Commonly referred to as **text-to-image**, this mode generates an image from text alone. While the only required
+ /// parameter is the `prompt`, it also supports an `aspect_ratio` parameter which can be used to control the
+ /// aspect ratio of the generated image.
+ /// #### **Generating with a prompt *and* an image**
+ /// Commonly referred to as **image-to-image**, this mode also generates an image from text but uses an existing image as the
+ /// starting point. The required parameters are:
+ /// - `prompt` - text to generate the image from
+ /// - `image` - the image to use as the starting point for the generation
+ /// - `strength` - controls how much influence the `image` parameter has on the output image
+ /// - `mode` - must be set to `image-to-image`
+ /// > **Note:** maximum request size is 10MiB.
+ /// #### **Optional Parameters:**
+ /// Both modes support the following optional parameters:
+ /// - `model` - the model to use (SD 3.5 Large, SD 3.5 Large Turbo, SD 3.5 Medium, SD 3.5 Flash)
+ /// - `output_format` - the format of the output image
+ /// - `seed` - the randomness seed to use for the generation
+ /// - `negative_prompt` - keywords of what you **do not** wish to see in the output image
+ /// - `cfg_scale` - controls how strictly the diffusion process adheres to the prompt text
+ /// - `style_preset` - guides the image model towards a particular style
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1MP. The default resolution is 1024x1024.
+ /// ### Credits
+ /// - **SD 3.5 Large**: Flat rate of 6.5 credits per successful generation.
+ /// - **SD 3.5 Large Turbo**: Flat rate of 4 credits per successful generation.
+ /// - **SD 3.5 Medium**: Flat rate of 3.5 credits per successful generation.
+ /// - **SD 3.5 Flash**: Flat rate of 2.5 credits per successful generation.
+ /// As always, you will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/generate/sd3",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={"none": ''},
+ /// data={
+ /// "prompt": "Lighthouse on a cliff overlooking the ocean",
+ /// "output_format": "jpeg",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./lighthouse.jpeg", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateStableImageGenerateSd3AsBytesAsync( + string contentType, + + global::StabilityAI.CreateStableImageGenerateSd3Request request, + global::StabilityAI.CreateStableImageGenerateSd3Accept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + var __response = await CreateStableImageGenerateSd3AsBytesAsResponseAsync( + contentType: contentType, + + request: request, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + requestOptions: requestOptions, + cancellationToken: cancellationToken + ).ConfigureAwait(false); + + return __response.Body; + } + /// + /// Stable Diffusion 3.5
+ /// Generate using Stable Diffusion 3.5 models, Stability AI latest base model:
+ /// - **Stable Diffusion 3.5 Large**: At 8 billion parameters, with superior quality and
+ /// prompt adherence, this base model is the most powerful in the Stable Diffusion
+ /// family. This model is ideal for professional use cases at 1 megapixel resolution.
+ /// - **Stable Diffusion 3.5 Large Turbo**: A distilled version of Stable Diffusion 3.5 Large.
+ /// SD3.5 Large Turbo generates high-quality images with exceptional prompt adherence
+ /// in just 4 steps, making it considerably faster than Stable Diffusion 3.5 Large.
+ /// - **Stable Diffusion 3.5 Medium**: With 2.5 billion parameters, the model delivers an
+ /// optimal balance between prompt accuracy and image quality, making it an efficient
+ /// choice for fast high-performance image generation.
+ /// - **Stable Diffusion 3.5 Flash**: A distilled version of Stable Diffusion 3.5 Medium.
+ /// SD3.5 Flash generates high-quality images with a 4 step process instead of 40, making
+ /// it faster than Stable Diffusion 3.5 Medium.
+ /// Read more about the model capabilities [here](https://stability.ai/news/introducing-stable-diffusion-3-5).
+ /// As of April 17, 2025, we have deprecated the Stable Diffusion 3.0 APIs and will be automatically
+ /// re-routing calls to Stable Diffusion 3.0 models to Stable Diffusion 3.5 APIs at no extra cost.
+ /// You can read more in the [release notes](/docs/release-notes#api-deprecation-notice).
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/SD3_API.ipynb)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`. The accept header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// #### **Generating with a prompt**
+ /// Commonly referred to as **text-to-image**, this mode generates an image from text alone. While the only required
+ /// parameter is the `prompt`, it also supports an `aspect_ratio` parameter which can be used to control the
+ /// aspect ratio of the generated image.
+ /// #### **Generating with a prompt *and* an image**
+ /// Commonly referred to as **image-to-image**, this mode also generates an image from text but uses an existing image as the
+ /// starting point. The required parameters are:
+ /// - `prompt` - text to generate the image from
+ /// - `image` - the image to use as the starting point for the generation
+ /// - `strength` - controls how much influence the `image` parameter has on the output image
+ /// - `mode` - must be set to `image-to-image`
+ /// > **Note:** maximum request size is 10MiB.
+ /// #### **Optional Parameters:**
+ /// Both modes support the following optional parameters:
+ /// - `model` - the model to use (SD 3.5 Large, SD 3.5 Large Turbo, SD 3.5 Medium, SD 3.5 Flash)
+ /// - `output_format` - the format of the output image
+ /// - `seed` - the randomness seed to use for the generation
+ /// - `negative_prompt` - keywords of what you **do not** wish to see in the output image
+ /// - `cfg_scale` - controls how strictly the diffusion process adheres to the prompt text
+ /// - `style_preset` - guides the image model towards a particular style
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1MP. The default resolution is 1024x1024.
+ /// ### Credits
+ /// - **SD 3.5 Large**: Flat rate of 6.5 credits per successful generation.
+ /// - **SD 3.5 Large Turbo**: Flat rate of 4 credits per successful generation.
+ /// - **SD 3.5 Medium**: Flat rate of 3.5 credits per successful generation.
+ /// - **SD 3.5 Flash**: Flat rate of 2.5 credits per successful generation.
+ /// As always, you will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/generate/sd3",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={"none": ''},
+ /// data={
+ /// "prompt": "Lighthouse on a cliff overlooking the ocean",
+ /// "output_format": "jpeg",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./lighthouse.jpeg", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateStableImageGenerateSd3AsBytesAsStreamAsync( + string contentType, + + global::StabilityAI.CreateStableImageGenerateSd3Request request, + global::StabilityAI.CreateStableImageGenerateSd3Accept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + request = request ?? throw new global::System.ArgumentNullException(nameof(request)); + + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageGenerateSd3AsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageGenerateSd3AsBytesSecurityRequirements, + operationName: "CreateStableImageGenerateSd3AsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/generate/sd3", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/png"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + if (request.Mode != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.Mode).HasValue ? (request.Mode).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"mode\""); + + } + if (request.Image != default) + { + + var __contentImage = new global::System.Net.Http.ByteArrayContent(request.Image ?? global::System.Array.Empty()); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + } + if (request.Strength != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Strength, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"strength\""); + + } + if (request.AspectRatio != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.AspectRatio).HasValue ? (request.AspectRatio).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"aspect_ratio\""); + + } + if (request.Model != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.Model).HasValue ? (request.Model).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"model\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + if (request.StylePreset != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.StylePreset).HasValue ? (request.StylePreset).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"style_preset\""); + + } + if (request.NegativePrompt != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty), + name: "\"negative_prompt\""); + + } + if (request.CfgScale != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.CfgScale, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"cfg_scale\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageGenerateSd3AsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageGenerateSd3AsBytes", + methodName: "CreateStableImageGenerateSd3AsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/generate/sd3\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseHeadersRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageGenerateSd3AsBytes", + methodName: "CreateStableImageGenerateSd3AsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/generate/sd3\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageGenerateSd3AsBytes", + methodName: "CreateStableImageGenerateSd3AsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/generate/sd3\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + try + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageGenerateSd3AsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageGenerateSd3AsBytes", + methodName: "CreateStableImageGenerateSd3AsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/generate/sd3\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageGenerateSd3AsBytes", + methodName: "CreateStableImageGenerateSd3AsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/generate/sd3\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageGenerateSd3Response4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageGenerateSd3Response4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageGenerateSd3Response4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageGenerateSd3Response5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageGenerateSd3Response5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageGenerateSd3Response5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateStableImageGenerateSd3Response6? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateStableImageGenerateSd3Response6.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateStableImageGenerateSd3Response6.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageGenerateSd3Response7? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageGenerateSd3Response7.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageGenerateSd3Response7.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageGenerateSd3Response8? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageGenerateSd3Response8.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageGenerateSd3Response8.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + try + { + __response.EnsureSuccessStatusCode(); + + var __content = await __response.Content.ReadAsStreamAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.ResponseStream(__response, __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + } + catch + { + __response.Dispose(); + throw; + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Stable Diffusion 3.5
+ /// Generate using Stable Diffusion 3.5 models, Stability AI latest base model:
+ /// - **Stable Diffusion 3.5 Large**: At 8 billion parameters, with superior quality and
+ /// prompt adherence, this base model is the most powerful in the Stable Diffusion
+ /// family. This model is ideal for professional use cases at 1 megapixel resolution.
+ /// - **Stable Diffusion 3.5 Large Turbo**: A distilled version of Stable Diffusion 3.5 Large.
+ /// SD3.5 Large Turbo generates high-quality images with exceptional prompt adherence
+ /// in just 4 steps, making it considerably faster than Stable Diffusion 3.5 Large.
+ /// - **Stable Diffusion 3.5 Medium**: With 2.5 billion parameters, the model delivers an
+ /// optimal balance between prompt accuracy and image quality, making it an efficient
+ /// choice for fast high-performance image generation.
+ /// - **Stable Diffusion 3.5 Flash**: A distilled version of Stable Diffusion 3.5 Medium.
+ /// SD3.5 Flash generates high-quality images with a 4 step process instead of 40, making
+ /// it faster than Stable Diffusion 3.5 Medium.
+ /// Read more about the model capabilities [here](https://stability.ai/news/introducing-stable-diffusion-3-5).
+ /// As of April 17, 2025, we have deprecated the Stable Diffusion 3.0 APIs and will be automatically
+ /// re-routing calls to Stable Diffusion 3.0 models to Stable Diffusion 3.5 APIs at no extra cost.
+ /// You can read more in the [release notes](/docs/release-notes#api-deprecation-notice).
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/SD3_API.ipynb)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`. The accept header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// #### **Generating with a prompt**
+ /// Commonly referred to as **text-to-image**, this mode generates an image from text alone. While the only required
+ /// parameter is the `prompt`, it also supports an `aspect_ratio` parameter which can be used to control the
+ /// aspect ratio of the generated image.
+ /// #### **Generating with a prompt *and* an image**
+ /// Commonly referred to as **image-to-image**, this mode also generates an image from text but uses an existing image as the
+ /// starting point. The required parameters are:
+ /// - `prompt` - text to generate the image from
+ /// - `image` - the image to use as the starting point for the generation
+ /// - `strength` - controls how much influence the `image` parameter has on the output image
+ /// - `mode` - must be set to `image-to-image`
+ /// > **Note:** maximum request size is 10MiB.
+ /// #### **Optional Parameters:**
+ /// Both modes support the following optional parameters:
+ /// - `model` - the model to use (SD 3.5 Large, SD 3.5 Large Turbo, SD 3.5 Medium, SD 3.5 Flash)
+ /// - `output_format` - the format of the output image
+ /// - `seed` - the randomness seed to use for the generation
+ /// - `negative_prompt` - keywords of what you **do not** wish to see in the output image
+ /// - `cfg_scale` - controls how strictly the diffusion process adheres to the prompt text
+ /// - `style_preset` - guides the image model towards a particular style
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1MP. The default resolution is 1024x1024.
+ /// ### Credits
+ /// - **SD 3.5 Large**: Flat rate of 6.5 credits per successful generation.
+ /// - **SD 3.5 Large Turbo**: Flat rate of 4 credits per successful generation.
+ /// - **SD 3.5 Medium**: Flat rate of 3.5 credits per successful generation.
+ /// - **SD 3.5 Flash**: Flat rate of 2.5 credits per successful generation.
+ /// As always, you will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/generate/sd3",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={"none": ''},
+ /// data={
+ /// "prompt": "Lighthouse on a cliff overlooking the ocean",
+ /// "output_format": "jpeg",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./lighthouse.jpeg", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task> CreateStableImageGenerateSd3AsBytesAsResponseAsync( + string contentType, + + global::StabilityAI.CreateStableImageGenerateSd3Request request, + global::StabilityAI.CreateStableImageGenerateSd3Accept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + request = request ?? throw new global::System.ArgumentNullException(nameof(request)); + + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageGenerateSd3AsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageGenerateSd3AsBytesSecurityRequirements, + operationName: "CreateStableImageGenerateSd3AsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/generate/sd3", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/png"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + if (request.Mode != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.Mode).HasValue ? (request.Mode).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"mode\""); + + } + if (request.Image != default) + { + + var __contentImage = new global::System.Net.Http.ByteArrayContent(request.Image ?? global::System.Array.Empty()); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + } + if (request.Strength != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Strength, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"strength\""); + + } + if (request.AspectRatio != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.AspectRatio).HasValue ? (request.AspectRatio).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"aspect_ratio\""); + + } + if (request.Model != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.Model).HasValue ? (request.Model).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"model\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + if (request.StylePreset != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.StylePreset).HasValue ? (request.StylePreset).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"style_preset\""); + + } + if (request.NegativePrompt != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty), + name: "\"negative_prompt\""); + + } + if (request.CfgScale != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.CfgScale, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"cfg_scale\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageGenerateSd3AsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageGenerateSd3AsBytes", + methodName: "CreateStableImageGenerateSd3AsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/generate/sd3\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageGenerateSd3AsBytes", + methodName: "CreateStableImageGenerateSd3AsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/generate/sd3\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageGenerateSd3AsBytes", + methodName: "CreateStableImageGenerateSd3AsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/generate/sd3\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageGenerateSd3AsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageGenerateSd3AsBytes", + methodName: "CreateStableImageGenerateSd3AsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/generate/sd3\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageGenerateSd3AsBytes", + methodName: "CreateStableImageGenerateSd3AsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/generate/sd3\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageGenerateSd3Response4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageGenerateSd3Response4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageGenerateSd3Response4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageGenerateSd3Response5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageGenerateSd3Response5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageGenerateSd3Response5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateStableImageGenerateSd3Response6? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateStableImageGenerateSd3Response6.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateStableImageGenerateSd3Response6.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageGenerateSd3Response7? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageGenerateSd3Response7.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageGenerateSd3Response7.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageGenerateSd3Response8? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageGenerateSd3Response8.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageGenerateSd3Response8.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessCreateStableImageGenerateSd3AsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Stable Diffusion 3.5
+ /// Generate using Stable Diffusion 3.5 models, Stability AI latest base model:
+ /// - **Stable Diffusion 3.5 Large**: At 8 billion parameters, with superior quality and
+ /// prompt adherence, this base model is the most powerful in the Stable Diffusion
+ /// family. This model is ideal for professional use cases at 1 megapixel resolution.
+ /// - **Stable Diffusion 3.5 Large Turbo**: A distilled version of Stable Diffusion 3.5 Large.
+ /// SD3.5 Large Turbo generates high-quality images with exceptional prompt adherence
+ /// in just 4 steps, making it considerably faster than Stable Diffusion 3.5 Large.
+ /// - **Stable Diffusion 3.5 Medium**: With 2.5 billion parameters, the model delivers an
+ /// optimal balance between prompt accuracy and image quality, making it an efficient
+ /// choice for fast high-performance image generation.
+ /// - **Stable Diffusion 3.5 Flash**: A distilled version of Stable Diffusion 3.5 Medium.
+ /// SD3.5 Flash generates high-quality images with a 4 step process instead of 40, making
+ /// it faster than Stable Diffusion 3.5 Medium.
+ /// Read more about the model capabilities [here](https://stability.ai/news/introducing-stable-diffusion-3-5).
+ /// As of April 17, 2025, we have deprecated the Stable Diffusion 3.0 APIs and will be automatically
+ /// re-routing calls to Stable Diffusion 3.0 models to Stable Diffusion 3.5 APIs at no extra cost.
+ /// You can read more in the [release notes](/docs/release-notes#api-deprecation-notice).
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/SD3_API.ipynb)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`. The accept header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// #### **Generating with a prompt**
+ /// Commonly referred to as **text-to-image**, this mode generates an image from text alone. While the only required
+ /// parameter is the `prompt`, it also supports an `aspect_ratio` parameter which can be used to control the
+ /// aspect ratio of the generated image.
+ /// #### **Generating with a prompt *and* an image**
+ /// Commonly referred to as **image-to-image**, this mode also generates an image from text but uses an existing image as the
+ /// starting point. The required parameters are:
+ /// - `prompt` - text to generate the image from
+ /// - `image` - the image to use as the starting point for the generation
+ /// - `strength` - controls how much influence the `image` parameter has on the output image
+ /// - `mode` - must be set to `image-to-image`
+ /// > **Note:** maximum request size is 10MiB.
+ /// #### **Optional Parameters:**
+ /// Both modes support the following optional parameters:
+ /// - `model` - the model to use (SD 3.5 Large, SD 3.5 Large Turbo, SD 3.5 Medium, SD 3.5 Flash)
+ /// - `output_format` - the format of the output image
+ /// - `seed` - the randomness seed to use for the generation
+ /// - `negative_prompt` - keywords of what you **do not** wish to see in the output image
+ /// - `cfg_scale` - controls how strictly the diffusion process adheres to the prompt text
+ /// - `style_preset` - guides the image model towards a particular style
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1MP. The default resolution is 1024x1024.
+ /// ### Credits
+ /// - **SD 3.5 Large**: Flat rate of 6.5 credits per successful generation.
+ /// - **SD 3.5 Large Turbo**: Flat rate of 4 credits per successful generation.
+ /// - **SD 3.5 Medium**: Flat rate of 3.5 credits per successful generation.
+ /// - **SD 3.5 Flash**: Flat rate of 2.5 credits per successful generation.
+ /// As always, you will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results. + /// + /// + /// Controls whether this is a text-to-image or image-to-image generation, which affects which parameters are required:
+ /// - **text-to-image** requires only the `prompt` parameter
+ /// - **image-to-image** requires the `prompt`, `image`, and `strength` parameters
+ /// Default Value: text-to-image + /// + /// + /// The image to use as the starting point for the generation.
+ /// Supported formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Supported dimensions:
+ /// - Every side must be at least 64 pixels
+ /// > **Important:** This parameter is only valid for **image-to-image** requests. + /// + /// + /// The image to use as the starting point for the generation.
+ /// Supported formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Supported dimensions:
+ /// - Every side must be at least 64 pixels
+ /// > **Important:** This parameter is only valid for **image-to-image** requests. + /// + /// + /// Sometimes referred to as _denoising_, this parameter controls how much influence the
+ /// `image` parameter has on the generated image. A value of 0 would yield an image that
+ /// is identical to the input. A value of 1 would be as if you passed in no image at all.
+ /// > **Important:** This parameter is only valid for **image-to-image** requests. For SD 3.5 Flash, the
+ /// best results for image-to-image generation are achieved with a `strength` between .94 - .97. + /// + /// + /// Controls the aspect ratio of the generated image. Defaults to 1:1.
+ /// > **Important:** This parameter is only valid for **text-to-image** requests.
+ /// Default Value: 1:1 + /// + /// + /// The model to use for generation.
+ /// - `sd3.5-large` requires 6.5 credits per generation
+ /// - `sd3.5-large-turbo` requires 4 credits per generation
+ /// - `sd3.5-medium` requires 3.5 credits per generation
+ /// - `sd3.5-flash` requires 2.5 credits per generation
+ /// - As of the April 17, 2025, `sd3-large`, `sd3-large-turbo` and `sd3-medium`
+ /// are re-routed to their `sd3.5-[model version]` equivalent, at the same price.
+ /// Default Value: sd3.5-large + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// + /// Keywords of what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// How strictly the diffusion process adheres to the prompt text (higher values keep your image closer to your prompt). The _Large_ and _Medium_ models use a default of `4`. The _Turbo_ and _Flash_ model uses a default of `1`. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + public async global::System.Threading.Tasks.Task CreateStableImageGenerateSd3AsBytesAsync( + string contentType, + string prompt, + global::StabilityAI.CreateStableImageGenerateSd3Accept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.CreateStableImageGenerateSd3RequestMode? mode = default, + byte[]? image = default, + string? imagename = default, + double? strength = default, + global::StabilityAI.CreateStableImageGenerateSd3RequestAspectRatio? aspectRatio = default, + global::StabilityAI.CreateStableImageGenerateSd3RequestModel? model = default, + double? seed = default, + global::StabilityAI.CreateStableImageGenerateSd3RequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageGenerateSd3RequestStylePreset? stylePreset = default, + string? negativePrompt = default, + double? cfgScale = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + var __request = new global::StabilityAI.CreateStableImageGenerateSd3Request + { + Prompt = prompt, + Mode = mode, + Image = image, + Imagename = imagename, + Strength = strength, + AspectRatio = aspectRatio, + Model = model, + Seed = seed, + OutputFormat = outputFormat, + StylePreset = stylePreset, + NegativePrompt = negativePrompt, + CfgScale = cfgScale, + }; + + return await CreateStableImageGenerateSd3AsBytesAsync( + contentType: contentType, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: __request, + requestOptions: requestOptions, + cancellationToken: cancellationToken).ConfigureAwait(false); + } + } +} \ No newline at end of file diff --git a/src/libs/StabilityAI/Generated/StabilityAI.GenerateClient.CreateStableImageGenerateUltra.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.GenerateClient.CreateStableImageGenerateUltra.g.cs index eb40536..7557255 100644 --- a/src/libs/StabilityAI/Generated/StabilityAI.GenerateClient.CreateStableImageGenerateUltra.g.cs +++ b/src/libs/StabilityAI/Generated/StabilityAI.GenerateClient.CreateStableImageGenerateUltra.g.cs @@ -287,6 +287,10 @@ partial void ProcessCreateStableImageGenerateUltraResponseContent( __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || @@ -324,42 +328,6 @@ partial void ProcessCreateStableImageGenerateUltraResponseContent( var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"accept\""); - - } - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } __httpRequestContent.Add( content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), name: "\"prompt\""); diff --git a/src/libs/StabilityAI/Generated/StabilityAI.GenerateClient.CreateStableImageGenerateUltraAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.GenerateClient.CreateStableImageGenerateUltraAsBytes.g.cs new file mode 100644 index 0000000..3206de4 --- /dev/null +++ b/src/libs/StabilityAI/Generated/StabilityAI.GenerateClient.CreateStableImageGenerateUltraAsBytes.g.cs @@ -0,0 +1,1830 @@ + +#nullable enable + +namespace StabilityAI +{ + public partial class GenerateClient + { + + + private static readonly global::StabilityAI.EndPointSecurityRequirement s_CreateStableImageGenerateUltraAsBytesSecurityRequirement0 = + new global::StabilityAI.EndPointSecurityRequirement + { + Authorizations = new global::StabilityAI.EndPointAuthorizationRequirement[] + { new global::StabilityAI.EndPointAuthorizationRequirement + { + Type = "Http", + SchemeId = "HttpBearer", + Location = "Header", + Name = "Bearer", + FriendlyName = "Bearer", + }, + }, + }; + private static readonly global::StabilityAI.EndPointSecurityRequirement[] s_CreateStableImageGenerateUltraAsBytesSecurityRequirements = + new global::StabilityAI.EndPointSecurityRequirement[] + { s_CreateStableImageGenerateUltraAsBytesSecurityRequirement0, + }; + partial void PrepareCreateStableImageGenerateUltraAsBytesArguments( + global::System.Net.Http.HttpClient httpClient, + ref string contentType, + ref global::StabilityAI.CreateStableImageGenerateUltraAccept? accept, + ref string? stabilityClientId, + ref string? stabilityClientUserId, + ref string? stabilityClientVersion, + global::StabilityAI.CreateStableImageGenerateUltraRequest request); + partial void PrepareCreateStableImageGenerateUltraAsBytesRequest( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpRequestMessage httpRequestMessage, + string contentType, + global::StabilityAI.CreateStableImageGenerateUltraAccept? accept, + string? stabilityClientId, + string? stabilityClientUserId, + string? stabilityClientVersion, + global::StabilityAI.CreateStableImageGenerateUltraRequest request); + partial void ProcessCreateStableImageGenerateUltraAsBytesResponse( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpResponseMessage httpResponseMessage); + + partial void ProcessCreateStableImageGenerateUltraAsBytesResponseContent( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpResponseMessage httpResponseMessage, + ref byte[] content); + + /// + /// Stable Image Ultra
+ /// Our most advanced text to image generation service, Stable Image Ultra creates the highest quality images
+ /// with unprecedented prompt understanding. Ultra excels in typography, complex compositions, dynamic lighting,
+ /// vibrant hues, and overall cohesion and structure of an art piece. Made from the most advanced models,
+ /// including Stable Diffusion 3.5, Ultra offers the best of the Stable Diffusion ecosystem.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=yXhs626oZdr1)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`. The accept header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image in the format specified by the `output_format` parameter, but encoded to base64 in a JSON response.
+ /// The only required parameter is the `prompt` field, which should contain the text prompt for the image generation.
+ /// The body of the request should include:
+ /// - `prompt` - text to generate the image from
+ /// The body may optionally include:
+ /// - `image` - the image to use as the starting point for the generation
+ /// - `strength` - controls how much influence the `image` parameter has on the output image
+ /// - `aspect_ratio` - the aspect ratio of the output image
+ /// - `negative_prompt` - keywords of what you **do not** wish to see in the output image
+ /// - `seed` - the randomness seed to use for the generation
+ /// - `output_format` - the format of the output image
+ /// > **Note:** for the full list of optional parameters, please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1 megapixel. The default resolution is 1024x1024.
+ /// ### Credits
+ /// The Ultra service uses 8 credits per successful result. You will not be charged for failed results. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/generate/ultra",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={"none": ''},
+ /// data={
+ /// "prompt": "Lighthouse on a cliff overlooking the ocean",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./lighthouse.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateStableImageGenerateUltraAsBytesAsync( + string contentType, + + global::StabilityAI.CreateStableImageGenerateUltraRequest request, + global::StabilityAI.CreateStableImageGenerateUltraAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + var __response = await CreateStableImageGenerateUltraAsBytesAsResponseAsync( + contentType: contentType, + + request: request, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + requestOptions: requestOptions, + cancellationToken: cancellationToken + ).ConfigureAwait(false); + + return __response.Body; + } + /// + /// Stable Image Ultra
+ /// Our most advanced text to image generation service, Stable Image Ultra creates the highest quality images
+ /// with unprecedented prompt understanding. Ultra excels in typography, complex compositions, dynamic lighting,
+ /// vibrant hues, and overall cohesion and structure of an art piece. Made from the most advanced models,
+ /// including Stable Diffusion 3.5, Ultra offers the best of the Stable Diffusion ecosystem.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=yXhs626oZdr1)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`. The accept header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image in the format specified by the `output_format` parameter, but encoded to base64 in a JSON response.
+ /// The only required parameter is the `prompt` field, which should contain the text prompt for the image generation.
+ /// The body of the request should include:
+ /// - `prompt` - text to generate the image from
+ /// The body may optionally include:
+ /// - `image` - the image to use as the starting point for the generation
+ /// - `strength` - controls how much influence the `image` parameter has on the output image
+ /// - `aspect_ratio` - the aspect ratio of the output image
+ /// - `negative_prompt` - keywords of what you **do not** wish to see in the output image
+ /// - `seed` - the randomness seed to use for the generation
+ /// - `output_format` - the format of the output image
+ /// > **Note:** for the full list of optional parameters, please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1 megapixel. The default resolution is 1024x1024.
+ /// ### Credits
+ /// The Ultra service uses 8 credits per successful result. You will not be charged for failed results. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/generate/ultra",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={"none": ''},
+ /// data={
+ /// "prompt": "Lighthouse on a cliff overlooking the ocean",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./lighthouse.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateStableImageGenerateUltraAsBytesAsStreamAsync( + string contentType, + + global::StabilityAI.CreateStableImageGenerateUltraRequest request, + global::StabilityAI.CreateStableImageGenerateUltraAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + request = request ?? throw new global::System.ArgumentNullException(nameof(request)); + + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageGenerateUltraAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageGenerateUltraAsBytesSecurityRequirements, + operationName: "CreateStableImageGenerateUltraAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/generate/ultra", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/jpeg"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + if (request.NegativePrompt != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty), + name: "\"negative_prompt\""); + + } + if (request.AspectRatio != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.AspectRatio).HasValue ? (request.AspectRatio).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"aspect_ratio\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + if (request.Image != default) + { + + var __contentImage = new global::System.Net.Http.ByteArrayContent(request.Image ?? global::System.Array.Empty()); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + } + if (request.StylePreset != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.StylePreset).HasValue ? (request.StylePreset).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"style_preset\""); + + } + if (request.Strength != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Strength, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"strength\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageGenerateUltraAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageGenerateUltraAsBytes", + methodName: "CreateStableImageGenerateUltraAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/generate/ultra\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseHeadersRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageGenerateUltraAsBytes", + methodName: "CreateStableImageGenerateUltraAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/generate/ultra\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageGenerateUltraAsBytes", + methodName: "CreateStableImageGenerateUltraAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/generate/ultra\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + try + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageGenerateUltraAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageGenerateUltraAsBytes", + methodName: "CreateStableImageGenerateUltraAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/generate/ultra\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageGenerateUltraAsBytes", + methodName: "CreateStableImageGenerateUltraAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/generate/ultra\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageGenerateUltraResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageGenerateUltraResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageGenerateUltraResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageGenerateUltraResponse5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageGenerateUltraResponse5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageGenerateUltraResponse5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateStableImageGenerateUltraResponse6? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateStableImageGenerateUltraResponse6.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateStableImageGenerateUltraResponse6.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageGenerateUltraResponse7? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageGenerateUltraResponse7.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageGenerateUltraResponse7.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageGenerateUltraResponse8? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageGenerateUltraResponse8.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageGenerateUltraResponse8.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + try + { + __response.EnsureSuccessStatusCode(); + + var __content = await __response.Content.ReadAsStreamAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.ResponseStream(__response, __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + } + catch + { + __response.Dispose(); + throw; + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Stable Image Ultra
+ /// Our most advanced text to image generation service, Stable Image Ultra creates the highest quality images
+ /// with unprecedented prompt understanding. Ultra excels in typography, complex compositions, dynamic lighting,
+ /// vibrant hues, and overall cohesion and structure of an art piece. Made from the most advanced models,
+ /// including Stable Diffusion 3.5, Ultra offers the best of the Stable Diffusion ecosystem.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=yXhs626oZdr1)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`. The accept header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image in the format specified by the `output_format` parameter, but encoded to base64 in a JSON response.
+ /// The only required parameter is the `prompt` field, which should contain the text prompt for the image generation.
+ /// The body of the request should include:
+ /// - `prompt` - text to generate the image from
+ /// The body may optionally include:
+ /// - `image` - the image to use as the starting point for the generation
+ /// - `strength` - controls how much influence the `image` parameter has on the output image
+ /// - `aspect_ratio` - the aspect ratio of the output image
+ /// - `negative_prompt` - keywords of what you **do not** wish to see in the output image
+ /// - `seed` - the randomness seed to use for the generation
+ /// - `output_format` - the format of the output image
+ /// > **Note:** for the full list of optional parameters, please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1 megapixel. The default resolution is 1024x1024.
+ /// ### Credits
+ /// The Ultra service uses 8 credits per successful result. You will not be charged for failed results. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/generate/ultra",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={"none": ''},
+ /// data={
+ /// "prompt": "Lighthouse on a cliff overlooking the ocean",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./lighthouse.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task> CreateStableImageGenerateUltraAsBytesAsResponseAsync( + string contentType, + + global::StabilityAI.CreateStableImageGenerateUltraRequest request, + global::StabilityAI.CreateStableImageGenerateUltraAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + request = request ?? throw new global::System.ArgumentNullException(nameof(request)); + + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageGenerateUltraAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageGenerateUltraAsBytesSecurityRequirements, + operationName: "CreateStableImageGenerateUltraAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/generate/ultra", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/jpeg"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + if (request.NegativePrompt != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty), + name: "\"negative_prompt\""); + + } + if (request.AspectRatio != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.AspectRatio).HasValue ? (request.AspectRatio).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"aspect_ratio\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + if (request.Image != default) + { + + var __contentImage = new global::System.Net.Http.ByteArrayContent(request.Image ?? global::System.Array.Empty()); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + } + if (request.StylePreset != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.StylePreset).HasValue ? (request.StylePreset).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"style_preset\""); + + } + if (request.Strength != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Strength, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"strength\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageGenerateUltraAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageGenerateUltraAsBytes", + methodName: "CreateStableImageGenerateUltraAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/generate/ultra\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageGenerateUltraAsBytes", + methodName: "CreateStableImageGenerateUltraAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/generate/ultra\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageGenerateUltraAsBytes", + methodName: "CreateStableImageGenerateUltraAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/generate/ultra\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageGenerateUltraAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageGenerateUltraAsBytes", + methodName: "CreateStableImageGenerateUltraAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/generate/ultra\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageGenerateUltraAsBytes", + methodName: "CreateStableImageGenerateUltraAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/generate/ultra\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageGenerateUltraResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageGenerateUltraResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageGenerateUltraResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageGenerateUltraResponse5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageGenerateUltraResponse5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageGenerateUltraResponse5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateStableImageGenerateUltraResponse6? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateStableImageGenerateUltraResponse6.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateStableImageGenerateUltraResponse6.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageGenerateUltraResponse7? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageGenerateUltraResponse7.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageGenerateUltraResponse7.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageGenerateUltraResponse8? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageGenerateUltraResponse8.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageGenerateUltraResponse8.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessCreateStableImageGenerateUltraAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Stable Image Ultra
+ /// Our most advanced text to image generation service, Stable Image Ultra creates the highest quality images
+ /// with unprecedented prompt understanding. Ultra excels in typography, complex compositions, dynamic lighting,
+ /// vibrant hues, and overall cohesion and structure of an art piece. Made from the most advanced models,
+ /// including Stable Diffusion 3.5, Ultra offers the best of the Stable Diffusion ecosystem.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=yXhs626oZdr1)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`. The accept header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image in the format specified by the `output_format` parameter, but encoded to base64 in a JSON response.
+ /// The only required parameter is the `prompt` field, which should contain the text prompt for the image generation.
+ /// The body of the request should include:
+ /// - `prompt` - text to generate the image from
+ /// The body may optionally include:
+ /// - `image` - the image to use as the starting point for the generation
+ /// - `strength` - controls how much influence the `image` parameter has on the output image
+ /// - `aspect_ratio` - the aspect ratio of the output image
+ /// - `negative_prompt` - keywords of what you **do not** wish to see in the output image
+ /// - `seed` - the randomness seed to use for the generation
+ /// - `output_format` - the format of the output image
+ /// > **Note:** for the full list of optional parameters, please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1 megapixel. The default resolution is 1024x1024.
+ /// ### Credits
+ /// The Ultra service uses 8 credits per successful result. You will not be charged for failed results. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// Controls the aspect ratio of the generated image.
+ /// Default Value: 1:1 + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// The image to use as the starting point for the generation.
+ /// > **Important:** The `strength` parameter is required when `image` is provided.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 64 and 16,384 pixels
+ /// - Height must be between 64 and 16,384 pixels
+ /// - Total pixel count must be at least 4,096 pixels
+ /// Example: ./some/image.png + /// + /// + /// The image to use as the starting point for the generation.
+ /// > **Important:** The `strength` parameter is required when `image` is provided.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 64 and 16,384 pixels
+ /// - Height must be between 64 and 16,384 pixels
+ /// - Total pixel count must be at least 4,096 pixels
+ /// Example: ./some/image.png + /// + /// + /// Guides the image model towards a particular style. + /// + /// + /// Sometimes referred to as _denoising_, this parameter controls how much influence the
+ /// `image` parameter has on the generated image. A value of 0 would yield an image that
+ /// is identical to the input. A value of 1 would be as if you passed in no image at all.
+ /// > **Important:** This parameter is required when `image` is provided. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + public async global::System.Threading.Tasks.Task CreateStableImageGenerateUltraAsBytesAsync( + string contentType, + string prompt, + global::StabilityAI.CreateStableImageGenerateUltraAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + string? negativePrompt = default, + global::StabilityAI.CreateStableImageGenerateUltraRequestAspectRatio? aspectRatio = default, + double? seed = default, + global::StabilityAI.CreateStableImageGenerateUltraRequestOutputFormat? outputFormat = default, + byte[]? image = default, + string? imagename = default, + global::StabilityAI.CreateStableImageGenerateUltraRequestStylePreset? stylePreset = default, + double? strength = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + var __request = new global::StabilityAI.CreateStableImageGenerateUltraRequest + { + Prompt = prompt, + NegativePrompt = negativePrompt, + AspectRatio = aspectRatio, + Seed = seed, + OutputFormat = outputFormat, + Image = image, + Imagename = imagename, + StylePreset = stylePreset, + Strength = strength, + }; + + return await CreateStableImageGenerateUltraAsBytesAsync( + contentType: contentType, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: __request, + requestOptions: requestOptions, + cancellationToken: cancellationToken).ConfigureAwait(false); + } + } +} \ No newline at end of file diff --git a/src/libs/StabilityAI/Generated/StabilityAI.IAudioResultsClient.FetchAudioResultAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.IAudioResultsClient.FetchAudioResultAsBytes.g.cs new file mode 100644 index 0000000..b057e37 --- /dev/null +++ b/src/libs/StabilityAI/Generated/StabilityAI.IAudioResultsClient.FetchAudioResultAsBytes.g.cs @@ -0,0 +1,167 @@ +#nullable enable + +namespace StabilityAI +{ + public partial interface IAudioResultsClient + { + /// + /// Fetch Audio Result
+ /// Fetch the result of an audio generation by ID.
+ /// Poll this endpoint after starting an async audio generation. Returns `202` while
+ /// in-progress, `200` with the audio when complete. + ///
+ /// + /// The `id` of a generation, typically used for async generations, that can be used to check the status of the generation or retrieve the result.
+ /// Example: a6dc6c6e20acda010fe14d71f180658f2896ed9b4ec25aa99a6ff06c796987c4 + /// + /// + /// Specify `audio/*` to receive the bytes of the audio directly. Otherwise specify `application/json` to receive the audio as base64 encoded JSON.
+ /// Default Value: audio/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// generation_id = "e52772ac75b..."
+ /// result = requests.get(
+ /// f"https://api.stability.ai/v2beta/audio/results/{generation_id}",
+ /// headers={"authorization": f"Bearer sk-MYAPIKEY", "accept": "audio/*"},
+ /// )
+ /// if result.status_code == 202:
+ /// print("Generation is still in-progress.")
+ /// elif result.status_code == 200:
+ /// with open("./output.mp3", "wb") as f:
+ /// f.write(result.content)
+ /// print("Download complete!")
+ /// else:
+ /// raise Exception(str(result.json())) + ///
+ global::System.Threading.Tasks.Task FetchAudioResultAsBytesAsync( + string id, + global::StabilityAI.FetchAudioResultAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Fetch Audio Result
+ /// Fetch the result of an audio generation by ID.
+ /// Poll this endpoint after starting an async audio generation. Returns `202` while
+ /// in-progress, `200` with the audio when complete. + ///
+ /// + /// The `id` of a generation, typically used for async generations, that can be used to check the status of the generation or retrieve the result.
+ /// Example: a6dc6c6e20acda010fe14d71f180658f2896ed9b4ec25aa99a6ff06c796987c4 + /// + /// + /// Specify `audio/*` to receive the bytes of the audio directly. Otherwise specify `application/json` to receive the audio as base64 encoded JSON.
+ /// Default Value: audio/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// generation_id = "e52772ac75b..."
+ /// result = requests.get(
+ /// f"https://api.stability.ai/v2beta/audio/results/{generation_id}",
+ /// headers={"authorization": f"Bearer sk-MYAPIKEY", "accept": "audio/*"},
+ /// )
+ /// if result.status_code == 202:
+ /// print("Generation is still in-progress.")
+ /// elif result.status_code == 200:
+ /// with open("./output.mp3", "wb") as f:
+ /// f.write(result.content)
+ /// print("Download complete!")
+ /// else:
+ /// raise Exception(str(result.json())) + ///
+ global::System.Threading.Tasks.Task FetchAudioResultAsBytesAsStreamAsync( + string id, + global::StabilityAI.FetchAudioResultAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Fetch Audio Result
+ /// Fetch the result of an audio generation by ID.
+ /// Poll this endpoint after starting an async audio generation. Returns `202` while
+ /// in-progress, `200` with the audio when complete. + ///
+ /// + /// The `id` of a generation, typically used for async generations, that can be used to check the status of the generation or retrieve the result.
+ /// Example: a6dc6c6e20acda010fe14d71f180658f2896ed9b4ec25aa99a6ff06c796987c4 + /// + /// + /// Specify `audio/*` to receive the bytes of the audio directly. Otherwise specify `application/json` to receive the audio as base64 encoded JSON.
+ /// Default Value: audio/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// generation_id = "e52772ac75b..."
+ /// result = requests.get(
+ /// f"https://api.stability.ai/v2beta/audio/results/{generation_id}",
+ /// headers={"authorization": f"Bearer sk-MYAPIKEY", "accept": "audio/*"},
+ /// )
+ /// if result.status_code == 202:
+ /// print("Generation is still in-progress.")
+ /// elif result.status_code == 200:
+ /// with open("./output.mp3", "wb") as f:
+ /// f.write(result.content)
+ /// print("Download complete!")
+ /// else:
+ /// raise Exception(str(result.json())) + ///
+ global::System.Threading.Tasks.Task> FetchAudioResultAsBytesAsResponseAsync( + string id, + global::StabilityAI.FetchAudioResultAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + } +} \ No newline at end of file diff --git a/src/libs/StabilityAI/Generated/StabilityAI.IControlClient.CreateStableImageControlSketchAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.IControlClient.CreateStableImageControlSketchAsBytes.g.cs new file mode 100644 index 0000000..728346c --- /dev/null +++ b/src/libs/StabilityAI/Generated/StabilityAI.IControlClient.CreateStableImageControlSketchAsBytes.g.cs @@ -0,0 +1,812 @@ +#nullable enable + +namespace StabilityAI +{ + public partial interface IControlClient + { + /// + /// Sketch
+ /// This service offers an ideal solution for design projects that require brainstorming and
+ /// frequent iterations. It upgrades rough hand-drawn sketches to refined outputs with precise
+ /// control. For non-sketch images, it allows detailed manipulation of the final appearance by
+ /// leveraging the contour lines and edges within the image.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=ZKIAqHzJzzUo)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `control_strength`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will match that of the input image.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/sketch",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./sketch.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a medieval castle on a hill",
+ /// "control_strength": 0.7,
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./castle.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateStableImageControlSketchAsBytesAsync( + string contentType, + + global::StabilityAI.CreateStableImageControlSketchRequest request, + global::StabilityAI.CreateStableImageControlSketchAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Sketch
+ /// This service offers an ideal solution for design projects that require brainstorming and
+ /// frequent iterations. It upgrades rough hand-drawn sketches to refined outputs with precise
+ /// control. For non-sketch images, it allows detailed manipulation of the final appearance by
+ /// leveraging the contour lines and edges within the image.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=ZKIAqHzJzzUo)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `control_strength`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will match that of the input image.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/sketch",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./sketch.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a medieval castle on a hill",
+ /// "control_strength": 0.7,
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./castle.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateStableImageControlSketchAsBytesAsStreamAsync( + string contentType, + + global::StabilityAI.CreateStableImageControlSketchRequest request, + global::StabilityAI.CreateStableImageControlSketchAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Sketch
+ /// This service offers an ideal solution for design projects that require brainstorming and
+ /// frequent iterations. It upgrades rough hand-drawn sketches to refined outputs with precise
+ /// control. For non-sketch images, it allows detailed manipulation of the final appearance by
+ /// leveraging the contour lines and edges within the image.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=ZKIAqHzJzzUo)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `control_strength`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will match that of the input image.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/sketch",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./sketch.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a medieval castle on a hill",
+ /// "control_strength": 0.7,
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./castle.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task> CreateStableImageControlSketchAsBytesAsResponseAsync( + string contentType, + + global::StabilityAI.CreateStableImageControlSketchRequest request, + global::StabilityAI.CreateStableImageControlSketchAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Sketch
+ /// This service offers an ideal solution for design projects that require brainstorming and
+ /// frequent iterations. It upgrades rough hand-drawn sketches to refined outputs with precise
+ /// control. For non-sketch images, it allows detailed manipulation of the final appearance by
+ /// leveraging the contour lines and edges within the image.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=ZKIAqHzJzzUo)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `control_strength`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will match that of the input image.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Image Dimensions:
+ /// - Every side must be at least 64 pixels
+ /// - The total pixel count cannot exceed 9,437,184 pixels (e.g. 3072x3072, 4096x2304, etc.)
+ /// Image Aspect Ratio:
+ /// - Must be between 1:2.5 and 2.5:1 (i.e. cannot be too tall or too wide)
+ /// Example: ./some/image.png + /// + /// + /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Image Dimensions:
+ /// - Every side must be at least 64 pixels
+ /// - The total pixel count cannot exceed 9,437,184 pixels (e.g. 3072x3072, 4096x2304, etc.)
+ /// Image Aspect Ratio:
+ /// - Must be between 1:2.5 and 2.5:1 (i.e. cannot be too tall or too wide)
+ /// Example: ./some/image.png + /// + /// + /// How much influence, or control, the `image` has on the generation. Represented as a float between 0 and 1, where 0 is the least influence and 1 is the maximum.
+ /// Default Value: 0.7F + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + global::System.Threading.Tasks.Task CreateStableImageControlSketchAsBytesAsync( + string contentType, + string prompt, + byte[] image, + string imagename, + global::StabilityAI.CreateStableImageControlSketchAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + double? controlStrength = default, + string? negativePrompt = default, + double? seed = default, + global::StabilityAI.CreateStableImageControlSketchRequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageControlSketchRequestStylePreset? stylePreset = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + + /// + /// Sketch
+ /// This service offers an ideal solution for design projects that require brainstorming and
+ /// frequent iterations. It upgrades rough hand-drawn sketches to refined outputs with precise
+ /// control. For non-sketch images, it allows detailed manipulation of the final appearance by
+ /// leveraging the contour lines and edges within the image.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=ZKIAqHzJzzUo)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `control_strength`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will match that of the input image.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Image Dimensions:
+ /// - Every side must be at least 64 pixels
+ /// - The total pixel count cannot exceed 9,437,184 pixels (e.g. 3072x3072, 4096x2304, etc.)
+ /// Image Aspect Ratio:
+ /// - Must be between 1:2.5 and 2.5:1 (i.e. cannot be too tall or too wide)
+ /// Example: ./some/image.png + /// + /// + /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Image Dimensions:
+ /// - Every side must be at least 64 pixels
+ /// - The total pixel count cannot exceed 9,437,184 pixels (e.g. 3072x3072, 4096x2304, etc.)
+ /// Image Aspect Ratio:
+ /// - Must be between 1:2.5 and 2.5:1 (i.e. cannot be too tall or too wide)
+ /// Example: ./some/image.png + /// + /// + /// How much influence, or control, the `image` has on the generation. Represented as a float between 0 and 1, where 0 is the least influence and 1 is the maximum.
+ /// Default Value: 0.7F + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/sketch",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./sketch.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a medieval castle on a hill",
+ /// "control_strength": 0.7,
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./castle.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateStableImageControlSketchAsBytesAsync( + string contentType, + string prompt, + global::System.IO.Stream image, + string imagename, + global::StabilityAI.CreateStableImageControlSketchAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + double? controlStrength = default, + string? negativePrompt = default, + double? seed = default, + global::StabilityAI.CreateStableImageControlSketchRequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageControlSketchRequestStylePreset? stylePreset = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Sketch
+ /// This service offers an ideal solution for design projects that require brainstorming and
+ /// frequent iterations. It upgrades rough hand-drawn sketches to refined outputs with precise
+ /// control. For non-sketch images, it allows detailed manipulation of the final appearance by
+ /// leveraging the contour lines and edges within the image.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=ZKIAqHzJzzUo)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `control_strength`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will match that of the input image.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Image Dimensions:
+ /// - Every side must be at least 64 pixels
+ /// - The total pixel count cannot exceed 9,437,184 pixels (e.g. 3072x3072, 4096x2304, etc.)
+ /// Image Aspect Ratio:
+ /// - Must be between 1:2.5 and 2.5:1 (i.e. cannot be too tall or too wide)
+ /// Example: ./some/image.png + /// + /// + /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Image Dimensions:
+ /// - Every side must be at least 64 pixels
+ /// - The total pixel count cannot exceed 9,437,184 pixels (e.g. 3072x3072, 4096x2304, etc.)
+ /// Image Aspect Ratio:
+ /// - Must be between 1:2.5 and 2.5:1 (i.e. cannot be too tall or too wide)
+ /// Example: ./some/image.png + /// + /// + /// How much influence, or control, the `image` has on the generation. Represented as a float between 0 and 1, where 0 is the least influence and 1 is the maximum.
+ /// Default Value: 0.7F + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/sketch",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./sketch.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a medieval castle on a hill",
+ /// "control_strength": 0.7,
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./castle.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateStableImageControlSketchAsBytesAsStreamAsync( + string contentType, + string prompt, + global::System.IO.Stream image, + string imagename, + global::StabilityAI.CreateStableImageControlSketchAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + double? controlStrength = default, + string? negativePrompt = default, + double? seed = default, + global::StabilityAI.CreateStableImageControlSketchRequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageControlSketchRequestStylePreset? stylePreset = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Sketch
+ /// This service offers an ideal solution for design projects that require brainstorming and
+ /// frequent iterations. It upgrades rough hand-drawn sketches to refined outputs with precise
+ /// control. For non-sketch images, it allows detailed manipulation of the final appearance by
+ /// leveraging the contour lines and edges within the image.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=ZKIAqHzJzzUo)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `control_strength`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will match that of the input image.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Image Dimensions:
+ /// - Every side must be at least 64 pixels
+ /// - The total pixel count cannot exceed 9,437,184 pixels (e.g. 3072x3072, 4096x2304, etc.)
+ /// Image Aspect Ratio:
+ /// - Must be between 1:2.5 and 2.5:1 (i.e. cannot be too tall or too wide)
+ /// Example: ./some/image.png + /// + /// + /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Image Dimensions:
+ /// - Every side must be at least 64 pixels
+ /// - The total pixel count cannot exceed 9,437,184 pixels (e.g. 3072x3072, 4096x2304, etc.)
+ /// Image Aspect Ratio:
+ /// - Must be between 1:2.5 and 2.5:1 (i.e. cannot be too tall or too wide)
+ /// Example: ./some/image.png + /// + /// + /// How much influence, or control, the `image` has on the generation. Represented as a float between 0 and 1, where 0 is the least influence and 1 is the maximum.
+ /// Default Value: 0.7F + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/sketch",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./sketch.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a medieval castle on a hill",
+ /// "control_strength": 0.7,
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./castle.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task> CreateStableImageControlSketchAsBytesAsResponseAsync( + string contentType, + string prompt, + global::System.IO.Stream image, + string imagename, + global::StabilityAI.CreateStableImageControlSketchAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + double? controlStrength = default, + string? negativePrompt = default, + double? seed = default, + global::StabilityAI.CreateStableImageControlSketchRequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageControlSketchRequestStylePreset? stylePreset = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + } +} \ No newline at end of file diff --git a/src/libs/StabilityAI/Generated/StabilityAI.IControlClient.CreateStableImageControlStructureAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.IControlClient.CreateStableImageControlStructureAsBytes.g.cs new file mode 100644 index 0000000..a153405 --- /dev/null +++ b/src/libs/StabilityAI/Generated/StabilityAI.IControlClient.CreateStableImageControlStructureAsBytes.g.cs @@ -0,0 +1,805 @@ +#nullable enable + +namespace StabilityAI +{ + public partial interface IControlClient + { + /// + /// Structure
+ /// This service excels in generating images by maintaining the structure of an input image,
+ /// making it especially valuable for advanced content creation scenarios such as recreating
+ /// scenes or rendering characters from models.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=59RaZazXz0AU)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `control_strength`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will match that of the input image.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/structure",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./cat-statue.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a well manicured shrub in an english garden",
+ /// "control_strength": 0.7,
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./shrub-in-a-garden.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateStableImageControlStructureAsBytesAsync( + string contentType, + + global::StabilityAI.CreateStableImageControlStructureRequest request, + global::StabilityAI.CreateStableImageControlStructureAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Structure
+ /// This service excels in generating images by maintaining the structure of an input image,
+ /// making it especially valuable for advanced content creation scenarios such as recreating
+ /// scenes or rendering characters from models.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=59RaZazXz0AU)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `control_strength`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will match that of the input image.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/structure",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./cat-statue.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a well manicured shrub in an english garden",
+ /// "control_strength": 0.7,
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./shrub-in-a-garden.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateStableImageControlStructureAsBytesAsStreamAsync( + string contentType, + + global::StabilityAI.CreateStableImageControlStructureRequest request, + global::StabilityAI.CreateStableImageControlStructureAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Structure
+ /// This service excels in generating images by maintaining the structure of an input image,
+ /// making it especially valuable for advanced content creation scenarios such as recreating
+ /// scenes or rendering characters from models.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=59RaZazXz0AU)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `control_strength`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will match that of the input image.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/structure",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./cat-statue.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a well manicured shrub in an english garden",
+ /// "control_strength": 0.7,
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./shrub-in-a-garden.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task> CreateStableImageControlStructureAsBytesAsResponseAsync( + string contentType, + + global::StabilityAI.CreateStableImageControlStructureRequest request, + global::StabilityAI.CreateStableImageControlStructureAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Structure
+ /// This service excels in generating images by maintaining the structure of an input image,
+ /// making it especially valuable for advanced content creation scenarios such as recreating
+ /// scenes or rendering characters from models.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=59RaZazXz0AU)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `control_strength`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will match that of the input image.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// An image whose structure you wish to use as the foundation for a generation.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// An image whose structure you wish to use as the foundation for a generation.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// How much influence, or control, the `image` has on the generation. Represented as a float between 0 and 1, where 0 is the least influence and 1 is the maximum.
+ /// Default Value: 0.7F + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + global::System.Threading.Tasks.Task CreateStableImageControlStructureAsBytesAsync( + string contentType, + string prompt, + byte[] image, + string imagename, + global::StabilityAI.CreateStableImageControlStructureAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + double? controlStrength = default, + string? negativePrompt = default, + double? seed = default, + global::StabilityAI.CreateStableImageControlStructureRequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageControlStructureRequestStylePreset? stylePreset = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + + /// + /// Structure
+ /// This service excels in generating images by maintaining the structure of an input image,
+ /// making it especially valuable for advanced content creation scenarios such as recreating
+ /// scenes or rendering characters from models.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=59RaZazXz0AU)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `control_strength`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will match that of the input image.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// An image whose structure you wish to use as the foundation for a generation.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// An image whose structure you wish to use as the foundation for a generation.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// How much influence, or control, the `image` has on the generation. Represented as a float between 0 and 1, where 0 is the least influence and 1 is the maximum.
+ /// Default Value: 0.7F + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/structure",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./cat-statue.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a well manicured shrub in an english garden",
+ /// "control_strength": 0.7,
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./shrub-in-a-garden.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateStableImageControlStructureAsBytesAsync( + string contentType, + string prompt, + global::System.IO.Stream image, + string imagename, + global::StabilityAI.CreateStableImageControlStructureAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + double? controlStrength = default, + string? negativePrompt = default, + double? seed = default, + global::StabilityAI.CreateStableImageControlStructureRequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageControlStructureRequestStylePreset? stylePreset = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Structure
+ /// This service excels in generating images by maintaining the structure of an input image,
+ /// making it especially valuable for advanced content creation scenarios such as recreating
+ /// scenes or rendering characters from models.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=59RaZazXz0AU)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `control_strength`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will match that of the input image.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// An image whose structure you wish to use as the foundation for a generation.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// An image whose structure you wish to use as the foundation for a generation.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// How much influence, or control, the `image` has on the generation. Represented as a float between 0 and 1, where 0 is the least influence and 1 is the maximum.
+ /// Default Value: 0.7F + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/structure",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./cat-statue.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a well manicured shrub in an english garden",
+ /// "control_strength": 0.7,
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./shrub-in-a-garden.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateStableImageControlStructureAsBytesAsStreamAsync( + string contentType, + string prompt, + global::System.IO.Stream image, + string imagename, + global::StabilityAI.CreateStableImageControlStructureAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + double? controlStrength = default, + string? negativePrompt = default, + double? seed = default, + global::StabilityAI.CreateStableImageControlStructureRequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageControlStructureRequestStylePreset? stylePreset = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Structure
+ /// This service excels in generating images by maintaining the structure of an input image,
+ /// making it especially valuable for advanced content creation scenarios such as recreating
+ /// scenes or rendering characters from models.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=59RaZazXz0AU)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `control_strength`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will match that of the input image.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// An image whose structure you wish to use as the foundation for a generation.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// An image whose structure you wish to use as the foundation for a generation.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// How much influence, or control, the `image` has on the generation. Represented as a float between 0 and 1, where 0 is the least influence and 1 is the maximum.
+ /// Default Value: 0.7F + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/structure",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./cat-statue.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a well manicured shrub in an english garden",
+ /// "control_strength": 0.7,
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./shrub-in-a-garden.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task> CreateStableImageControlStructureAsBytesAsResponseAsync( + string contentType, + string prompt, + global::System.IO.Stream image, + string imagename, + global::StabilityAI.CreateStableImageControlStructureAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + double? controlStrength = default, + string? negativePrompt = default, + double? seed = default, + global::StabilityAI.CreateStableImageControlStructureRequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageControlStructureRequestStylePreset? stylePreset = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + } +} \ No newline at end of file diff --git a/src/libs/StabilityAI/Generated/StabilityAI.IControlClient.CreateStableImageControlStyleAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.IControlClient.CreateStableImageControlStyleAsBytes.g.cs new file mode 100644 index 0000000..e5f73d5 --- /dev/null +++ b/src/libs/StabilityAI/Generated/StabilityAI.IControlClient.CreateStableImageControlStyleAsBytes.g.cs @@ -0,0 +1,812 @@ +#nullable enable + +namespace StabilityAI +{ + public partial interface IControlClient + { + /// + /// Style Guide
+ /// This service extracts stylistic elements from an input image (control image) and uses it to guide the creation of an output image based on the prompt. The result is a new image in the same style as the control image.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=y0WKjG72RvTE)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `negative_prompt`
+ /// - `aspect_ratio`
+ /// - `fidelity`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1MP. The default resolution is 1024x1024.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/style",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./cinematic-portrait.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a majestic portrait of a chicken",
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./chicken-portrait.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateStableImageControlStyleAsBytesAsync( + string contentType, + + global::StabilityAI.CreateStableImageControlStyleRequest request, + global::StabilityAI.CreateStableImageControlStyleAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Style Guide
+ /// This service extracts stylistic elements from an input image (control image) and uses it to guide the creation of an output image based on the prompt. The result is a new image in the same style as the control image.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=y0WKjG72RvTE)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `negative_prompt`
+ /// - `aspect_ratio`
+ /// - `fidelity`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1MP. The default resolution is 1024x1024.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/style",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./cinematic-portrait.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a majestic portrait of a chicken",
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./chicken-portrait.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateStableImageControlStyleAsBytesAsStreamAsync( + string contentType, + + global::StabilityAI.CreateStableImageControlStyleRequest request, + global::StabilityAI.CreateStableImageControlStyleAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Style Guide
+ /// This service extracts stylistic elements from an input image (control image) and uses it to guide the creation of an output image based on the prompt. The result is a new image in the same style as the control image.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=y0WKjG72RvTE)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `negative_prompt`
+ /// - `aspect_ratio`
+ /// - `fidelity`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1MP. The default resolution is 1024x1024.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/style",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./cinematic-portrait.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a majestic portrait of a chicken",
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./chicken-portrait.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task> CreateStableImageControlStyleAsBytesAsResponseAsync( + string contentType, + + global::StabilityAI.CreateStableImageControlStyleRequest request, + global::StabilityAI.CreateStableImageControlStyleAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Style Guide
+ /// This service extracts stylistic elements from an input image (control image) and uses it to guide the creation of an output image based on the prompt. The result is a new image in the same style as the control image.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=y0WKjG72RvTE)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `negative_prompt`
+ /// - `aspect_ratio`
+ /// - `fidelity`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1MP. The default resolution is 1024x1024.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// An image whose style you wish to use as the foundation for a generation.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// An image whose style you wish to use as the foundation for a generation.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// Controls the aspect ratio of the generated image.
+ /// Default Value: 1:1 + /// + /// + /// How closely the output image's style resembles the input image's style.
+ /// Default Value: 0.5F + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + global::System.Threading.Tasks.Task CreateStableImageControlStyleAsBytesAsync( + string contentType, + string prompt, + byte[] image, + string imagename, + global::StabilityAI.CreateStableImageControlStyleAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + string? negativePrompt = default, + global::StabilityAI.CreateStableImageControlStyleRequestAspectRatio? aspectRatio = default, + double? fidelity = default, + double? seed = default, + global::StabilityAI.CreateStableImageControlStyleRequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageControlStyleRequestStylePreset? stylePreset = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + + /// + /// Style Guide
+ /// This service extracts stylistic elements from an input image (control image) and uses it to guide the creation of an output image based on the prompt. The result is a new image in the same style as the control image.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=y0WKjG72RvTE)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `negative_prompt`
+ /// - `aspect_ratio`
+ /// - `fidelity`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1MP. The default resolution is 1024x1024.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// An image whose style you wish to use as the foundation for a generation.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// An image whose style you wish to use as the foundation for a generation.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// Controls the aspect ratio of the generated image.
+ /// Default Value: 1:1 + /// + /// + /// How closely the output image's style resembles the input image's style.
+ /// Default Value: 0.5F + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/style",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./cinematic-portrait.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a majestic portrait of a chicken",
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./chicken-portrait.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateStableImageControlStyleAsBytesAsync( + string contentType, + string prompt, + global::System.IO.Stream image, + string imagename, + global::StabilityAI.CreateStableImageControlStyleAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + string? negativePrompt = default, + global::StabilityAI.CreateStableImageControlStyleRequestAspectRatio? aspectRatio = default, + double? fidelity = default, + double? seed = default, + global::StabilityAI.CreateStableImageControlStyleRequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageControlStyleRequestStylePreset? stylePreset = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Style Guide
+ /// This service extracts stylistic elements from an input image (control image) and uses it to guide the creation of an output image based on the prompt. The result is a new image in the same style as the control image.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=y0WKjG72RvTE)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `negative_prompt`
+ /// - `aspect_ratio`
+ /// - `fidelity`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1MP. The default resolution is 1024x1024.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// An image whose style you wish to use as the foundation for a generation.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// An image whose style you wish to use as the foundation for a generation.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// Controls the aspect ratio of the generated image.
+ /// Default Value: 1:1 + /// + /// + /// How closely the output image's style resembles the input image's style.
+ /// Default Value: 0.5F + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/style",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./cinematic-portrait.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a majestic portrait of a chicken",
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./chicken-portrait.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateStableImageControlStyleAsBytesAsStreamAsync( + string contentType, + string prompt, + global::System.IO.Stream image, + string imagename, + global::StabilityAI.CreateStableImageControlStyleAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + string? negativePrompt = default, + global::StabilityAI.CreateStableImageControlStyleRequestAspectRatio? aspectRatio = default, + double? fidelity = default, + double? seed = default, + global::StabilityAI.CreateStableImageControlStyleRequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageControlStyleRequestStylePreset? stylePreset = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Style Guide
+ /// This service extracts stylistic elements from an input image (control image) and uses it to guide the creation of an output image based on the prompt. The result is a new image in the same style as the control image.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=y0WKjG72RvTE)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `negative_prompt`
+ /// - `aspect_ratio`
+ /// - `fidelity`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1MP. The default resolution is 1024x1024.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// An image whose style you wish to use as the foundation for a generation.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// An image whose style you wish to use as the foundation for a generation.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// Controls the aspect ratio of the generated image.
+ /// Default Value: 1:1 + /// + /// + /// How closely the output image's style resembles the input image's style.
+ /// Default Value: 0.5F + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/style",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./cinematic-portrait.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a majestic portrait of a chicken",
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./chicken-portrait.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task> CreateStableImageControlStyleAsBytesAsResponseAsync( + string contentType, + string prompt, + global::System.IO.Stream image, + string imagename, + global::StabilityAI.CreateStableImageControlStyleAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + string? negativePrompt = default, + global::StabilityAI.CreateStableImageControlStyleRequestAspectRatio? aspectRatio = default, + double? fidelity = default, + double? seed = default, + global::StabilityAI.CreateStableImageControlStyleRequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageControlStyleRequestStylePreset? stylePreset = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + } +} \ No newline at end of file diff --git a/src/libs/StabilityAI/Generated/StabilityAI.IControlClient.CreateStableImageControlStyleTransferAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.IControlClient.CreateStableImageControlStyleTransferAsBytes.g.cs new file mode 100644 index 0000000..4087900 --- /dev/null +++ b/src/libs/StabilityAI/Generated/StabilityAI.IControlClient.CreateStableImageControlStyleTransferAsBytes.g.cs @@ -0,0 +1,978 @@ +#nullable enable + +namespace StabilityAI +{ + public partial interface IControlClient + { + /// + /// Style Transfer
+ /// Style Transfer applies visual characteristics from reference style images to target images.
+ /// While Style Guide extracts stylistic elements from an input image (control image) and uses it
+ /// to guide the creation of an output image based on the prompt, Style Transfer specifically
+ /// transforms existing content while preserving the original composition.
+ /// This tool helps create consistent content across multiple assets.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to
+ /// [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=YCrxdv5LzqJ9)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `init_image`
+ /// - `style_image`
+ /// The body may optionally include:
+ /// - `prompt`
+ /// - `negative_prompt`
+ /// - `style_strength`
+ /// - `composition_fidelity`
+ /// - `change_strength`
+ /// - `seed`
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1MP, with the same aspect ratio as the `init_image`.
+ /// ### Credits
+ /// Flat rate of 8 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/style-transfer",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "init_image": open("./chicken-portrait.png", "rb"),
+ /// "style_image": open("./glowbot.png", "rb")
+ /// },
+ /// data={
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./glow-chicken.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateStableImageControlStyleTransferAsBytesAsync( + string contentType, + + global::StabilityAI.CreateStableImageControlStyleTransferRequest request, + global::StabilityAI.CreateStableImageControlStyleTransferAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Style Transfer
+ /// Style Transfer applies visual characteristics from reference style images to target images.
+ /// While Style Guide extracts stylistic elements from an input image (control image) and uses it
+ /// to guide the creation of an output image based on the prompt, Style Transfer specifically
+ /// transforms existing content while preserving the original composition.
+ /// This tool helps create consistent content across multiple assets.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to
+ /// [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=YCrxdv5LzqJ9)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `init_image`
+ /// - `style_image`
+ /// The body may optionally include:
+ /// - `prompt`
+ /// - `negative_prompt`
+ /// - `style_strength`
+ /// - `composition_fidelity`
+ /// - `change_strength`
+ /// - `seed`
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1MP, with the same aspect ratio as the `init_image`.
+ /// ### Credits
+ /// Flat rate of 8 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/style-transfer",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "init_image": open("./chicken-portrait.png", "rb"),
+ /// "style_image": open("./glowbot.png", "rb")
+ /// },
+ /// data={
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./glow-chicken.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateStableImageControlStyleTransferAsBytesAsStreamAsync( + string contentType, + + global::StabilityAI.CreateStableImageControlStyleTransferRequest request, + global::StabilityAI.CreateStableImageControlStyleTransferAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Style Transfer
+ /// Style Transfer applies visual characteristics from reference style images to target images.
+ /// While Style Guide extracts stylistic elements from an input image (control image) and uses it
+ /// to guide the creation of an output image based on the prompt, Style Transfer specifically
+ /// transforms existing content while preserving the original composition.
+ /// This tool helps create consistent content across multiple assets.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to
+ /// [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=YCrxdv5LzqJ9)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `init_image`
+ /// - `style_image`
+ /// The body may optionally include:
+ /// - `prompt`
+ /// - `negative_prompt`
+ /// - `style_strength`
+ /// - `composition_fidelity`
+ /// - `change_strength`
+ /// - `seed`
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1MP, with the same aspect ratio as the `init_image`.
+ /// ### Credits
+ /// Flat rate of 8 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/style-transfer",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "init_image": open("./chicken-portrait.png", "rb"),
+ /// "style_image": open("./glowbot.png", "rb")
+ /// },
+ /// data={
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./glow-chicken.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task> CreateStableImageControlStyleTransferAsBytesAsResponseAsync( + string contentType, + + global::StabilityAI.CreateStableImageControlStyleTransferRequest request, + global::StabilityAI.CreateStableImageControlStyleTransferAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Style Transfer
+ /// Style Transfer applies visual characteristics from reference style images to target images.
+ /// While Style Guide extracts stylistic elements from an input image (control image) and uses it
+ /// to guide the creation of an output image based on the prompt, Style Transfer specifically
+ /// transforms existing content while preserving the original composition.
+ /// This tool helps create consistent content across multiple assets.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to
+ /// [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=YCrxdv5LzqJ9)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `init_image`
+ /// - `style_image`
+ /// The body may optionally include:
+ /// - `prompt`
+ /// - `negative_prompt`
+ /// - `style_strength`
+ /// - `composition_fidelity`
+ /// - `change_strength`
+ /// - `seed`
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1MP, with the same aspect ratio as the `init_image`.
+ /// ### Credits
+ /// Flat rate of 8 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// An image containing the subject you wish to restyle.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 64 and 16,383 pixels
+ /// - Height must be between 64 and 16,383 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// An image containing the subject you wish to restyle.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 64 and 16,383 pixels
+ /// - Height must be between 64 and 16,383 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// An image containing the new style.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 64 and 16,383 pixels
+ /// - Height must be between 64 and 16,383 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png + /// + /// + /// An image containing the new style.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 64 and 16,383 pixels
+ /// - Height must be between 64 and 16,383 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Sometimes referred to as _denoising_, this parameter controls how much influence the
+ /// `style_image` parameter has on the generated image. A value of 0 would yield an image that
+ /// is identical to the input. A value of 1 would be as if you passed in no image at all.
+ /// Default Value: 1 + /// + /// + /// How closely the output image's style resembles the input image's style.
+ /// Default Value: 0.9F + /// + /// + /// How much the original image should change
+ /// Default Value: 0.9F + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + global::System.Threading.Tasks.Task CreateStableImageControlStyleTransferAsBytesAsync( + string contentType, + byte[] initImage, + string initImagename, + byte[] styleImage, + string styleImagename, + global::StabilityAI.CreateStableImageControlStyleTransferAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + string? prompt = default, + string? negativePrompt = default, + double? seed = default, + double? styleStrength = default, + double? compositionFidelity = default, + double? changeStrength = default, + global::StabilityAI.CreateStableImageControlStyleTransferRequestOutputFormat? outputFormat = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + + /// + /// Style Transfer
+ /// Style Transfer applies visual characteristics from reference style images to target images.
+ /// While Style Guide extracts stylistic elements from an input image (control image) and uses it
+ /// to guide the creation of an output image based on the prompt, Style Transfer specifically
+ /// transforms existing content while preserving the original composition.
+ /// This tool helps create consistent content across multiple assets.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to
+ /// [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=YCrxdv5LzqJ9)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `init_image`
+ /// - `style_image`
+ /// The body may optionally include:
+ /// - `prompt`
+ /// - `negative_prompt`
+ /// - `style_strength`
+ /// - `composition_fidelity`
+ /// - `change_strength`
+ /// - `seed`
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1MP, with the same aspect ratio as the `init_image`.
+ /// ### Credits
+ /// Flat rate of 8 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// An image containing the subject you wish to restyle.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 64 and 16,383 pixels
+ /// - Height must be between 64 and 16,383 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// An image containing the subject you wish to restyle.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 64 and 16,383 pixels
+ /// - Height must be between 64 and 16,383 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// An image containing the new style.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 64 and 16,383 pixels
+ /// - Height must be between 64 and 16,383 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png + /// + /// + /// An image containing the new style.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 64 and 16,383 pixels
+ /// - Height must be between 64 and 16,383 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Sometimes referred to as _denoising_, this parameter controls how much influence the
+ /// `style_image` parameter has on the generated image. A value of 0 would yield an image that
+ /// is identical to the input. A value of 1 would be as if you passed in no image at all.
+ /// Default Value: 1 + /// + /// + /// How closely the output image's style resembles the input image's style.
+ /// Default Value: 0.9F + /// + /// + /// How much the original image should change
+ /// Default Value: 0.9F + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/style-transfer",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "init_image": open("./chicken-portrait.png", "rb"),
+ /// "style_image": open("./glowbot.png", "rb")
+ /// },
+ /// data={
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./glow-chicken.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateStableImageControlStyleTransferAsBytesAsync( + string contentType, + global::System.IO.Stream initImage, + string initImagename, + global::System.IO.Stream styleImage, + string styleImagename, + global::StabilityAI.CreateStableImageControlStyleTransferAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + string? prompt = default, + string? negativePrompt = default, + double? seed = default, + double? styleStrength = default, + double? compositionFidelity = default, + double? changeStrength = default, + global::StabilityAI.CreateStableImageControlStyleTransferRequestOutputFormat? outputFormat = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Style Transfer
+ /// Style Transfer applies visual characteristics from reference style images to target images.
+ /// While Style Guide extracts stylistic elements from an input image (control image) and uses it
+ /// to guide the creation of an output image based on the prompt, Style Transfer specifically
+ /// transforms existing content while preserving the original composition.
+ /// This tool helps create consistent content across multiple assets.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to
+ /// [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=YCrxdv5LzqJ9)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `init_image`
+ /// - `style_image`
+ /// The body may optionally include:
+ /// - `prompt`
+ /// - `negative_prompt`
+ /// - `style_strength`
+ /// - `composition_fidelity`
+ /// - `change_strength`
+ /// - `seed`
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1MP, with the same aspect ratio as the `init_image`.
+ /// ### Credits
+ /// Flat rate of 8 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// An image containing the subject you wish to restyle.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 64 and 16,383 pixels
+ /// - Height must be between 64 and 16,383 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// An image containing the subject you wish to restyle.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 64 and 16,383 pixels
+ /// - Height must be between 64 and 16,383 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// An image containing the new style.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 64 and 16,383 pixels
+ /// - Height must be between 64 and 16,383 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png + /// + /// + /// An image containing the new style.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 64 and 16,383 pixels
+ /// - Height must be between 64 and 16,383 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Sometimes referred to as _denoising_, this parameter controls how much influence the
+ /// `style_image` parameter has on the generated image. A value of 0 would yield an image that
+ /// is identical to the input. A value of 1 would be as if you passed in no image at all.
+ /// Default Value: 1 + /// + /// + /// How closely the output image's style resembles the input image's style.
+ /// Default Value: 0.9F + /// + /// + /// How much the original image should change
+ /// Default Value: 0.9F + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/style-transfer",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "init_image": open("./chicken-portrait.png", "rb"),
+ /// "style_image": open("./glowbot.png", "rb")
+ /// },
+ /// data={
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./glow-chicken.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateStableImageControlStyleTransferAsBytesAsStreamAsync( + string contentType, + global::System.IO.Stream initImage, + string initImagename, + global::System.IO.Stream styleImage, + string styleImagename, + global::StabilityAI.CreateStableImageControlStyleTransferAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + string? prompt = default, + string? negativePrompt = default, + double? seed = default, + double? styleStrength = default, + double? compositionFidelity = default, + double? changeStrength = default, + global::StabilityAI.CreateStableImageControlStyleTransferRequestOutputFormat? outputFormat = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Style Transfer
+ /// Style Transfer applies visual characteristics from reference style images to target images.
+ /// While Style Guide extracts stylistic elements from an input image (control image) and uses it
+ /// to guide the creation of an output image based on the prompt, Style Transfer specifically
+ /// transforms existing content while preserving the original composition.
+ /// This tool helps create consistent content across multiple assets.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to
+ /// [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=YCrxdv5LzqJ9)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `init_image`
+ /// - `style_image`
+ /// The body may optionally include:
+ /// - `prompt`
+ /// - `negative_prompt`
+ /// - `style_strength`
+ /// - `composition_fidelity`
+ /// - `change_strength`
+ /// - `seed`
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1MP, with the same aspect ratio as the `init_image`.
+ /// ### Credits
+ /// Flat rate of 8 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// An image containing the subject you wish to restyle.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 64 and 16,383 pixels
+ /// - Height must be between 64 and 16,383 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// An image containing the subject you wish to restyle.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 64 and 16,383 pixels
+ /// - Height must be between 64 and 16,383 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// An image containing the new style.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 64 and 16,383 pixels
+ /// - Height must be between 64 and 16,383 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png + /// + /// + /// An image containing the new style.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 64 and 16,383 pixels
+ /// - Height must be between 64 and 16,383 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Sometimes referred to as _denoising_, this parameter controls how much influence the
+ /// `style_image` parameter has on the generated image. A value of 0 would yield an image that
+ /// is identical to the input. A value of 1 would be as if you passed in no image at all.
+ /// Default Value: 1 + /// + /// + /// How closely the output image's style resembles the input image's style.
+ /// Default Value: 0.9F + /// + /// + /// How much the original image should change
+ /// Default Value: 0.9F + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/style-transfer",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "init_image": open("./chicken-portrait.png", "rb"),
+ /// "style_image": open("./glowbot.png", "rb")
+ /// },
+ /// data={
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./glow-chicken.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task> CreateStableImageControlStyleTransferAsBytesAsResponseAsync( + string contentType, + global::System.IO.Stream initImage, + string initImagename, + global::System.IO.Stream styleImage, + string styleImagename, + global::StabilityAI.CreateStableImageControlStyleTransferAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + string? prompt = default, + string? negativePrompt = default, + double? seed = default, + double? styleStrength = default, + double? compositionFidelity = default, + double? changeStrength = default, + global::StabilityAI.CreateStableImageControlStyleTransferRequestOutputFormat? outputFormat = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + } +} \ No newline at end of file diff --git a/src/libs/StabilityAI/Generated/StabilityAI.IEditClient.CreateStableImageEditEraseAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.IEditClient.CreateStableImageEditEraseAsBytes.g.cs new file mode 100644 index 0000000..27ea1c7 --- /dev/null +++ b/src/libs/StabilityAI/Generated/StabilityAI.IEditClient.CreateStableImageEditEraseAsBytes.g.cs @@ -0,0 +1,841 @@ +#nullable enable + +namespace StabilityAI +{ + public partial interface IEditClient + { + /// + /// Erase
+ /// The Erase service removes unwanted objects, such as blemishes on portraits or items on desks, using image masks.
+ /// The mask is provided in one of two ways:
+ /// 1. Explicitly passing in a separate image via the `mask` parameter
+ /// 2. Derived from the alpha channel of the `image` parameter.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// Optionally, the body of the request may also include:
+ /// - `mask`
+ /// - `seed`
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/erase",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./kangaroo-on-the-beach.png", "rb"),
+ /// "mask": open("./mask-of-kangaroo.png", "rb"),
+ /// },
+ /// data={
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./just-the-beach.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateStableImageEditEraseAsBytesAsync( + string contentType, + + global::StabilityAI.CreateStableImageEditEraseRequest request, + global::StabilityAI.CreateStableImageEditEraseAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Erase
+ /// The Erase service removes unwanted objects, such as blemishes on portraits or items on desks, using image masks.
+ /// The mask is provided in one of two ways:
+ /// 1. Explicitly passing in a separate image via the `mask` parameter
+ /// 2. Derived from the alpha channel of the `image` parameter.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// Optionally, the body of the request may also include:
+ /// - `mask`
+ /// - `seed`
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/erase",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./kangaroo-on-the-beach.png", "rb"),
+ /// "mask": open("./mask-of-kangaroo.png", "rb"),
+ /// },
+ /// data={
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./just-the-beach.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateStableImageEditEraseAsBytesAsStreamAsync( + string contentType, + + global::StabilityAI.CreateStableImageEditEraseRequest request, + global::StabilityAI.CreateStableImageEditEraseAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Erase
+ /// The Erase service removes unwanted objects, such as blemishes on portraits or items on desks, using image masks.
+ /// The mask is provided in one of two ways:
+ /// 1. Explicitly passing in a separate image via the `mask` parameter
+ /// 2. Derived from the alpha channel of the `image` parameter.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// Optionally, the body of the request may also include:
+ /// - `mask`
+ /// - `seed`
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/erase",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./kangaroo-on-the-beach.png", "rb"),
+ /// "mask": open("./mask-of-kangaroo.png", "rb"),
+ /// },
+ /// data={
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./just-the-beach.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task> CreateStableImageEditEraseAsBytesAsResponseAsync( + string contentType, + + global::StabilityAI.CreateStableImageEditEraseRequest request, + global::StabilityAI.CreateStableImageEditEraseAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Erase
+ /// The Erase service removes unwanted objects, such as blemishes on portraits or items on desks, using image masks.
+ /// The mask is provided in one of two ways:
+ /// 1. Explicitly passing in a separate image via the `mask` parameter
+ /// 2. Derived from the alpha channel of the `image` parameter.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// Optionally, the body of the request may also include:
+ /// - `mask`
+ /// - `seed`
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// The image you wish to erase from.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png + /// + /// + /// The image you wish to erase from.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png + /// + /// + /// Controls the strength of the inpainting process on a per-pixel basis, either via a
+ /// second image (passed into this parameter) or via the alpha channel of the `image` parameter.
+ /// **Passing in a Mask**
+ /// The image passed to this parameter should be a black and white image that represents,
+ /// at any pixel, the strength of inpainting based on how dark or light the given pixel is.
+ /// Completely black pixels represent no inpainting strength while completely white pixels
+ /// represent maximum strength.
+ /// In the event the mask is a different size than the `image` parameter, it will be automatically resized.
+ /// **Alpha Channel Support**
+ /// If you don't provide an explicit mask, one will be derived from the alpha channel of the `image` parameter.
+ /// Transparent pixels will be inpainted while opaque pixels will be preserved.
+ /// In the event an `image` with an alpha channel is provided along with a `mask`, the `mask` will take precedence.
+ /// Example: ./some/image.png + /// + /// + /// Controls the strength of the inpainting process on a per-pixel basis, either via a
+ /// second image (passed into this parameter) or via the alpha channel of the `image` parameter.
+ /// **Passing in a Mask**
+ /// The image passed to this parameter should be a black and white image that represents,
+ /// at any pixel, the strength of inpainting based on how dark or light the given pixel is.
+ /// Completely black pixels represent no inpainting strength while completely white pixels
+ /// represent maximum strength.
+ /// In the event the mask is a different size than the `image` parameter, it will be automatically resized.
+ /// **Alpha Channel Support**
+ /// If you don't provide an explicit mask, one will be derived from the alpha channel of the `image` parameter.
+ /// Transparent pixels will be inpainted while opaque pixels will be preserved.
+ /// In the event an `image` with an alpha channel is provided along with a `mask`, the `mask` will take precedence.
+ /// Example: ./some/image.png + /// + /// + /// Grows the edges of the mask outward in all directions by the specified number of pixels. The expanded area around the mask will be blurred, which can help smooth the transition between inpainted content and the original image.
+ /// Try this parameter if you notice seams or rough edges around the inpainted content.
+ /// > Note: Excessive growth may obscure fine details in the mask and/or merge nearby masked regions.
+ /// Default Value: 5 + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + global::System.Threading.Tasks.Task CreateStableImageEditEraseAsBytesAsync( + string contentType, + byte[] image, + string imagename, + global::StabilityAI.CreateStableImageEditEraseAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + byte[]? mask = default, + string? maskname = default, + double? growMask = default, + double? seed = default, + global::StabilityAI.CreateStableImageEditEraseRequestOutputFormat? outputFormat = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + + /// + /// Erase
+ /// The Erase service removes unwanted objects, such as blemishes on portraits or items on desks, using image masks.
+ /// The mask is provided in one of two ways:
+ /// 1. Explicitly passing in a separate image via the `mask` parameter
+ /// 2. Derived from the alpha channel of the `image` parameter.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// Optionally, the body of the request may also include:
+ /// - `mask`
+ /// - `seed`
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// The image you wish to erase from.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png + /// + /// + /// The image you wish to erase from.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png + /// + /// + /// Controls the strength of the inpainting process on a per-pixel basis, either via a
+ /// second image (passed into this parameter) or via the alpha channel of the `image` parameter.
+ /// **Passing in a Mask**
+ /// The image passed to this parameter should be a black and white image that represents,
+ /// at any pixel, the strength of inpainting based on how dark or light the given pixel is.
+ /// Completely black pixels represent no inpainting strength while completely white pixels
+ /// represent maximum strength.
+ /// In the event the mask is a different size than the `image` parameter, it will be automatically resized.
+ /// **Alpha Channel Support**
+ /// If you don't provide an explicit mask, one will be derived from the alpha channel of the `image` parameter.
+ /// Transparent pixels will be inpainted while opaque pixels will be preserved.
+ /// In the event an `image` with an alpha channel is provided along with a `mask`, the `mask` will take precedence.
+ /// Example: ./some/image.png + /// + /// + /// Controls the strength of the inpainting process on a per-pixel basis, either via a
+ /// second image (passed into this parameter) or via the alpha channel of the `image` parameter.
+ /// **Passing in a Mask**
+ /// The image passed to this parameter should be a black and white image that represents,
+ /// at any pixel, the strength of inpainting based on how dark or light the given pixel is.
+ /// Completely black pixels represent no inpainting strength while completely white pixels
+ /// represent maximum strength.
+ /// In the event the mask is a different size than the `image` parameter, it will be automatically resized.
+ /// **Alpha Channel Support**
+ /// If you don't provide an explicit mask, one will be derived from the alpha channel of the `image` parameter.
+ /// Transparent pixels will be inpainted while opaque pixels will be preserved.
+ /// In the event an `image` with an alpha channel is provided along with a `mask`, the `mask` will take precedence.
+ /// Example: ./some/image.png + /// + /// + /// Grows the edges of the mask outward in all directions by the specified number of pixels. The expanded area around the mask will be blurred, which can help smooth the transition between inpainted content and the original image.
+ /// Try this parameter if you notice seams or rough edges around the inpainted content.
+ /// > Note: Excessive growth may obscure fine details in the mask and/or merge nearby masked regions.
+ /// Default Value: 5 + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/erase",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./kangaroo-on-the-beach.png", "rb"),
+ /// "mask": open("./mask-of-kangaroo.png", "rb"),
+ /// },
+ /// data={
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./just-the-beach.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateStableImageEditEraseAsBytesAsync( + string contentType, + global::System.IO.Stream image, + string imagename, + global::StabilityAI.CreateStableImageEditEraseAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::System.IO.Stream? mask = default, + string? maskname = default, + double? growMask = default, + double? seed = default, + global::StabilityAI.CreateStableImageEditEraseRequestOutputFormat? outputFormat = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Erase
+ /// The Erase service removes unwanted objects, such as blemishes on portraits or items on desks, using image masks.
+ /// The mask is provided in one of two ways:
+ /// 1. Explicitly passing in a separate image via the `mask` parameter
+ /// 2. Derived from the alpha channel of the `image` parameter.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// Optionally, the body of the request may also include:
+ /// - `mask`
+ /// - `seed`
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// The image you wish to erase from.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png + /// + /// + /// The image you wish to erase from.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png + /// + /// + /// Controls the strength of the inpainting process on a per-pixel basis, either via a
+ /// second image (passed into this parameter) or via the alpha channel of the `image` parameter.
+ /// **Passing in a Mask**
+ /// The image passed to this parameter should be a black and white image that represents,
+ /// at any pixel, the strength of inpainting based on how dark or light the given pixel is.
+ /// Completely black pixels represent no inpainting strength while completely white pixels
+ /// represent maximum strength.
+ /// In the event the mask is a different size than the `image` parameter, it will be automatically resized.
+ /// **Alpha Channel Support**
+ /// If you don't provide an explicit mask, one will be derived from the alpha channel of the `image` parameter.
+ /// Transparent pixels will be inpainted while opaque pixels will be preserved.
+ /// In the event an `image` with an alpha channel is provided along with a `mask`, the `mask` will take precedence.
+ /// Example: ./some/image.png + /// + /// + /// Controls the strength of the inpainting process on a per-pixel basis, either via a
+ /// second image (passed into this parameter) or via the alpha channel of the `image` parameter.
+ /// **Passing in a Mask**
+ /// The image passed to this parameter should be a black and white image that represents,
+ /// at any pixel, the strength of inpainting based on how dark or light the given pixel is.
+ /// Completely black pixels represent no inpainting strength while completely white pixels
+ /// represent maximum strength.
+ /// In the event the mask is a different size than the `image` parameter, it will be automatically resized.
+ /// **Alpha Channel Support**
+ /// If you don't provide an explicit mask, one will be derived from the alpha channel of the `image` parameter.
+ /// Transparent pixels will be inpainted while opaque pixels will be preserved.
+ /// In the event an `image` with an alpha channel is provided along with a `mask`, the `mask` will take precedence.
+ /// Example: ./some/image.png + /// + /// + /// Grows the edges of the mask outward in all directions by the specified number of pixels. The expanded area around the mask will be blurred, which can help smooth the transition between inpainted content and the original image.
+ /// Try this parameter if you notice seams or rough edges around the inpainted content.
+ /// > Note: Excessive growth may obscure fine details in the mask and/or merge nearby masked regions.
+ /// Default Value: 5 + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/erase",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./kangaroo-on-the-beach.png", "rb"),
+ /// "mask": open("./mask-of-kangaroo.png", "rb"),
+ /// },
+ /// data={
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./just-the-beach.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateStableImageEditEraseAsBytesAsStreamAsync( + string contentType, + global::System.IO.Stream image, + string imagename, + global::StabilityAI.CreateStableImageEditEraseAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::System.IO.Stream? mask = default, + string? maskname = default, + double? growMask = default, + double? seed = default, + global::StabilityAI.CreateStableImageEditEraseRequestOutputFormat? outputFormat = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Erase
+ /// The Erase service removes unwanted objects, such as blemishes on portraits or items on desks, using image masks.
+ /// The mask is provided in one of two ways:
+ /// 1. Explicitly passing in a separate image via the `mask` parameter
+ /// 2. Derived from the alpha channel of the `image` parameter.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// Optionally, the body of the request may also include:
+ /// - `mask`
+ /// - `seed`
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// The image you wish to erase from.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png + /// + /// + /// The image you wish to erase from.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png + /// + /// + /// Controls the strength of the inpainting process on a per-pixel basis, either via a
+ /// second image (passed into this parameter) or via the alpha channel of the `image` parameter.
+ /// **Passing in a Mask**
+ /// The image passed to this parameter should be a black and white image that represents,
+ /// at any pixel, the strength of inpainting based on how dark or light the given pixel is.
+ /// Completely black pixels represent no inpainting strength while completely white pixels
+ /// represent maximum strength.
+ /// In the event the mask is a different size than the `image` parameter, it will be automatically resized.
+ /// **Alpha Channel Support**
+ /// If you don't provide an explicit mask, one will be derived from the alpha channel of the `image` parameter.
+ /// Transparent pixels will be inpainted while opaque pixels will be preserved.
+ /// In the event an `image` with an alpha channel is provided along with a `mask`, the `mask` will take precedence.
+ /// Example: ./some/image.png + /// + /// + /// Controls the strength of the inpainting process on a per-pixel basis, either via a
+ /// second image (passed into this parameter) or via the alpha channel of the `image` parameter.
+ /// **Passing in a Mask**
+ /// The image passed to this parameter should be a black and white image that represents,
+ /// at any pixel, the strength of inpainting based on how dark or light the given pixel is.
+ /// Completely black pixels represent no inpainting strength while completely white pixels
+ /// represent maximum strength.
+ /// In the event the mask is a different size than the `image` parameter, it will be automatically resized.
+ /// **Alpha Channel Support**
+ /// If you don't provide an explicit mask, one will be derived from the alpha channel of the `image` parameter.
+ /// Transparent pixels will be inpainted while opaque pixels will be preserved.
+ /// In the event an `image` with an alpha channel is provided along with a `mask`, the `mask` will take precedence.
+ /// Example: ./some/image.png + /// + /// + /// Grows the edges of the mask outward in all directions by the specified number of pixels. The expanded area around the mask will be blurred, which can help smooth the transition between inpainted content and the original image.
+ /// Try this parameter if you notice seams or rough edges around the inpainted content.
+ /// > Note: Excessive growth may obscure fine details in the mask and/or merge nearby masked regions.
+ /// Default Value: 5 + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/erase",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./kangaroo-on-the-beach.png", "rb"),
+ /// "mask": open("./mask-of-kangaroo.png", "rb"),
+ /// },
+ /// data={
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./just-the-beach.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task> CreateStableImageEditEraseAsBytesAsResponseAsync( + string contentType, + global::System.IO.Stream image, + string imagename, + global::StabilityAI.CreateStableImageEditEraseAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::System.IO.Stream? mask = default, + string? maskname = default, + double? growMask = default, + double? seed = default, + global::StabilityAI.CreateStableImageEditEraseRequestOutputFormat? outputFormat = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + } +} \ No newline at end of file diff --git a/src/libs/StabilityAI/Generated/StabilityAI.IEditClient.CreateStableImageEditInpaintAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.IEditClient.CreateStableImageEditInpaintAsBytes.g.cs new file mode 100644 index 0000000..6abbeff --- /dev/null +++ b/src/libs/StabilityAI/Generated/StabilityAI.IEditClient.CreateStableImageEditInpaintAsBytes.g.cs @@ -0,0 +1,947 @@ +#nullable enable + +namespace StabilityAI +{ + public partial interface IEditClient + { + /// + /// Inpaint
+ /// Intelligently modify images by filling in or replacing specified areas with new content based
+ /// on the content of a "mask" image.
+ /// The "mask" is provided in one of two ways:
+ /// 1. Explicitly passing in a separate image via the `mask` parameter
+ /// 2. Derived from the alpha channel of the `image` parameter.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// - `prompt`
+ /// Optionally, the body of the request may also include:
+ /// - `mask`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/inpaint",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./dog-wearing-vr-goggles.png", "rb"),
+ /// "mask": open("./mask.png", "rb"),
+ /// },
+ /// data={
+ /// "prompt": "dog wearing black glasses",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./dog-wearing-black-glasses.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateStableImageEditInpaintAsBytesAsync( + string contentType, + + global::StabilityAI.CreateStableImageEditInpaintRequest request, + global::StabilityAI.CreateStableImageEditInpaintAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Inpaint
+ /// Intelligently modify images by filling in or replacing specified areas with new content based
+ /// on the content of a "mask" image.
+ /// The "mask" is provided in one of two ways:
+ /// 1. Explicitly passing in a separate image via the `mask` parameter
+ /// 2. Derived from the alpha channel of the `image` parameter.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// - `prompt`
+ /// Optionally, the body of the request may also include:
+ /// - `mask`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/inpaint",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./dog-wearing-vr-goggles.png", "rb"),
+ /// "mask": open("./mask.png", "rb"),
+ /// },
+ /// data={
+ /// "prompt": "dog wearing black glasses",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./dog-wearing-black-glasses.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateStableImageEditInpaintAsBytesAsStreamAsync( + string contentType, + + global::StabilityAI.CreateStableImageEditInpaintRequest request, + global::StabilityAI.CreateStableImageEditInpaintAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Inpaint
+ /// Intelligently modify images by filling in or replacing specified areas with new content based
+ /// on the content of a "mask" image.
+ /// The "mask" is provided in one of two ways:
+ /// 1. Explicitly passing in a separate image via the `mask` parameter
+ /// 2. Derived from the alpha channel of the `image` parameter.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// - `prompt`
+ /// Optionally, the body of the request may also include:
+ /// - `mask`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/inpaint",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./dog-wearing-vr-goggles.png", "rb"),
+ /// "mask": open("./mask.png", "rb"),
+ /// },
+ /// data={
+ /// "prompt": "dog wearing black glasses",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./dog-wearing-black-glasses.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task> CreateStableImageEditInpaintAsBytesAsResponseAsync( + string contentType, + + global::StabilityAI.CreateStableImageEditInpaintRequest request, + global::StabilityAI.CreateStableImageEditInpaintAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Inpaint
+ /// Intelligently modify images by filling in or replacing specified areas with new content based
+ /// on the content of a "mask" image.
+ /// The "mask" is provided in one of two ways:
+ /// 1. Explicitly passing in a separate image via the `mask` parameter
+ /// 2. Derived from the alpha channel of the `image` parameter.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// - `prompt`
+ /// Optionally, the body of the request may also include:
+ /// - `mask`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// The image you wish to inpaint.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png + /// + /// + /// The image you wish to inpaint.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// Controls the strength of the inpainting process on a per-pixel basis, either via a
+ /// second image (passed into this parameter) or via the alpha channel of the `image` parameter.
+ /// **Passing in a Mask**
+ /// The image passed to this parameter should be a black and white image that represents,
+ /// at any pixel, the strength of inpainting based on how dark or light the given pixel is.
+ /// Completely black pixels represent no inpainting strength while completely white pixels
+ /// represent maximum strength.
+ /// In the event the mask is a different size than the `image` parameter, it will be automatically resized.
+ /// **Alpha Channel Support**
+ /// If you don't provide an explicit mask, one will be derived from the alpha channel of the `image` parameter.
+ /// Transparent pixels will be inpainted while opaque pixels will be preserved.
+ /// In the event an `image` with an alpha channel is provided along with a `mask`, the `mask` will take precedence.
+ /// Example: ./some/image.png + /// + /// + /// Controls the strength of the inpainting process on a per-pixel basis, either via a
+ /// second image (passed into this parameter) or via the alpha channel of the `image` parameter.
+ /// **Passing in a Mask**
+ /// The image passed to this parameter should be a black and white image that represents,
+ /// at any pixel, the strength of inpainting based on how dark or light the given pixel is.
+ /// Completely black pixels represent no inpainting strength while completely white pixels
+ /// represent maximum strength.
+ /// In the event the mask is a different size than the `image` parameter, it will be automatically resized.
+ /// **Alpha Channel Support**
+ /// If you don't provide an explicit mask, one will be derived from the alpha channel of the `image` parameter.
+ /// Transparent pixels will be inpainted while opaque pixels will be preserved.
+ /// In the event an `image` with an alpha channel is provided along with a `mask`, the `mask` will take precedence.
+ /// Example: ./some/image.png + /// + /// + /// Grows the edges of the mask outward in all directions by the specified number of pixels. The expanded area around the mask will be blurred, which can help smooth the transition between inpainted content and the original image.
+ /// Try this parameter if you notice seams or rough edges around the inpainted content.
+ /// > Note: Excessive growth may obscure fine details in the mask and/or merge nearby masked regions.
+ /// Default Value: 5 + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + global::System.Threading.Tasks.Task CreateStableImageEditInpaintAsBytesAsync( + string contentType, + byte[] image, + string imagename, + string prompt, + global::StabilityAI.CreateStableImageEditInpaintAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + string? negativePrompt = default, + byte[]? mask = default, + string? maskname = default, + double? growMask = default, + double? seed = default, + global::StabilityAI.CreateStableImageEditInpaintRequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageEditInpaintRequestStylePreset? stylePreset = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + + /// + /// Inpaint
+ /// Intelligently modify images by filling in or replacing specified areas with new content based
+ /// on the content of a "mask" image.
+ /// The "mask" is provided in one of two ways:
+ /// 1. Explicitly passing in a separate image via the `mask` parameter
+ /// 2. Derived from the alpha channel of the `image` parameter.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// - `prompt`
+ /// Optionally, the body of the request may also include:
+ /// - `mask`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// The image you wish to inpaint.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png + /// + /// + /// The image you wish to inpaint.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// Controls the strength of the inpainting process on a per-pixel basis, either via a
+ /// second image (passed into this parameter) or via the alpha channel of the `image` parameter.
+ /// **Passing in a Mask**
+ /// The image passed to this parameter should be a black and white image that represents,
+ /// at any pixel, the strength of inpainting based on how dark or light the given pixel is.
+ /// Completely black pixels represent no inpainting strength while completely white pixels
+ /// represent maximum strength.
+ /// In the event the mask is a different size than the `image` parameter, it will be automatically resized.
+ /// **Alpha Channel Support**
+ /// If you don't provide an explicit mask, one will be derived from the alpha channel of the `image` parameter.
+ /// Transparent pixels will be inpainted while opaque pixels will be preserved.
+ /// In the event an `image` with an alpha channel is provided along with a `mask`, the `mask` will take precedence.
+ /// Example: ./some/image.png + /// + /// + /// Controls the strength of the inpainting process on a per-pixel basis, either via a
+ /// second image (passed into this parameter) or via the alpha channel of the `image` parameter.
+ /// **Passing in a Mask**
+ /// The image passed to this parameter should be a black and white image that represents,
+ /// at any pixel, the strength of inpainting based on how dark or light the given pixel is.
+ /// Completely black pixels represent no inpainting strength while completely white pixels
+ /// represent maximum strength.
+ /// In the event the mask is a different size than the `image` parameter, it will be automatically resized.
+ /// **Alpha Channel Support**
+ /// If you don't provide an explicit mask, one will be derived from the alpha channel of the `image` parameter.
+ /// Transparent pixels will be inpainted while opaque pixels will be preserved.
+ /// In the event an `image` with an alpha channel is provided along with a `mask`, the `mask` will take precedence.
+ /// Example: ./some/image.png + /// + /// + /// Grows the edges of the mask outward in all directions by the specified number of pixels. The expanded area around the mask will be blurred, which can help smooth the transition between inpainted content and the original image.
+ /// Try this parameter if you notice seams or rough edges around the inpainted content.
+ /// > Note: Excessive growth may obscure fine details in the mask and/or merge nearby masked regions.
+ /// Default Value: 5 + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/inpaint",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./dog-wearing-vr-goggles.png", "rb"),
+ /// "mask": open("./mask.png", "rb"),
+ /// },
+ /// data={
+ /// "prompt": "dog wearing black glasses",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./dog-wearing-black-glasses.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateStableImageEditInpaintAsBytesAsync( + string contentType, + global::System.IO.Stream image, + string imagename, + string prompt, + global::StabilityAI.CreateStableImageEditInpaintAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + string? negativePrompt = default, + global::System.IO.Stream? mask = default, + string? maskname = default, + double? growMask = default, + double? seed = default, + global::StabilityAI.CreateStableImageEditInpaintRequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageEditInpaintRequestStylePreset? stylePreset = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Inpaint
+ /// Intelligently modify images by filling in or replacing specified areas with new content based
+ /// on the content of a "mask" image.
+ /// The "mask" is provided in one of two ways:
+ /// 1. Explicitly passing in a separate image via the `mask` parameter
+ /// 2. Derived from the alpha channel of the `image` parameter.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// - `prompt`
+ /// Optionally, the body of the request may also include:
+ /// - `mask`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// The image you wish to inpaint.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png + /// + /// + /// The image you wish to inpaint.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// Controls the strength of the inpainting process on a per-pixel basis, either via a
+ /// second image (passed into this parameter) or via the alpha channel of the `image` parameter.
+ /// **Passing in a Mask**
+ /// The image passed to this parameter should be a black and white image that represents,
+ /// at any pixel, the strength of inpainting based on how dark or light the given pixel is.
+ /// Completely black pixels represent no inpainting strength while completely white pixels
+ /// represent maximum strength.
+ /// In the event the mask is a different size than the `image` parameter, it will be automatically resized.
+ /// **Alpha Channel Support**
+ /// If you don't provide an explicit mask, one will be derived from the alpha channel of the `image` parameter.
+ /// Transparent pixels will be inpainted while opaque pixels will be preserved.
+ /// In the event an `image` with an alpha channel is provided along with a `mask`, the `mask` will take precedence.
+ /// Example: ./some/image.png + /// + /// + /// Controls the strength of the inpainting process on a per-pixel basis, either via a
+ /// second image (passed into this parameter) or via the alpha channel of the `image` parameter.
+ /// **Passing in a Mask**
+ /// The image passed to this parameter should be a black and white image that represents,
+ /// at any pixel, the strength of inpainting based on how dark or light the given pixel is.
+ /// Completely black pixels represent no inpainting strength while completely white pixels
+ /// represent maximum strength.
+ /// In the event the mask is a different size than the `image` parameter, it will be automatically resized.
+ /// **Alpha Channel Support**
+ /// If you don't provide an explicit mask, one will be derived from the alpha channel of the `image` parameter.
+ /// Transparent pixels will be inpainted while opaque pixels will be preserved.
+ /// In the event an `image` with an alpha channel is provided along with a `mask`, the `mask` will take precedence.
+ /// Example: ./some/image.png + /// + /// + /// Grows the edges of the mask outward in all directions by the specified number of pixels. The expanded area around the mask will be blurred, which can help smooth the transition between inpainted content and the original image.
+ /// Try this parameter if you notice seams or rough edges around the inpainted content.
+ /// > Note: Excessive growth may obscure fine details in the mask and/or merge nearby masked regions.
+ /// Default Value: 5 + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/inpaint",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./dog-wearing-vr-goggles.png", "rb"),
+ /// "mask": open("./mask.png", "rb"),
+ /// },
+ /// data={
+ /// "prompt": "dog wearing black glasses",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./dog-wearing-black-glasses.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateStableImageEditInpaintAsBytesAsStreamAsync( + string contentType, + global::System.IO.Stream image, + string imagename, + string prompt, + global::StabilityAI.CreateStableImageEditInpaintAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + string? negativePrompt = default, + global::System.IO.Stream? mask = default, + string? maskname = default, + double? growMask = default, + double? seed = default, + global::StabilityAI.CreateStableImageEditInpaintRequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageEditInpaintRequestStylePreset? stylePreset = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Inpaint
+ /// Intelligently modify images by filling in or replacing specified areas with new content based
+ /// on the content of a "mask" image.
+ /// The "mask" is provided in one of two ways:
+ /// 1. Explicitly passing in a separate image via the `mask` parameter
+ /// 2. Derived from the alpha channel of the `image` parameter.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// - `prompt`
+ /// Optionally, the body of the request may also include:
+ /// - `mask`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// The image you wish to inpaint.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png + /// + /// + /// The image you wish to inpaint.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// Controls the strength of the inpainting process on a per-pixel basis, either via a
+ /// second image (passed into this parameter) or via the alpha channel of the `image` parameter.
+ /// **Passing in a Mask**
+ /// The image passed to this parameter should be a black and white image that represents,
+ /// at any pixel, the strength of inpainting based on how dark or light the given pixel is.
+ /// Completely black pixels represent no inpainting strength while completely white pixels
+ /// represent maximum strength.
+ /// In the event the mask is a different size than the `image` parameter, it will be automatically resized.
+ /// **Alpha Channel Support**
+ /// If you don't provide an explicit mask, one will be derived from the alpha channel of the `image` parameter.
+ /// Transparent pixels will be inpainted while opaque pixels will be preserved.
+ /// In the event an `image` with an alpha channel is provided along with a `mask`, the `mask` will take precedence.
+ /// Example: ./some/image.png + /// + /// + /// Controls the strength of the inpainting process on a per-pixel basis, either via a
+ /// second image (passed into this parameter) or via the alpha channel of the `image` parameter.
+ /// **Passing in a Mask**
+ /// The image passed to this parameter should be a black and white image that represents,
+ /// at any pixel, the strength of inpainting based on how dark or light the given pixel is.
+ /// Completely black pixels represent no inpainting strength while completely white pixels
+ /// represent maximum strength.
+ /// In the event the mask is a different size than the `image` parameter, it will be automatically resized.
+ /// **Alpha Channel Support**
+ /// If you don't provide an explicit mask, one will be derived from the alpha channel of the `image` parameter.
+ /// Transparent pixels will be inpainted while opaque pixels will be preserved.
+ /// In the event an `image` with an alpha channel is provided along with a `mask`, the `mask` will take precedence.
+ /// Example: ./some/image.png + /// + /// + /// Grows the edges of the mask outward in all directions by the specified number of pixels. The expanded area around the mask will be blurred, which can help smooth the transition between inpainted content and the original image.
+ /// Try this parameter if you notice seams or rough edges around the inpainted content.
+ /// > Note: Excessive growth may obscure fine details in the mask and/or merge nearby masked regions.
+ /// Default Value: 5 + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/inpaint",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./dog-wearing-vr-goggles.png", "rb"),
+ /// "mask": open("./mask.png", "rb"),
+ /// },
+ /// data={
+ /// "prompt": "dog wearing black glasses",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./dog-wearing-black-glasses.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task> CreateStableImageEditInpaintAsBytesAsResponseAsync( + string contentType, + global::System.IO.Stream image, + string imagename, + string prompt, + global::StabilityAI.CreateStableImageEditInpaintAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + string? negativePrompt = default, + global::System.IO.Stream? mask = default, + string? maskname = default, + double? growMask = default, + double? seed = default, + global::StabilityAI.CreateStableImageEditInpaintRequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageEditInpaintRequestStylePreset? stylePreset = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + } +} \ No newline at end of file diff --git a/src/libs/StabilityAI/Generated/StabilityAI.IEditClient.CreateStableImageEditOutpaintAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.IEditClient.CreateStableImageEditOutpaintAsBytes.g.cs new file mode 100644 index 0000000..dd5674f --- /dev/null +++ b/src/libs/StabilityAI/Generated/StabilityAI.IEditClient.CreateStableImageEditOutpaintAsBytes.g.cs @@ -0,0 +1,881 @@ +#nullable enable + +namespace StabilityAI +{ + public partial interface IEditClient + { + /// + /// Outpaint
+ /// The Outpaint service inserts additional content in an image to fill in the space in any direction.
+ /// Compared to other automated or manual attempts to expand the content in an image, the Outpaint service
+ /// should minimize artifacts and signs that the original image has been edited.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=bZ2yK7VQSgLw)
+ /// ### How to use
+ /// Please invoke this endpoint with a POST request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// Along with _at least one_ outpaint direction:
+ /// - `left`
+ /// - `right`
+ /// - `up`
+ /// - `down`
+ /// > **Note:** for best quality use outpaint direction values smaller or equal to your source image dimensions.
+ /// Each of these parameters should be set to a number between 0 and 2000, representing the number of pixels to outpaint in that direction.
+ /// Optionally, the body of the request may also include:
+ /// - `prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `creativity`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// Flat rate of 4 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/outpaint",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./husky-in-a-field.png", "rb")
+ /// },
+ /// data={
+ /// "left": 200,
+ /// "down": 200,
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./husky-in-a-huge-field.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateStableImageEditOutpaintAsBytesAsync( + string contentType, + + global::StabilityAI.CreateStableImageEditOutpaintRequest request, + global::StabilityAI.CreateStableImageEditOutpaintAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Outpaint
+ /// The Outpaint service inserts additional content in an image to fill in the space in any direction.
+ /// Compared to other automated or manual attempts to expand the content in an image, the Outpaint service
+ /// should minimize artifacts and signs that the original image has been edited.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=bZ2yK7VQSgLw)
+ /// ### How to use
+ /// Please invoke this endpoint with a POST request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// Along with _at least one_ outpaint direction:
+ /// - `left`
+ /// - `right`
+ /// - `up`
+ /// - `down`
+ /// > **Note:** for best quality use outpaint direction values smaller or equal to your source image dimensions.
+ /// Each of these parameters should be set to a number between 0 and 2000, representing the number of pixels to outpaint in that direction.
+ /// Optionally, the body of the request may also include:
+ /// - `prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `creativity`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// Flat rate of 4 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/outpaint",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./husky-in-a-field.png", "rb")
+ /// },
+ /// data={
+ /// "left": 200,
+ /// "down": 200,
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./husky-in-a-huge-field.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateStableImageEditOutpaintAsBytesAsStreamAsync( + string contentType, + + global::StabilityAI.CreateStableImageEditOutpaintRequest request, + global::StabilityAI.CreateStableImageEditOutpaintAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Outpaint
+ /// The Outpaint service inserts additional content in an image to fill in the space in any direction.
+ /// Compared to other automated or manual attempts to expand the content in an image, the Outpaint service
+ /// should minimize artifacts and signs that the original image has been edited.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=bZ2yK7VQSgLw)
+ /// ### How to use
+ /// Please invoke this endpoint with a POST request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// Along with _at least one_ outpaint direction:
+ /// - `left`
+ /// - `right`
+ /// - `up`
+ /// - `down`
+ /// > **Note:** for best quality use outpaint direction values smaller or equal to your source image dimensions.
+ /// Each of these parameters should be set to a number between 0 and 2000, representing the number of pixels to outpaint in that direction.
+ /// Optionally, the body of the request may also include:
+ /// - `prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `creativity`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// Flat rate of 4 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/outpaint",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./husky-in-a-field.png", "rb")
+ /// },
+ /// data={
+ /// "left": 200,
+ /// "down": 200,
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./husky-in-a-huge-field.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task> CreateStableImageEditOutpaintAsBytesAsResponseAsync( + string contentType, + + global::StabilityAI.CreateStableImageEditOutpaintRequest request, + global::StabilityAI.CreateStableImageEditOutpaintAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Outpaint
+ /// The Outpaint service inserts additional content in an image to fill in the space in any direction.
+ /// Compared to other automated or manual attempts to expand the content in an image, the Outpaint service
+ /// should minimize artifacts and signs that the original image has been edited.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=bZ2yK7VQSgLw)
+ /// ### How to use
+ /// Please invoke this endpoint with a POST request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// Along with _at least one_ outpaint direction:
+ /// - `left`
+ /// - `right`
+ /// - `up`
+ /// - `down`
+ /// > **Note:** for best quality use outpaint direction values smaller or equal to your source image dimensions.
+ /// Each of these parameters should be set to a number between 0 and 2000, representing the number of pixels to outpaint in that direction.
+ /// Optionally, the body of the request may also include:
+ /// - `prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `creativity`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// Flat rate of 4 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// The image you wish to outpaint.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// The image you wish to outpaint.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// The number of pixels to outpaint on the left side of the image. At least one outpainting direction must be supplied with a non-zero value.
+ /// Default Value: 0 + /// + /// + /// The number of pixels to outpaint on the right side of the image. At least one outpainting direction must be supplied with a non-zero value.
+ /// Default Value: 0 + /// + /// + /// The number of pixels to outpaint on the top of the image. At least one outpainting direction must be supplied with a non-zero value.
+ /// Default Value: 0 + /// + /// + /// The number of pixels to outpaint on the bottom of the image. At least one outpainting direction must be supplied with a non-zero value.
+ /// Default Value: 0 + /// + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + global::System.Threading.Tasks.Task CreateStableImageEditOutpaintAsBytesAsync( + string contentType, + byte[] image, + string imagename, + global::StabilityAI.CreateStableImageEditOutpaintAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + int? left = default, + int? right = default, + int? up = default, + int? down = default, + global::StabilityAI.AllOf? creativity = default, + string? prompt = default, + double? seed = default, + global::StabilityAI.CreateStableImageEditOutpaintRequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageEditOutpaintRequestStylePreset? stylePreset = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + + /// + /// Outpaint
+ /// The Outpaint service inserts additional content in an image to fill in the space in any direction.
+ /// Compared to other automated or manual attempts to expand the content in an image, the Outpaint service
+ /// should minimize artifacts and signs that the original image has been edited.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=bZ2yK7VQSgLw)
+ /// ### How to use
+ /// Please invoke this endpoint with a POST request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// Along with _at least one_ outpaint direction:
+ /// - `left`
+ /// - `right`
+ /// - `up`
+ /// - `down`
+ /// > **Note:** for best quality use outpaint direction values smaller or equal to your source image dimensions.
+ /// Each of these parameters should be set to a number between 0 and 2000, representing the number of pixels to outpaint in that direction.
+ /// Optionally, the body of the request may also include:
+ /// - `prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `creativity`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// Flat rate of 4 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// The image you wish to outpaint.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// The image you wish to outpaint.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// The number of pixels to outpaint on the left side of the image. At least one outpainting direction must be supplied with a non-zero value.
+ /// Default Value: 0 + /// + /// + /// The number of pixels to outpaint on the right side of the image. At least one outpainting direction must be supplied with a non-zero value.
+ /// Default Value: 0 + /// + /// + /// The number of pixels to outpaint on the top of the image. At least one outpainting direction must be supplied with a non-zero value.
+ /// Default Value: 0 + /// + /// + /// The number of pixels to outpaint on the bottom of the image. At least one outpainting direction must be supplied with a non-zero value.
+ /// Default Value: 0 + /// + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/outpaint",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./husky-in-a-field.png", "rb")
+ /// },
+ /// data={
+ /// "left": 200,
+ /// "down": 200,
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./husky-in-a-huge-field.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateStableImageEditOutpaintAsBytesAsync( + string contentType, + global::System.IO.Stream image, + string imagename, + global::StabilityAI.CreateStableImageEditOutpaintAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + int? left = default, + int? right = default, + int? up = default, + int? down = default, + global::StabilityAI.AllOf? creativity = default, + string? prompt = default, + double? seed = default, + global::StabilityAI.CreateStableImageEditOutpaintRequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageEditOutpaintRequestStylePreset? stylePreset = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Outpaint
+ /// The Outpaint service inserts additional content in an image to fill in the space in any direction.
+ /// Compared to other automated or manual attempts to expand the content in an image, the Outpaint service
+ /// should minimize artifacts and signs that the original image has been edited.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=bZ2yK7VQSgLw)
+ /// ### How to use
+ /// Please invoke this endpoint with a POST request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// Along with _at least one_ outpaint direction:
+ /// - `left`
+ /// - `right`
+ /// - `up`
+ /// - `down`
+ /// > **Note:** for best quality use outpaint direction values smaller or equal to your source image dimensions.
+ /// Each of these parameters should be set to a number between 0 and 2000, representing the number of pixels to outpaint in that direction.
+ /// Optionally, the body of the request may also include:
+ /// - `prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `creativity`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// Flat rate of 4 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// The image you wish to outpaint.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// The image you wish to outpaint.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// The number of pixels to outpaint on the left side of the image. At least one outpainting direction must be supplied with a non-zero value.
+ /// Default Value: 0 + /// + /// + /// The number of pixels to outpaint on the right side of the image. At least one outpainting direction must be supplied with a non-zero value.
+ /// Default Value: 0 + /// + /// + /// The number of pixels to outpaint on the top of the image. At least one outpainting direction must be supplied with a non-zero value.
+ /// Default Value: 0 + /// + /// + /// The number of pixels to outpaint on the bottom of the image. At least one outpainting direction must be supplied with a non-zero value.
+ /// Default Value: 0 + /// + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/outpaint",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./husky-in-a-field.png", "rb")
+ /// },
+ /// data={
+ /// "left": 200,
+ /// "down": 200,
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./husky-in-a-huge-field.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateStableImageEditOutpaintAsBytesAsStreamAsync( + string contentType, + global::System.IO.Stream image, + string imagename, + global::StabilityAI.CreateStableImageEditOutpaintAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + int? left = default, + int? right = default, + int? up = default, + int? down = default, + global::StabilityAI.AllOf? creativity = default, + string? prompt = default, + double? seed = default, + global::StabilityAI.CreateStableImageEditOutpaintRequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageEditOutpaintRequestStylePreset? stylePreset = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Outpaint
+ /// The Outpaint service inserts additional content in an image to fill in the space in any direction.
+ /// Compared to other automated or manual attempts to expand the content in an image, the Outpaint service
+ /// should minimize artifacts and signs that the original image has been edited.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=bZ2yK7VQSgLw)
+ /// ### How to use
+ /// Please invoke this endpoint with a POST request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// Along with _at least one_ outpaint direction:
+ /// - `left`
+ /// - `right`
+ /// - `up`
+ /// - `down`
+ /// > **Note:** for best quality use outpaint direction values smaller or equal to your source image dimensions.
+ /// Each of these parameters should be set to a number between 0 and 2000, representing the number of pixels to outpaint in that direction.
+ /// Optionally, the body of the request may also include:
+ /// - `prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `creativity`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// Flat rate of 4 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// The image you wish to outpaint.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// The image you wish to outpaint.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// The number of pixels to outpaint on the left side of the image. At least one outpainting direction must be supplied with a non-zero value.
+ /// Default Value: 0 + /// + /// + /// The number of pixels to outpaint on the right side of the image. At least one outpainting direction must be supplied with a non-zero value.
+ /// Default Value: 0 + /// + /// + /// The number of pixels to outpaint on the top of the image. At least one outpainting direction must be supplied with a non-zero value.
+ /// Default Value: 0 + /// + /// + /// The number of pixels to outpaint on the bottom of the image. At least one outpainting direction must be supplied with a non-zero value.
+ /// Default Value: 0 + /// + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/outpaint",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./husky-in-a-field.png", "rb")
+ /// },
+ /// data={
+ /// "left": 200,
+ /// "down": 200,
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./husky-in-a-huge-field.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task> CreateStableImageEditOutpaintAsBytesAsResponseAsync( + string contentType, + global::System.IO.Stream image, + string imagename, + global::StabilityAI.CreateStableImageEditOutpaintAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + int? left = default, + int? right = default, + int? up = default, + int? down = default, + global::StabilityAI.AllOf? creativity = default, + string? prompt = default, + double? seed = default, + global::StabilityAI.CreateStableImageEditOutpaintRequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageEditOutpaintRequestStylePreset? stylePreset = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + } +} \ No newline at end of file diff --git a/src/libs/StabilityAI/Generated/StabilityAI.IEditClient.CreateStableImageEditRemoveBackgroundAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.IEditClient.CreateStableImageEditRemoveBackgroundAsBytes.g.cs new file mode 100644 index 0000000..ef5b4d2 --- /dev/null +++ b/src/libs/StabilityAI/Generated/StabilityAI.IEditClient.CreateStableImageEditRemoveBackgroundAsBytes.g.cs @@ -0,0 +1,624 @@ +#nullable enable + +namespace StabilityAI +{ + public partial interface IEditClient + { + /// + /// Remove Background
+ /// The Remove Background service accurately segments the foreground from an image and implements
+ /// and removes the background.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=VHofb3LAVmqi)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ ///
+ /// The body of the request must include:
+ /// - `image`
+ /// Optionally, the body of the request may also include:
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/remove-background",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./husky-in-a-field.png", "rb")
+ /// },
+ /// data={
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./husky.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateStableImageEditRemoveBackgroundAsBytesAsync( + string contentType, + + global::StabilityAI.CreateStableImageEditRemoveBackgroundRequest request, + global::StabilityAI.CreateStableImageEditRemoveBackgroundAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Remove Background
+ /// The Remove Background service accurately segments the foreground from an image and implements
+ /// and removes the background.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=VHofb3LAVmqi)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ ///
+ /// The body of the request must include:
+ /// - `image`
+ /// Optionally, the body of the request may also include:
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/remove-background",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./husky-in-a-field.png", "rb")
+ /// },
+ /// data={
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./husky.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateStableImageEditRemoveBackgroundAsBytesAsStreamAsync( + string contentType, + + global::StabilityAI.CreateStableImageEditRemoveBackgroundRequest request, + global::StabilityAI.CreateStableImageEditRemoveBackgroundAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Remove Background
+ /// The Remove Background service accurately segments the foreground from an image and implements
+ /// and removes the background.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=VHofb3LAVmqi)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ ///
+ /// The body of the request must include:
+ /// - `image`
+ /// Optionally, the body of the request may also include:
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/remove-background",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./husky-in-a-field.png", "rb")
+ /// },
+ /// data={
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./husky.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task> CreateStableImageEditRemoveBackgroundAsBytesAsResponseAsync( + string contentType, + + global::StabilityAI.CreateStableImageEditRemoveBackgroundRequest request, + global::StabilityAI.CreateStableImageEditRemoveBackgroundAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Remove Background
+ /// The Remove Background service accurately segments the foreground from an image and implements
+ /// and removes the background.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=VHofb3LAVmqi)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ ///
+ /// The body of the request must include:
+ /// - `image`
+ /// Optionally, the body of the request may also include:
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// The image whose background you wish to remove.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 4,194,304 pixels
+ /// Example: ./some/image.png + /// + /// + /// The image whose background you wish to remove.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 4,194,304 pixels
+ /// Example: ./some/image.png + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + global::System.Threading.Tasks.Task CreateStableImageEditRemoveBackgroundAsBytesAsync( + string contentType, + byte[] image, + string imagename, + global::StabilityAI.CreateStableImageEditRemoveBackgroundAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.CreateStableImageEditRemoveBackgroundRequestOutputFormat? outputFormat = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + + /// + /// Remove Background
+ /// The Remove Background service accurately segments the foreground from an image and implements
+ /// and removes the background.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=VHofb3LAVmqi)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ ///
+ /// The body of the request must include:
+ /// - `image`
+ /// Optionally, the body of the request may also include:
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// The image whose background you wish to remove.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 4,194,304 pixels
+ /// Example: ./some/image.png + /// + /// + /// The image whose background you wish to remove.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 4,194,304 pixels
+ /// Example: ./some/image.png + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/remove-background",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./husky-in-a-field.png", "rb")
+ /// },
+ /// data={
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./husky.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateStableImageEditRemoveBackgroundAsBytesAsync( + string contentType, + global::System.IO.Stream image, + string imagename, + global::StabilityAI.CreateStableImageEditRemoveBackgroundAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.CreateStableImageEditRemoveBackgroundRequestOutputFormat? outputFormat = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Remove Background
+ /// The Remove Background service accurately segments the foreground from an image and implements
+ /// and removes the background.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=VHofb3LAVmqi)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ ///
+ /// The body of the request must include:
+ /// - `image`
+ /// Optionally, the body of the request may also include:
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// The image whose background you wish to remove.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 4,194,304 pixels
+ /// Example: ./some/image.png + /// + /// + /// The image whose background you wish to remove.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 4,194,304 pixels
+ /// Example: ./some/image.png + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/remove-background",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./husky-in-a-field.png", "rb")
+ /// },
+ /// data={
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./husky.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateStableImageEditRemoveBackgroundAsBytesAsStreamAsync( + string contentType, + global::System.IO.Stream image, + string imagename, + global::StabilityAI.CreateStableImageEditRemoveBackgroundAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.CreateStableImageEditRemoveBackgroundRequestOutputFormat? outputFormat = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Remove Background
+ /// The Remove Background service accurately segments the foreground from an image and implements
+ /// and removes the background.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=VHofb3LAVmqi)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ ///
+ /// The body of the request must include:
+ /// - `image`
+ /// Optionally, the body of the request may also include:
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// The image whose background you wish to remove.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 4,194,304 pixels
+ /// Example: ./some/image.png + /// + /// + /// The image whose background you wish to remove.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 4,194,304 pixels
+ /// Example: ./some/image.png + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/remove-background",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./husky-in-a-field.png", "rb")
+ /// },
+ /// data={
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./husky.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task> CreateStableImageEditRemoveBackgroundAsBytesAsResponseAsync( + string contentType, + global::System.IO.Stream image, + string imagename, + global::StabilityAI.CreateStableImageEditRemoveBackgroundAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.CreateStableImageEditRemoveBackgroundRequestOutputFormat? outputFormat = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + } +} \ No newline at end of file diff --git a/src/libs/StabilityAI/Generated/StabilityAI.IEditClient.CreateStableImageEditSearchAndRecolorAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.IEditClient.CreateStableImageEditSearchAndRecolorAsBytes.g.cs new file mode 100644 index 0000000..f04e758 --- /dev/null +++ b/src/libs/StabilityAI/Generated/StabilityAI.IEditClient.CreateStableImageEditSearchAndRecolorAsBytes.g.cs @@ -0,0 +1,840 @@ +#nullable enable + +namespace StabilityAI +{ + public partial interface IEditClient + { + /// + /// Search and Recolor
+ /// The Search and Recolor service provides the ability to change the color of a specific object in an image using a prompt.
+ /// This service is a specific version of inpainting that does not require a mask. The Search and Recolor
+ /// service will automatically segment the object and recolor it using the colors requested in the prompt.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=mtgSh4Stj3l)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// - `select_prompt`
+ /// The body may optionally include:
+ /// - `grow_mask`
+ /// - `seed`
+ /// - `negative_prompt`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will match the resolution of the input image.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/search-and-recolor",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./red-car.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a yellow car",
+ /// "select_prompt": "car",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./yellow-car.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateStableImageEditSearchAndRecolorAsBytesAsync( + string contentType, + + global::StabilityAI.CreateStableImageEditSearchAndRecolorRequest request, + global::StabilityAI.CreateStableImageEditSearchAndRecolorAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Search and Recolor
+ /// The Search and Recolor service provides the ability to change the color of a specific object in an image using a prompt.
+ /// This service is a specific version of inpainting that does not require a mask. The Search and Recolor
+ /// service will automatically segment the object and recolor it using the colors requested in the prompt.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=mtgSh4Stj3l)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// - `select_prompt`
+ /// The body may optionally include:
+ /// - `grow_mask`
+ /// - `seed`
+ /// - `negative_prompt`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will match the resolution of the input image.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/search-and-recolor",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./red-car.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a yellow car",
+ /// "select_prompt": "car",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./yellow-car.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateStableImageEditSearchAndRecolorAsBytesAsStreamAsync( + string contentType, + + global::StabilityAI.CreateStableImageEditSearchAndRecolorRequest request, + global::StabilityAI.CreateStableImageEditSearchAndRecolorAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Search and Recolor
+ /// The Search and Recolor service provides the ability to change the color of a specific object in an image using a prompt.
+ /// This service is a specific version of inpainting that does not require a mask. The Search and Recolor
+ /// service will automatically segment the object and recolor it using the colors requested in the prompt.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=mtgSh4Stj3l)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// - `select_prompt`
+ /// The body may optionally include:
+ /// - `grow_mask`
+ /// - `seed`
+ /// - `negative_prompt`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will match the resolution of the input image.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/search-and-recolor",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./red-car.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a yellow car",
+ /// "select_prompt": "car",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./yellow-car.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task> CreateStableImageEditSearchAndRecolorAsBytesAsResponseAsync( + string contentType, + + global::StabilityAI.CreateStableImageEditSearchAndRecolorRequest request, + global::StabilityAI.CreateStableImageEditSearchAndRecolorAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Search and Recolor
+ /// The Search and Recolor service provides the ability to change the color of a specific object in an image using a prompt.
+ /// This service is a specific version of inpainting that does not require a mask. The Search and Recolor
+ /// service will automatically segment the object and recolor it using the colors requested in the prompt.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=mtgSh4Stj3l)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// - `select_prompt`
+ /// The body may optionally include:
+ /// - `grow_mask`
+ /// - `seed`
+ /// - `negative_prompt`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will match the resolution of the input image.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// An image containing content you wish to recolor.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// An image containing content you wish to recolor.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// Short description of what to search for in the `image`.
+ /// Example: glasses + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// Grows the edges of the mask outward in all directions by the specified number of pixels. The expanded area around the mask will be blurred, which can help smooth the transition between inpainted content and the original image.
+ /// Try this parameter if you notice seams or rough edges around the inpainted content.
+ /// > Note: Excessive growth may obscure fine details in the mask and/or merge nearby masked regions.
+ /// Default Value: 3 + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + global::System.Threading.Tasks.Task CreateStableImageEditSearchAndRecolorAsBytesAsync( + string contentType, + byte[] image, + string imagename, + string prompt, + string selectPrompt, + global::StabilityAI.CreateStableImageEditSearchAndRecolorAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + string? negativePrompt = default, + double? growMask = default, + double? seed = default, + global::StabilityAI.CreateStableImageEditSearchAndRecolorRequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageEditSearchAndRecolorRequestStylePreset? stylePreset = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + + /// + /// Search and Recolor
+ /// The Search and Recolor service provides the ability to change the color of a specific object in an image using a prompt.
+ /// This service is a specific version of inpainting that does not require a mask. The Search and Recolor
+ /// service will automatically segment the object and recolor it using the colors requested in the prompt.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=mtgSh4Stj3l)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// - `select_prompt`
+ /// The body may optionally include:
+ /// - `grow_mask`
+ /// - `seed`
+ /// - `negative_prompt`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will match the resolution of the input image.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// An image containing content you wish to recolor.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// An image containing content you wish to recolor.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// Short description of what to search for in the `image`.
+ /// Example: glasses + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// Grows the edges of the mask outward in all directions by the specified number of pixels. The expanded area around the mask will be blurred, which can help smooth the transition between inpainted content and the original image.
+ /// Try this parameter if you notice seams or rough edges around the inpainted content.
+ /// > Note: Excessive growth may obscure fine details in the mask and/or merge nearby masked regions.
+ /// Default Value: 3 + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/search-and-recolor",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./red-car.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a yellow car",
+ /// "select_prompt": "car",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./yellow-car.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateStableImageEditSearchAndRecolorAsBytesAsync( + string contentType, + global::System.IO.Stream image, + string imagename, + string prompt, + string selectPrompt, + global::StabilityAI.CreateStableImageEditSearchAndRecolorAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + string? negativePrompt = default, + double? growMask = default, + double? seed = default, + global::StabilityAI.CreateStableImageEditSearchAndRecolorRequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageEditSearchAndRecolorRequestStylePreset? stylePreset = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Search and Recolor
+ /// The Search and Recolor service provides the ability to change the color of a specific object in an image using a prompt.
+ /// This service is a specific version of inpainting that does not require a mask. The Search and Recolor
+ /// service will automatically segment the object and recolor it using the colors requested in the prompt.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=mtgSh4Stj3l)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// - `select_prompt`
+ /// The body may optionally include:
+ /// - `grow_mask`
+ /// - `seed`
+ /// - `negative_prompt`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will match the resolution of the input image.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// An image containing content you wish to recolor.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// An image containing content you wish to recolor.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// Short description of what to search for in the `image`.
+ /// Example: glasses + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// Grows the edges of the mask outward in all directions by the specified number of pixels. The expanded area around the mask will be blurred, which can help smooth the transition between inpainted content and the original image.
+ /// Try this parameter if you notice seams or rough edges around the inpainted content.
+ /// > Note: Excessive growth may obscure fine details in the mask and/or merge nearby masked regions.
+ /// Default Value: 3 + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/search-and-recolor",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./red-car.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a yellow car",
+ /// "select_prompt": "car",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./yellow-car.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateStableImageEditSearchAndRecolorAsBytesAsStreamAsync( + string contentType, + global::System.IO.Stream image, + string imagename, + string prompt, + string selectPrompt, + global::StabilityAI.CreateStableImageEditSearchAndRecolorAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + string? negativePrompt = default, + double? growMask = default, + double? seed = default, + global::StabilityAI.CreateStableImageEditSearchAndRecolorRequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageEditSearchAndRecolorRequestStylePreset? stylePreset = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Search and Recolor
+ /// The Search and Recolor service provides the ability to change the color of a specific object in an image using a prompt.
+ /// This service is a specific version of inpainting that does not require a mask. The Search and Recolor
+ /// service will automatically segment the object and recolor it using the colors requested in the prompt.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=mtgSh4Stj3l)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// - `select_prompt`
+ /// The body may optionally include:
+ /// - `grow_mask`
+ /// - `seed`
+ /// - `negative_prompt`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will match the resolution of the input image.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// An image containing content you wish to recolor.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// An image containing content you wish to recolor.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// Short description of what to search for in the `image`.
+ /// Example: glasses + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// Grows the edges of the mask outward in all directions by the specified number of pixels. The expanded area around the mask will be blurred, which can help smooth the transition between inpainted content and the original image.
+ /// Try this parameter if you notice seams or rough edges around the inpainted content.
+ /// > Note: Excessive growth may obscure fine details in the mask and/or merge nearby masked regions.
+ /// Default Value: 3 + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/search-and-recolor",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./red-car.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a yellow car",
+ /// "select_prompt": "car",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./yellow-car.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task> CreateStableImageEditSearchAndRecolorAsBytesAsResponseAsync( + string contentType, + global::System.IO.Stream image, + string imagename, + string prompt, + string selectPrompt, + global::StabilityAI.CreateStableImageEditSearchAndRecolorAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + string? negativePrompt = default, + double? growMask = default, + double? seed = default, + global::StabilityAI.CreateStableImageEditSearchAndRecolorRequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageEditSearchAndRecolorRequestStylePreset? stylePreset = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + } +} \ No newline at end of file diff --git a/src/libs/StabilityAI/Generated/StabilityAI.IEditClient.CreateStableImageEditSearchAndReplaceAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.IEditClient.CreateStableImageEditSearchAndReplaceAsBytes.g.cs new file mode 100644 index 0000000..28abc4f --- /dev/null +++ b/src/libs/StabilityAI/Generated/StabilityAI.IEditClient.CreateStableImageEditSearchAndReplaceAsBytes.g.cs @@ -0,0 +1,833 @@ +#nullable enable + +namespace StabilityAI +{ + public partial interface IEditClient + { + /// + /// Search and Replace
+ /// The Search and Replace service is a specific version of inpainting that does not require a mask.
+ /// Instead, users can leverage a `search_prompt` to identify an object in simple language to be replaced.
+ /// The service will automatically segment the object and replace it with the object requested in the prompt.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=0lDpGa2jAmAs)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// - `search_prompt`
+ /// The body may optionally include:
+ /// - `seed`
+ /// - `negative_prompt`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/search-and-replace",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./husky-in-a-field.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "golden retriever in a field",
+ /// "search_prompt": "dog",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./golden-retriever-in-a-field.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateStableImageEditSearchAndReplaceAsBytesAsync( + string contentType, + + global::StabilityAI.CreateStableImageEditSearchAndReplaceRequest request, + global::StabilityAI.CreateStableImageEditSearchAndReplaceAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Search and Replace
+ /// The Search and Replace service is a specific version of inpainting that does not require a mask.
+ /// Instead, users can leverage a `search_prompt` to identify an object in simple language to be replaced.
+ /// The service will automatically segment the object and replace it with the object requested in the prompt.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=0lDpGa2jAmAs)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// - `search_prompt`
+ /// The body may optionally include:
+ /// - `seed`
+ /// - `negative_prompt`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/search-and-replace",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./husky-in-a-field.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "golden retriever in a field",
+ /// "search_prompt": "dog",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./golden-retriever-in-a-field.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateStableImageEditSearchAndReplaceAsBytesAsStreamAsync( + string contentType, + + global::StabilityAI.CreateStableImageEditSearchAndReplaceRequest request, + global::StabilityAI.CreateStableImageEditSearchAndReplaceAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Search and Replace
+ /// The Search and Replace service is a specific version of inpainting that does not require a mask.
+ /// Instead, users can leverage a `search_prompt` to identify an object in simple language to be replaced.
+ /// The service will automatically segment the object and replace it with the object requested in the prompt.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=0lDpGa2jAmAs)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// - `search_prompt`
+ /// The body may optionally include:
+ /// - `seed`
+ /// - `negative_prompt`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/search-and-replace",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./husky-in-a-field.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "golden retriever in a field",
+ /// "search_prompt": "dog",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./golden-retriever-in-a-field.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task> CreateStableImageEditSearchAndReplaceAsBytesAsResponseAsync( + string contentType, + + global::StabilityAI.CreateStableImageEditSearchAndReplaceRequest request, + global::StabilityAI.CreateStableImageEditSearchAndReplaceAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Search and Replace
+ /// The Search and Replace service is a specific version of inpainting that does not require a mask.
+ /// Instead, users can leverage a `search_prompt` to identify an object in simple language to be replaced.
+ /// The service will automatically segment the object and replace it with the object requested in the prompt.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=0lDpGa2jAmAs)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// - `search_prompt`
+ /// The body may optionally include:
+ /// - `seed`
+ /// - `negative_prompt`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// An image containing content you wish to replace.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// An image containing content you wish to replace.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// Short description of what to inpaint in the `image`.
+ /// Example: glasses + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// Grows the edges of the mask outward in all directions by the specified number of pixels. The expanded area around the mask will be blurred, which can help smooth the transition between inpainted content and the original image.
+ /// Try this parameter if you notice seams or rough edges around the inpainted content.
+ /// > Note: Excessive growth may obscure fine details in the mask and/or merge nearby masked regions.
+ /// Default Value: 3 + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + global::System.Threading.Tasks.Task CreateStableImageEditSearchAndReplaceAsBytesAsync( + string contentType, + byte[] image, + string imagename, + string prompt, + string searchPrompt, + global::StabilityAI.CreateStableImageEditSearchAndReplaceAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + string? negativePrompt = default, + double? growMask = default, + double? seed = default, + global::StabilityAI.CreateStableImageEditSearchAndReplaceRequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageEditSearchAndReplaceRequestStylePreset? stylePreset = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + + /// + /// Search and Replace
+ /// The Search and Replace service is a specific version of inpainting that does not require a mask.
+ /// Instead, users can leverage a `search_prompt` to identify an object in simple language to be replaced.
+ /// The service will automatically segment the object and replace it with the object requested in the prompt.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=0lDpGa2jAmAs)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// - `search_prompt`
+ /// The body may optionally include:
+ /// - `seed`
+ /// - `negative_prompt`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// An image containing content you wish to replace.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// An image containing content you wish to replace.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// Short description of what to inpaint in the `image`.
+ /// Example: glasses + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// Grows the edges of the mask outward in all directions by the specified number of pixels. The expanded area around the mask will be blurred, which can help smooth the transition between inpainted content and the original image.
+ /// Try this parameter if you notice seams or rough edges around the inpainted content.
+ /// > Note: Excessive growth may obscure fine details in the mask and/or merge nearby masked regions.
+ /// Default Value: 3 + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/search-and-replace",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./husky-in-a-field.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "golden retriever in a field",
+ /// "search_prompt": "dog",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./golden-retriever-in-a-field.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateStableImageEditSearchAndReplaceAsBytesAsync( + string contentType, + global::System.IO.Stream image, + string imagename, + string prompt, + string searchPrompt, + global::StabilityAI.CreateStableImageEditSearchAndReplaceAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + string? negativePrompt = default, + double? growMask = default, + double? seed = default, + global::StabilityAI.CreateStableImageEditSearchAndReplaceRequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageEditSearchAndReplaceRequestStylePreset? stylePreset = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Search and Replace
+ /// The Search and Replace service is a specific version of inpainting that does not require a mask.
+ /// Instead, users can leverage a `search_prompt` to identify an object in simple language to be replaced.
+ /// The service will automatically segment the object and replace it with the object requested in the prompt.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=0lDpGa2jAmAs)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// - `search_prompt`
+ /// The body may optionally include:
+ /// - `seed`
+ /// - `negative_prompt`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// An image containing content you wish to replace.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// An image containing content you wish to replace.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// Short description of what to inpaint in the `image`.
+ /// Example: glasses + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// Grows the edges of the mask outward in all directions by the specified number of pixels. The expanded area around the mask will be blurred, which can help smooth the transition between inpainted content and the original image.
+ /// Try this parameter if you notice seams or rough edges around the inpainted content.
+ /// > Note: Excessive growth may obscure fine details in the mask and/or merge nearby masked regions.
+ /// Default Value: 3 + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/search-and-replace",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./husky-in-a-field.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "golden retriever in a field",
+ /// "search_prompt": "dog",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./golden-retriever-in-a-field.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateStableImageEditSearchAndReplaceAsBytesAsStreamAsync( + string contentType, + global::System.IO.Stream image, + string imagename, + string prompt, + string searchPrompt, + global::StabilityAI.CreateStableImageEditSearchAndReplaceAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + string? negativePrompt = default, + double? growMask = default, + double? seed = default, + global::StabilityAI.CreateStableImageEditSearchAndReplaceRequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageEditSearchAndReplaceRequestStylePreset? stylePreset = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Search and Replace
+ /// The Search and Replace service is a specific version of inpainting that does not require a mask.
+ /// Instead, users can leverage a `search_prompt` to identify an object in simple language to be replaced.
+ /// The service will automatically segment the object and replace it with the object requested in the prompt.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=0lDpGa2jAmAs)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// - `search_prompt`
+ /// The body may optionally include:
+ /// - `seed`
+ /// - `negative_prompt`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// An image containing content you wish to replace.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// An image containing content you wish to replace.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// Short description of what to inpaint in the `image`.
+ /// Example: glasses + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// Grows the edges of the mask outward in all directions by the specified number of pixels. The expanded area around the mask will be blurred, which can help smooth the transition between inpainted content and the original image.
+ /// Try this parameter if you notice seams or rough edges around the inpainted content.
+ /// > Note: Excessive growth may obscure fine details in the mask and/or merge nearby masked regions.
+ /// Default Value: 3 + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/search-and-replace",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./husky-in-a-field.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "golden retriever in a field",
+ /// "search_prompt": "dog",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./golden-retriever-in-a-field.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task> CreateStableImageEditSearchAndReplaceAsBytesAsResponseAsync( + string contentType, + global::System.IO.Stream image, + string imagename, + string prompt, + string searchPrompt, + global::StabilityAI.CreateStableImageEditSearchAndReplaceAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + string? negativePrompt = default, + double? growMask = default, + double? seed = default, + global::StabilityAI.CreateStableImageEditSearchAndReplaceRequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageEditSearchAndReplaceRequestStylePreset? stylePreset = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + } +} \ No newline at end of file diff --git a/src/libs/StabilityAI/Generated/StabilityAI.IGenerateClient.CreateStableImageGenerateCoreAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.IGenerateClient.CreateStableImageGenerateCoreAsBytes.g.cs new file mode 100644 index 0000000..d4d3f57 --- /dev/null +++ b/src/libs/StabilityAI/Generated/StabilityAI.IGenerateClient.CreateStableImageGenerateCoreAsBytes.g.cs @@ -0,0 +1,338 @@ +#nullable enable + +namespace StabilityAI +{ + public partial interface IGenerateClient + { + /// + /// Stable Image Core
+ /// Our primary service for text-to-image generation, Stable Image Core represents the best quality achievable at high
+ /// speed. No prompt engineering is required! Try asking for a style, a scene, or a character, and see what you get.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=yXhs626oZdr1)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `aspect_ratio`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `style_preset`
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1.5 megapixels.
+ /// ### Credits
+ /// Flat rate of 3 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/generate/core",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={"none": ''},
+ /// data={
+ /// "prompt": "Lighthouse on a cliff overlooking the ocean",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./lighthouse.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateStableImageGenerateCoreAsBytesAsync( + string contentType, + + global::StabilityAI.CreateStableImageGenerateCoreRequest request, + global::StabilityAI.CreateStableImageGenerateCoreAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Stable Image Core
+ /// Our primary service for text-to-image generation, Stable Image Core represents the best quality achievable at high
+ /// speed. No prompt engineering is required! Try asking for a style, a scene, or a character, and see what you get.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=yXhs626oZdr1)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `aspect_ratio`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `style_preset`
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1.5 megapixels.
+ /// ### Credits
+ /// Flat rate of 3 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/generate/core",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={"none": ''},
+ /// data={
+ /// "prompt": "Lighthouse on a cliff overlooking the ocean",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./lighthouse.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateStableImageGenerateCoreAsBytesAsStreamAsync( + string contentType, + + global::StabilityAI.CreateStableImageGenerateCoreRequest request, + global::StabilityAI.CreateStableImageGenerateCoreAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Stable Image Core
+ /// Our primary service for text-to-image generation, Stable Image Core represents the best quality achievable at high
+ /// speed. No prompt engineering is required! Try asking for a style, a scene, or a character, and see what you get.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=yXhs626oZdr1)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `aspect_ratio`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `style_preset`
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1.5 megapixels.
+ /// ### Credits
+ /// Flat rate of 3 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/generate/core",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={"none": ''},
+ /// data={
+ /// "prompt": "Lighthouse on a cliff overlooking the ocean",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./lighthouse.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task> CreateStableImageGenerateCoreAsBytesAsResponseAsync( + string contentType, + + global::StabilityAI.CreateStableImageGenerateCoreRequest request, + global::StabilityAI.CreateStableImageGenerateCoreAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Stable Image Core
+ /// Our primary service for text-to-image generation, Stable Image Core represents the best quality achievable at high
+ /// speed. No prompt engineering is required! Try asking for a style, a scene, or a character, and see what you get.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=yXhs626oZdr1)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `aspect_ratio`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `style_preset`
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1.5 megapixels.
+ /// ### Credits
+ /// Flat rate of 3 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// Controls the aspect ratio of the generated image.
+ /// Default Value: 1:1 + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Guides the image model towards a particular style. + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + global::System.Threading.Tasks.Task CreateStableImageGenerateCoreAsBytesAsync( + string contentType, + string prompt, + global::StabilityAI.CreateStableImageGenerateCoreAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.CreateStableImageGenerateCoreRequestAspectRatio? aspectRatio = default, + string? negativePrompt = default, + double? seed = default, + global::StabilityAI.CreateStableImageGenerateCoreRequestStylePreset? stylePreset = default, + global::StabilityAI.CreateStableImageGenerateCoreRequestOutputFormat? outputFormat = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + } +} \ No newline at end of file diff --git a/src/libs/StabilityAI/Generated/StabilityAI.IGenerateClient.CreateStableImageGenerateSd3AsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.IGenerateClient.CreateStableImageGenerateSd3AsBytes.g.cs new file mode 100644 index 0000000..1ae617a --- /dev/null +++ b/src/libs/StabilityAI/Generated/StabilityAI.IGenerateClient.CreateStableImageGenerateSd3AsBytes.g.cs @@ -0,0 +1,511 @@ +#nullable enable + +namespace StabilityAI +{ + public partial interface IGenerateClient + { + /// + /// Stable Diffusion 3.5
+ /// Generate using Stable Diffusion 3.5 models, Stability AI latest base model:
+ /// - **Stable Diffusion 3.5 Large**: At 8 billion parameters, with superior quality and
+ /// prompt adherence, this base model is the most powerful in the Stable Diffusion
+ /// family. This model is ideal for professional use cases at 1 megapixel resolution.
+ /// - **Stable Diffusion 3.5 Large Turbo**: A distilled version of Stable Diffusion 3.5 Large.
+ /// SD3.5 Large Turbo generates high-quality images with exceptional prompt adherence
+ /// in just 4 steps, making it considerably faster than Stable Diffusion 3.5 Large.
+ /// - **Stable Diffusion 3.5 Medium**: With 2.5 billion parameters, the model delivers an
+ /// optimal balance between prompt accuracy and image quality, making it an efficient
+ /// choice for fast high-performance image generation.
+ /// - **Stable Diffusion 3.5 Flash**: A distilled version of Stable Diffusion 3.5 Medium.
+ /// SD3.5 Flash generates high-quality images with a 4 step process instead of 40, making
+ /// it faster than Stable Diffusion 3.5 Medium.
+ /// Read more about the model capabilities [here](https://stability.ai/news/introducing-stable-diffusion-3-5).
+ /// As of April 17, 2025, we have deprecated the Stable Diffusion 3.0 APIs and will be automatically
+ /// re-routing calls to Stable Diffusion 3.0 models to Stable Diffusion 3.5 APIs at no extra cost.
+ /// You can read more in the [release notes](/docs/release-notes#api-deprecation-notice).
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/SD3_API.ipynb)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`. The accept header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// #### **Generating with a prompt**
+ /// Commonly referred to as **text-to-image**, this mode generates an image from text alone. While the only required
+ /// parameter is the `prompt`, it also supports an `aspect_ratio` parameter which can be used to control the
+ /// aspect ratio of the generated image.
+ /// #### **Generating with a prompt *and* an image**
+ /// Commonly referred to as **image-to-image**, this mode also generates an image from text but uses an existing image as the
+ /// starting point. The required parameters are:
+ /// - `prompt` - text to generate the image from
+ /// - `image` - the image to use as the starting point for the generation
+ /// - `strength` - controls how much influence the `image` parameter has on the output image
+ /// - `mode` - must be set to `image-to-image`
+ /// > **Note:** maximum request size is 10MiB.
+ /// #### **Optional Parameters:**
+ /// Both modes support the following optional parameters:
+ /// - `model` - the model to use (SD 3.5 Large, SD 3.5 Large Turbo, SD 3.5 Medium, SD 3.5 Flash)
+ /// - `output_format` - the format of the output image
+ /// - `seed` - the randomness seed to use for the generation
+ /// - `negative_prompt` - keywords of what you **do not** wish to see in the output image
+ /// - `cfg_scale` - controls how strictly the diffusion process adheres to the prompt text
+ /// - `style_preset` - guides the image model towards a particular style
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1MP. The default resolution is 1024x1024.
+ /// ### Credits
+ /// - **SD 3.5 Large**: Flat rate of 6.5 credits per successful generation.
+ /// - **SD 3.5 Large Turbo**: Flat rate of 4 credits per successful generation.
+ /// - **SD 3.5 Medium**: Flat rate of 3.5 credits per successful generation.
+ /// - **SD 3.5 Flash**: Flat rate of 2.5 credits per successful generation.
+ /// As always, you will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/generate/sd3",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={"none": ''},
+ /// data={
+ /// "prompt": "Lighthouse on a cliff overlooking the ocean",
+ /// "output_format": "jpeg",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./lighthouse.jpeg", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateStableImageGenerateSd3AsBytesAsync( + string contentType, + + global::StabilityAI.CreateStableImageGenerateSd3Request request, + global::StabilityAI.CreateStableImageGenerateSd3Accept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Stable Diffusion 3.5
+ /// Generate using Stable Diffusion 3.5 models, Stability AI latest base model:
+ /// - **Stable Diffusion 3.5 Large**: At 8 billion parameters, with superior quality and
+ /// prompt adherence, this base model is the most powerful in the Stable Diffusion
+ /// family. This model is ideal for professional use cases at 1 megapixel resolution.
+ /// - **Stable Diffusion 3.5 Large Turbo**: A distilled version of Stable Diffusion 3.5 Large.
+ /// SD3.5 Large Turbo generates high-quality images with exceptional prompt adherence
+ /// in just 4 steps, making it considerably faster than Stable Diffusion 3.5 Large.
+ /// - **Stable Diffusion 3.5 Medium**: With 2.5 billion parameters, the model delivers an
+ /// optimal balance between prompt accuracy and image quality, making it an efficient
+ /// choice for fast high-performance image generation.
+ /// - **Stable Diffusion 3.5 Flash**: A distilled version of Stable Diffusion 3.5 Medium.
+ /// SD3.5 Flash generates high-quality images with a 4 step process instead of 40, making
+ /// it faster than Stable Diffusion 3.5 Medium.
+ /// Read more about the model capabilities [here](https://stability.ai/news/introducing-stable-diffusion-3-5).
+ /// As of April 17, 2025, we have deprecated the Stable Diffusion 3.0 APIs and will be automatically
+ /// re-routing calls to Stable Diffusion 3.0 models to Stable Diffusion 3.5 APIs at no extra cost.
+ /// You can read more in the [release notes](/docs/release-notes#api-deprecation-notice).
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/SD3_API.ipynb)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`. The accept header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// #### **Generating with a prompt**
+ /// Commonly referred to as **text-to-image**, this mode generates an image from text alone. While the only required
+ /// parameter is the `prompt`, it also supports an `aspect_ratio` parameter which can be used to control the
+ /// aspect ratio of the generated image.
+ /// #### **Generating with a prompt *and* an image**
+ /// Commonly referred to as **image-to-image**, this mode also generates an image from text but uses an existing image as the
+ /// starting point. The required parameters are:
+ /// - `prompt` - text to generate the image from
+ /// - `image` - the image to use as the starting point for the generation
+ /// - `strength` - controls how much influence the `image` parameter has on the output image
+ /// - `mode` - must be set to `image-to-image`
+ /// > **Note:** maximum request size is 10MiB.
+ /// #### **Optional Parameters:**
+ /// Both modes support the following optional parameters:
+ /// - `model` - the model to use (SD 3.5 Large, SD 3.5 Large Turbo, SD 3.5 Medium, SD 3.5 Flash)
+ /// - `output_format` - the format of the output image
+ /// - `seed` - the randomness seed to use for the generation
+ /// - `negative_prompt` - keywords of what you **do not** wish to see in the output image
+ /// - `cfg_scale` - controls how strictly the diffusion process adheres to the prompt text
+ /// - `style_preset` - guides the image model towards a particular style
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1MP. The default resolution is 1024x1024.
+ /// ### Credits
+ /// - **SD 3.5 Large**: Flat rate of 6.5 credits per successful generation.
+ /// - **SD 3.5 Large Turbo**: Flat rate of 4 credits per successful generation.
+ /// - **SD 3.5 Medium**: Flat rate of 3.5 credits per successful generation.
+ /// - **SD 3.5 Flash**: Flat rate of 2.5 credits per successful generation.
+ /// As always, you will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/generate/sd3",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={"none": ''},
+ /// data={
+ /// "prompt": "Lighthouse on a cliff overlooking the ocean",
+ /// "output_format": "jpeg",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./lighthouse.jpeg", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateStableImageGenerateSd3AsBytesAsStreamAsync( + string contentType, + + global::StabilityAI.CreateStableImageGenerateSd3Request request, + global::StabilityAI.CreateStableImageGenerateSd3Accept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Stable Diffusion 3.5
+ /// Generate using Stable Diffusion 3.5 models, Stability AI latest base model:
+ /// - **Stable Diffusion 3.5 Large**: At 8 billion parameters, with superior quality and
+ /// prompt adherence, this base model is the most powerful in the Stable Diffusion
+ /// family. This model is ideal for professional use cases at 1 megapixel resolution.
+ /// - **Stable Diffusion 3.5 Large Turbo**: A distilled version of Stable Diffusion 3.5 Large.
+ /// SD3.5 Large Turbo generates high-quality images with exceptional prompt adherence
+ /// in just 4 steps, making it considerably faster than Stable Diffusion 3.5 Large.
+ /// - **Stable Diffusion 3.5 Medium**: With 2.5 billion parameters, the model delivers an
+ /// optimal balance between prompt accuracy and image quality, making it an efficient
+ /// choice for fast high-performance image generation.
+ /// - **Stable Diffusion 3.5 Flash**: A distilled version of Stable Diffusion 3.5 Medium.
+ /// SD3.5 Flash generates high-quality images with a 4 step process instead of 40, making
+ /// it faster than Stable Diffusion 3.5 Medium.
+ /// Read more about the model capabilities [here](https://stability.ai/news/introducing-stable-diffusion-3-5).
+ /// As of April 17, 2025, we have deprecated the Stable Diffusion 3.0 APIs and will be automatically
+ /// re-routing calls to Stable Diffusion 3.0 models to Stable Diffusion 3.5 APIs at no extra cost.
+ /// You can read more in the [release notes](/docs/release-notes#api-deprecation-notice).
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/SD3_API.ipynb)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`. The accept header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// #### **Generating with a prompt**
+ /// Commonly referred to as **text-to-image**, this mode generates an image from text alone. While the only required
+ /// parameter is the `prompt`, it also supports an `aspect_ratio` parameter which can be used to control the
+ /// aspect ratio of the generated image.
+ /// #### **Generating with a prompt *and* an image**
+ /// Commonly referred to as **image-to-image**, this mode also generates an image from text but uses an existing image as the
+ /// starting point. The required parameters are:
+ /// - `prompt` - text to generate the image from
+ /// - `image` - the image to use as the starting point for the generation
+ /// - `strength` - controls how much influence the `image` parameter has on the output image
+ /// - `mode` - must be set to `image-to-image`
+ /// > **Note:** maximum request size is 10MiB.
+ /// #### **Optional Parameters:**
+ /// Both modes support the following optional parameters:
+ /// - `model` - the model to use (SD 3.5 Large, SD 3.5 Large Turbo, SD 3.5 Medium, SD 3.5 Flash)
+ /// - `output_format` - the format of the output image
+ /// - `seed` - the randomness seed to use for the generation
+ /// - `negative_prompt` - keywords of what you **do not** wish to see in the output image
+ /// - `cfg_scale` - controls how strictly the diffusion process adheres to the prompt text
+ /// - `style_preset` - guides the image model towards a particular style
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1MP. The default resolution is 1024x1024.
+ /// ### Credits
+ /// - **SD 3.5 Large**: Flat rate of 6.5 credits per successful generation.
+ /// - **SD 3.5 Large Turbo**: Flat rate of 4 credits per successful generation.
+ /// - **SD 3.5 Medium**: Flat rate of 3.5 credits per successful generation.
+ /// - **SD 3.5 Flash**: Flat rate of 2.5 credits per successful generation.
+ /// As always, you will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/generate/sd3",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={"none": ''},
+ /// data={
+ /// "prompt": "Lighthouse on a cliff overlooking the ocean",
+ /// "output_format": "jpeg",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./lighthouse.jpeg", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task> CreateStableImageGenerateSd3AsBytesAsResponseAsync( + string contentType, + + global::StabilityAI.CreateStableImageGenerateSd3Request request, + global::StabilityAI.CreateStableImageGenerateSd3Accept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Stable Diffusion 3.5
+ /// Generate using Stable Diffusion 3.5 models, Stability AI latest base model:
+ /// - **Stable Diffusion 3.5 Large**: At 8 billion parameters, with superior quality and
+ /// prompt adherence, this base model is the most powerful in the Stable Diffusion
+ /// family. This model is ideal for professional use cases at 1 megapixel resolution.
+ /// - **Stable Diffusion 3.5 Large Turbo**: A distilled version of Stable Diffusion 3.5 Large.
+ /// SD3.5 Large Turbo generates high-quality images with exceptional prompt adherence
+ /// in just 4 steps, making it considerably faster than Stable Diffusion 3.5 Large.
+ /// - **Stable Diffusion 3.5 Medium**: With 2.5 billion parameters, the model delivers an
+ /// optimal balance between prompt accuracy and image quality, making it an efficient
+ /// choice for fast high-performance image generation.
+ /// - **Stable Diffusion 3.5 Flash**: A distilled version of Stable Diffusion 3.5 Medium.
+ /// SD3.5 Flash generates high-quality images with a 4 step process instead of 40, making
+ /// it faster than Stable Diffusion 3.5 Medium.
+ /// Read more about the model capabilities [here](https://stability.ai/news/introducing-stable-diffusion-3-5).
+ /// As of April 17, 2025, we have deprecated the Stable Diffusion 3.0 APIs and will be automatically
+ /// re-routing calls to Stable Diffusion 3.0 models to Stable Diffusion 3.5 APIs at no extra cost.
+ /// You can read more in the [release notes](/docs/release-notes#api-deprecation-notice).
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/SD3_API.ipynb)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`. The accept header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// #### **Generating with a prompt**
+ /// Commonly referred to as **text-to-image**, this mode generates an image from text alone. While the only required
+ /// parameter is the `prompt`, it also supports an `aspect_ratio` parameter which can be used to control the
+ /// aspect ratio of the generated image.
+ /// #### **Generating with a prompt *and* an image**
+ /// Commonly referred to as **image-to-image**, this mode also generates an image from text but uses an existing image as the
+ /// starting point. The required parameters are:
+ /// - `prompt` - text to generate the image from
+ /// - `image` - the image to use as the starting point for the generation
+ /// - `strength` - controls how much influence the `image` parameter has on the output image
+ /// - `mode` - must be set to `image-to-image`
+ /// > **Note:** maximum request size is 10MiB.
+ /// #### **Optional Parameters:**
+ /// Both modes support the following optional parameters:
+ /// - `model` - the model to use (SD 3.5 Large, SD 3.5 Large Turbo, SD 3.5 Medium, SD 3.5 Flash)
+ /// - `output_format` - the format of the output image
+ /// - `seed` - the randomness seed to use for the generation
+ /// - `negative_prompt` - keywords of what you **do not** wish to see in the output image
+ /// - `cfg_scale` - controls how strictly the diffusion process adheres to the prompt text
+ /// - `style_preset` - guides the image model towards a particular style
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1MP. The default resolution is 1024x1024.
+ /// ### Credits
+ /// - **SD 3.5 Large**: Flat rate of 6.5 credits per successful generation.
+ /// - **SD 3.5 Large Turbo**: Flat rate of 4 credits per successful generation.
+ /// - **SD 3.5 Medium**: Flat rate of 3.5 credits per successful generation.
+ /// - **SD 3.5 Flash**: Flat rate of 2.5 credits per successful generation.
+ /// As always, you will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results. + /// + /// + /// Controls whether this is a text-to-image or image-to-image generation, which affects which parameters are required:
+ /// - **text-to-image** requires only the `prompt` parameter
+ /// - **image-to-image** requires the `prompt`, `image`, and `strength` parameters
+ /// Default Value: text-to-image + /// + /// + /// The image to use as the starting point for the generation.
+ /// Supported formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Supported dimensions:
+ /// - Every side must be at least 64 pixels
+ /// > **Important:** This parameter is only valid for **image-to-image** requests. + /// + /// + /// The image to use as the starting point for the generation.
+ /// Supported formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Supported dimensions:
+ /// - Every side must be at least 64 pixels
+ /// > **Important:** This parameter is only valid for **image-to-image** requests. + /// + /// + /// Sometimes referred to as _denoising_, this parameter controls how much influence the
+ /// `image` parameter has on the generated image. A value of 0 would yield an image that
+ /// is identical to the input. A value of 1 would be as if you passed in no image at all.
+ /// > **Important:** This parameter is only valid for **image-to-image** requests. For SD 3.5 Flash, the
+ /// best results for image-to-image generation are achieved with a `strength` between .94 - .97. + /// + /// + /// Controls the aspect ratio of the generated image. Defaults to 1:1.
+ /// > **Important:** This parameter is only valid for **text-to-image** requests.
+ /// Default Value: 1:1 + /// + /// + /// The model to use for generation.
+ /// - `sd3.5-large` requires 6.5 credits per generation
+ /// - `sd3.5-large-turbo` requires 4 credits per generation
+ /// - `sd3.5-medium` requires 3.5 credits per generation
+ /// - `sd3.5-flash` requires 2.5 credits per generation
+ /// - As of the April 17, 2025, `sd3-large`, `sd3-large-turbo` and `sd3-medium`
+ /// are re-routed to their `sd3.5-[model version]` equivalent, at the same price.
+ /// Default Value: sd3.5-large + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Guides the image model towards a particular style. + /// + /// + /// Keywords of what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// How strictly the diffusion process adheres to the prompt text (higher values keep your image closer to your prompt). The _Large_ and _Medium_ models use a default of `4`. The _Turbo_ and _Flash_ model uses a default of `1`. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + global::System.Threading.Tasks.Task CreateStableImageGenerateSd3AsBytesAsync( + string contentType, + string prompt, + global::StabilityAI.CreateStableImageGenerateSd3Accept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.CreateStableImageGenerateSd3RequestMode? mode = default, + byte[]? image = default, + string? imagename = default, + double? strength = default, + global::StabilityAI.CreateStableImageGenerateSd3RequestAspectRatio? aspectRatio = default, + global::StabilityAI.CreateStableImageGenerateSd3RequestModel? model = default, + double? seed = default, + global::StabilityAI.CreateStableImageGenerateSd3RequestOutputFormat? outputFormat = default, + global::StabilityAI.CreateStableImageGenerateSd3RequestStylePreset? stylePreset = default, + string? negativePrompt = default, + double? cfgScale = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + } +} \ No newline at end of file diff --git a/src/libs/StabilityAI/Generated/StabilityAI.IGenerateClient.CreateStableImageGenerateUltraAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.IGenerateClient.CreateStableImageGenerateUltraAsBytes.g.cs new file mode 100644 index 0000000..b4c75b4 --- /dev/null +++ b/src/libs/StabilityAI/Generated/StabilityAI.IGenerateClient.CreateStableImageGenerateUltraAsBytes.g.cs @@ -0,0 +1,389 @@ +#nullable enable + +namespace StabilityAI +{ + public partial interface IGenerateClient + { + /// + /// Stable Image Ultra
+ /// Our most advanced text to image generation service, Stable Image Ultra creates the highest quality images
+ /// with unprecedented prompt understanding. Ultra excels in typography, complex compositions, dynamic lighting,
+ /// vibrant hues, and overall cohesion and structure of an art piece. Made from the most advanced models,
+ /// including Stable Diffusion 3.5, Ultra offers the best of the Stable Diffusion ecosystem.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=yXhs626oZdr1)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`. The accept header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image in the format specified by the `output_format` parameter, but encoded to base64 in a JSON response.
+ /// The only required parameter is the `prompt` field, which should contain the text prompt for the image generation.
+ /// The body of the request should include:
+ /// - `prompt` - text to generate the image from
+ /// The body may optionally include:
+ /// - `image` - the image to use as the starting point for the generation
+ /// - `strength` - controls how much influence the `image` parameter has on the output image
+ /// - `aspect_ratio` - the aspect ratio of the output image
+ /// - `negative_prompt` - keywords of what you **do not** wish to see in the output image
+ /// - `seed` - the randomness seed to use for the generation
+ /// - `output_format` - the format of the output image
+ /// > **Note:** for the full list of optional parameters, please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1 megapixel. The default resolution is 1024x1024.
+ /// ### Credits
+ /// The Ultra service uses 8 credits per successful result. You will not be charged for failed results. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/generate/ultra",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={"none": ''},
+ /// data={
+ /// "prompt": "Lighthouse on a cliff overlooking the ocean",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./lighthouse.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateStableImageGenerateUltraAsBytesAsync( + string contentType, + + global::StabilityAI.CreateStableImageGenerateUltraRequest request, + global::StabilityAI.CreateStableImageGenerateUltraAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Stable Image Ultra
+ /// Our most advanced text to image generation service, Stable Image Ultra creates the highest quality images
+ /// with unprecedented prompt understanding. Ultra excels in typography, complex compositions, dynamic lighting,
+ /// vibrant hues, and overall cohesion and structure of an art piece. Made from the most advanced models,
+ /// including Stable Diffusion 3.5, Ultra offers the best of the Stable Diffusion ecosystem.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=yXhs626oZdr1)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`. The accept header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image in the format specified by the `output_format` parameter, but encoded to base64 in a JSON response.
+ /// The only required parameter is the `prompt` field, which should contain the text prompt for the image generation.
+ /// The body of the request should include:
+ /// - `prompt` - text to generate the image from
+ /// The body may optionally include:
+ /// - `image` - the image to use as the starting point for the generation
+ /// - `strength` - controls how much influence the `image` parameter has on the output image
+ /// - `aspect_ratio` - the aspect ratio of the output image
+ /// - `negative_prompt` - keywords of what you **do not** wish to see in the output image
+ /// - `seed` - the randomness seed to use for the generation
+ /// - `output_format` - the format of the output image
+ /// > **Note:** for the full list of optional parameters, please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1 megapixel. The default resolution is 1024x1024.
+ /// ### Credits
+ /// The Ultra service uses 8 credits per successful result. You will not be charged for failed results. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/generate/ultra",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={"none": ''},
+ /// data={
+ /// "prompt": "Lighthouse on a cliff overlooking the ocean",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./lighthouse.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateStableImageGenerateUltraAsBytesAsStreamAsync( + string contentType, + + global::StabilityAI.CreateStableImageGenerateUltraRequest request, + global::StabilityAI.CreateStableImageGenerateUltraAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Stable Image Ultra
+ /// Our most advanced text to image generation service, Stable Image Ultra creates the highest quality images
+ /// with unprecedented prompt understanding. Ultra excels in typography, complex compositions, dynamic lighting,
+ /// vibrant hues, and overall cohesion and structure of an art piece. Made from the most advanced models,
+ /// including Stable Diffusion 3.5, Ultra offers the best of the Stable Diffusion ecosystem.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=yXhs626oZdr1)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`. The accept header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image in the format specified by the `output_format` parameter, but encoded to base64 in a JSON response.
+ /// The only required parameter is the `prompt` field, which should contain the text prompt for the image generation.
+ /// The body of the request should include:
+ /// - `prompt` - text to generate the image from
+ /// The body may optionally include:
+ /// - `image` - the image to use as the starting point for the generation
+ /// - `strength` - controls how much influence the `image` parameter has on the output image
+ /// - `aspect_ratio` - the aspect ratio of the output image
+ /// - `negative_prompt` - keywords of what you **do not** wish to see in the output image
+ /// - `seed` - the randomness seed to use for the generation
+ /// - `output_format` - the format of the output image
+ /// > **Note:** for the full list of optional parameters, please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1 megapixel. The default resolution is 1024x1024.
+ /// ### Credits
+ /// The Ultra service uses 8 credits per successful result. You will not be charged for failed results. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/generate/ultra",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={"none": ''},
+ /// data={
+ /// "prompt": "Lighthouse on a cliff overlooking the ocean",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./lighthouse.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task> CreateStableImageGenerateUltraAsBytesAsResponseAsync( + string contentType, + + global::StabilityAI.CreateStableImageGenerateUltraRequest request, + global::StabilityAI.CreateStableImageGenerateUltraAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Stable Image Ultra
+ /// Our most advanced text to image generation service, Stable Image Ultra creates the highest quality images
+ /// with unprecedented prompt understanding. Ultra excels in typography, complex compositions, dynamic lighting,
+ /// vibrant hues, and overall cohesion and structure of an art piece. Made from the most advanced models,
+ /// including Stable Diffusion 3.5, Ultra offers the best of the Stable Diffusion ecosystem.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=yXhs626oZdr1)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`. The accept header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image in the format specified by the `output_format` parameter, but encoded to base64 in a JSON response.
+ /// The only required parameter is the `prompt` field, which should contain the text prompt for the image generation.
+ /// The body of the request should include:
+ /// - `prompt` - text to generate the image from
+ /// The body may optionally include:
+ /// - `image` - the image to use as the starting point for the generation
+ /// - `strength` - controls how much influence the `image` parameter has on the output image
+ /// - `aspect_ratio` - the aspect ratio of the output image
+ /// - `negative_prompt` - keywords of what you **do not** wish to see in the output image
+ /// - `seed` - the randomness seed to use for the generation
+ /// - `output_format` - the format of the output image
+ /// > **Note:** for the full list of optional parameters, please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1 megapixel. The default resolution is 1024x1024.
+ /// ### Credits
+ /// The Ultra service uses 8 credits per successful result. You will not be charged for failed results. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// Controls the aspect ratio of the generated image.
+ /// Default Value: 1:1 + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// The image to use as the starting point for the generation.
+ /// > **Important:** The `strength` parameter is required when `image` is provided.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 64 and 16,384 pixels
+ /// - Height must be between 64 and 16,384 pixels
+ /// - Total pixel count must be at least 4,096 pixels
+ /// Example: ./some/image.png + /// + /// + /// The image to use as the starting point for the generation.
+ /// > **Important:** The `strength` parameter is required when `image` is provided.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 64 and 16,384 pixels
+ /// - Height must be between 64 and 16,384 pixels
+ /// - Total pixel count must be at least 4,096 pixels
+ /// Example: ./some/image.png + /// + /// + /// Guides the image model towards a particular style. + /// + /// + /// Sometimes referred to as _denoising_, this parameter controls how much influence the
+ /// `image` parameter has on the generated image. A value of 0 would yield an image that
+ /// is identical to the input. A value of 1 would be as if you passed in no image at all.
+ /// > **Important:** This parameter is required when `image` is provided. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + global::System.Threading.Tasks.Task CreateStableImageGenerateUltraAsBytesAsync( + string contentType, + string prompt, + global::StabilityAI.CreateStableImageGenerateUltraAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + string? negativePrompt = default, + global::StabilityAI.CreateStableImageGenerateUltraRequestAspectRatio? aspectRatio = default, + double? seed = default, + global::StabilityAI.CreateStableImageGenerateUltraRequestOutputFormat? outputFormat = default, + byte[]? image = default, + string? imagename = default, + global::StabilityAI.CreateStableImageGenerateUltraRequestStylePreset? stylePreset = default, + double? strength = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + } +} \ No newline at end of file diff --git a/src/libs/StabilityAI/Generated/StabilityAI.IResultsClient.GetResultsByIdAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.IResultsClient.GetResultsByIdAsBytes.g.cs new file mode 100644 index 0000000..3f352b3 --- /dev/null +++ b/src/libs/StabilityAI/Generated/StabilityAI.IResultsClient.GetResultsByIdAsBytes.g.cs @@ -0,0 +1,206 @@ +#nullable enable + +namespace StabilityAI +{ + public partial interface IResultsClient + { + /// + /// Fetch async generation result
+ /// Fetch the result of a generation by ID.
+ /// Make sure to use the same API key to fetch the generation result that you used to create the generation,
+ /// otherwise you will receive a `404` response.
+ /// ### How to use
+ /// Please invoke this endpoint with a `GET` request.
+ /// The headers of the request must include an API key in the `authorization` field and the ID
+ /// of your generation must be in the path.
+ /// ### How is progress reported?
+ /// Your generation is either `in-progress` (i.e. status code `202`) or it is complete (i.e. status code `200`).
+ /// We may add more fine-grained progress reporting in the future (e.g. a numerical progress).
+ /// ### How long are results stored?
+ /// Results are stored for 24 hours after generation. After that, the results are deleted. + ///
+ /// + /// The `id` of a generation, typically used for async generations, that can be used to check the status of the generation or retrieve the result.
+ /// Example: a6dc6c6e20acda010fe14d71f180658f2896ed9b4ec25aa99a6ff06c796987c4 + /// + /// + /// Specify `*/*` to receive the bytes of the result directly. Otherwise specify `application/json` to receive the result as base64 encoded JSON.
+ /// Default Value: */* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// generation_id = "e52772ac75b..."
+ /// response = requests.request(
+ /// "GET",
+ /// f"https://api.stability.ai/v2beta/results/{generation_id}",
+ /// headers={
+ /// 'accept': "image/*", # Use 'application/json' to receive base64 encoded JSON
+ /// 'authorization': f"Bearer sk-MYAPIKEY"
+ /// },
+ /// )
+ /// if response.status_code == 202:
+ /// print("Generation in-progress, try again in 10 seconds.")
+ /// elif response.status_code == 200:
+ /// print("Generation complete!")
+ /// with open("result.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task GetResultsByIdAsBytesAsync( + string id, + global::StabilityAI.GetResultsAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Fetch async generation result
+ /// Fetch the result of a generation by ID.
+ /// Make sure to use the same API key to fetch the generation result that you used to create the generation,
+ /// otherwise you will receive a `404` response.
+ /// ### How to use
+ /// Please invoke this endpoint with a `GET` request.
+ /// The headers of the request must include an API key in the `authorization` field and the ID
+ /// of your generation must be in the path.
+ /// ### How is progress reported?
+ /// Your generation is either `in-progress` (i.e. status code `202`) or it is complete (i.e. status code `200`).
+ /// We may add more fine-grained progress reporting in the future (e.g. a numerical progress).
+ /// ### How long are results stored?
+ /// Results are stored for 24 hours after generation. After that, the results are deleted. + ///
+ /// + /// The `id` of a generation, typically used for async generations, that can be used to check the status of the generation or retrieve the result.
+ /// Example: a6dc6c6e20acda010fe14d71f180658f2896ed9b4ec25aa99a6ff06c796987c4 + /// + /// + /// Specify `*/*` to receive the bytes of the result directly. Otherwise specify `application/json` to receive the result as base64 encoded JSON.
+ /// Default Value: */* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// generation_id = "e52772ac75b..."
+ /// response = requests.request(
+ /// "GET",
+ /// f"https://api.stability.ai/v2beta/results/{generation_id}",
+ /// headers={
+ /// 'accept': "image/*", # Use 'application/json' to receive base64 encoded JSON
+ /// 'authorization': f"Bearer sk-MYAPIKEY"
+ /// },
+ /// )
+ /// if response.status_code == 202:
+ /// print("Generation in-progress, try again in 10 seconds.")
+ /// elif response.status_code == 200:
+ /// print("Generation complete!")
+ /// with open("result.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task GetResultsByIdAsBytesAsStreamAsync( + string id, + global::StabilityAI.GetResultsAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Fetch async generation result
+ /// Fetch the result of a generation by ID.
+ /// Make sure to use the same API key to fetch the generation result that you used to create the generation,
+ /// otherwise you will receive a `404` response.
+ /// ### How to use
+ /// Please invoke this endpoint with a `GET` request.
+ /// The headers of the request must include an API key in the `authorization` field and the ID
+ /// of your generation must be in the path.
+ /// ### How is progress reported?
+ /// Your generation is either `in-progress` (i.e. status code `202`) or it is complete (i.e. status code `200`).
+ /// We may add more fine-grained progress reporting in the future (e.g. a numerical progress).
+ /// ### How long are results stored?
+ /// Results are stored for 24 hours after generation. After that, the results are deleted. + ///
+ /// + /// The `id` of a generation, typically used for async generations, that can be used to check the status of the generation or retrieve the result.
+ /// Example: a6dc6c6e20acda010fe14d71f180658f2896ed9b4ec25aa99a6ff06c796987c4 + /// + /// + /// Specify `*/*` to receive the bytes of the result directly. Otherwise specify `application/json` to receive the result as base64 encoded JSON.
+ /// Default Value: */* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// generation_id = "e52772ac75b..."
+ /// response = requests.request(
+ /// "GET",
+ /// f"https://api.stability.ai/v2beta/results/{generation_id}",
+ /// headers={
+ /// 'accept': "image/*", # Use 'application/json' to receive base64 encoded JSON
+ /// 'authorization': f"Bearer sk-MYAPIKEY"
+ /// },
+ /// )
+ /// if response.status_code == 202:
+ /// print("Generation in-progress, try again in 10 seconds.")
+ /// elif response.status_code == 200:
+ /// print("Generation complete!")
+ /// with open("result.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task> GetResultsByIdAsBytesAsResponseAsync( + string id, + global::StabilityAI.GetResultsAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + } +} \ No newline at end of file diff --git a/src/libs/StabilityAI/Generated/StabilityAI.IStabilityAIClient.GetStableImageUpscaleCreativeResultByIdAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.IStabilityAIClient.GetStableImageUpscaleCreativeResultByIdAsBytes.g.cs new file mode 100644 index 0000000..916a762 --- /dev/null +++ b/src/libs/StabilityAI/Generated/StabilityAI.IStabilityAIClient.GetStableImageUpscaleCreativeResultByIdAsBytes.g.cs @@ -0,0 +1,206 @@ +#nullable enable + +namespace StabilityAI +{ + public partial interface IStabilityAIClient + { + /// + /// Fetch Creative Upscale result
+ /// Fetch the result of an upscale generation by ID.
+ /// Make sure to use the same API key to fetch the generation result that you used to create the generation,
+ /// otherwise you will receive a `404` response.
+ /// ### How to use
+ /// Please invoke this endpoint with a `GET` request.
+ /// The headers of the request must include an API key in the `authorization` field and the ID
+ /// of your generation must be in the path.
+ /// ### How is progress reported?
+ /// Your generation is either `in-progress` (i.e. status code `202`) or it is complete (i.e. status code `200`).
+ /// We may add more fine-grained progress reporting in the future (e.g. a numerical progress).
+ /// ### How long are results stored?
+ /// Results are stored for 24 hours after generation. After that, the results are deleted. + ///
+ /// + /// The `id` of a generation, typically used for async generations, that can be used to check the status of the generation or retrieve the result.
+ /// Example: a6dc6c6e20acda010fe14d71f180658f2896ed9b4ec25aa99a6ff06c796987c4 + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// generation_id = "e52772ac75b..."
+ /// response = requests.request(
+ /// "GET",
+ /// f"https://api.stability.ai/v2beta/stable-image/upscale/creative/result/{generation_id}",
+ /// headers={
+ /// 'accept': "image/*", # Use 'application/json' to receive base64 encoded JSON
+ /// 'authorization': f"Bearer sk-MYAPIKEY"
+ /// },
+ /// )
+ /// if response.status_code == 202:
+ /// print("Generation in-progress, try again in 10 seconds.")
+ /// elif response.status_code == 200:
+ /// print("Generation complete!")
+ /// with open("upscaled.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task GetStableImageUpscaleCreativeResultByIdAsBytesAsync( + string id, + global::StabilityAI.GetStableImageUpscaleCreativeResultAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Fetch Creative Upscale result
+ /// Fetch the result of an upscale generation by ID.
+ /// Make sure to use the same API key to fetch the generation result that you used to create the generation,
+ /// otherwise you will receive a `404` response.
+ /// ### How to use
+ /// Please invoke this endpoint with a `GET` request.
+ /// The headers of the request must include an API key in the `authorization` field and the ID
+ /// of your generation must be in the path.
+ /// ### How is progress reported?
+ /// Your generation is either `in-progress` (i.e. status code `202`) or it is complete (i.e. status code `200`).
+ /// We may add more fine-grained progress reporting in the future (e.g. a numerical progress).
+ /// ### How long are results stored?
+ /// Results are stored for 24 hours after generation. After that, the results are deleted. + ///
+ /// + /// The `id` of a generation, typically used for async generations, that can be used to check the status of the generation or retrieve the result.
+ /// Example: a6dc6c6e20acda010fe14d71f180658f2896ed9b4ec25aa99a6ff06c796987c4 + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// generation_id = "e52772ac75b..."
+ /// response = requests.request(
+ /// "GET",
+ /// f"https://api.stability.ai/v2beta/stable-image/upscale/creative/result/{generation_id}",
+ /// headers={
+ /// 'accept': "image/*", # Use 'application/json' to receive base64 encoded JSON
+ /// 'authorization': f"Bearer sk-MYAPIKEY"
+ /// },
+ /// )
+ /// if response.status_code == 202:
+ /// print("Generation in-progress, try again in 10 seconds.")
+ /// elif response.status_code == 200:
+ /// print("Generation complete!")
+ /// with open("upscaled.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task GetStableImageUpscaleCreativeResultByIdAsBytesAsStreamAsync( + string id, + global::StabilityAI.GetStableImageUpscaleCreativeResultAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Fetch Creative Upscale result
+ /// Fetch the result of an upscale generation by ID.
+ /// Make sure to use the same API key to fetch the generation result that you used to create the generation,
+ /// otherwise you will receive a `404` response.
+ /// ### How to use
+ /// Please invoke this endpoint with a `GET` request.
+ /// The headers of the request must include an API key in the `authorization` field and the ID
+ /// of your generation must be in the path.
+ /// ### How is progress reported?
+ /// Your generation is either `in-progress` (i.e. status code `202`) or it is complete (i.e. status code `200`).
+ /// We may add more fine-grained progress reporting in the future (e.g. a numerical progress).
+ /// ### How long are results stored?
+ /// Results are stored for 24 hours after generation. After that, the results are deleted. + ///
+ /// + /// The `id` of a generation, typically used for async generations, that can be used to check the status of the generation or retrieve the result.
+ /// Example: a6dc6c6e20acda010fe14d71f180658f2896ed9b4ec25aa99a6ff06c796987c4 + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// generation_id = "e52772ac75b..."
+ /// response = requests.request(
+ /// "GET",
+ /// f"https://api.stability.ai/v2beta/stable-image/upscale/creative/result/{generation_id}",
+ /// headers={
+ /// 'accept': "image/*", # Use 'application/json' to receive base64 encoded JSON
+ /// 'authorization': f"Bearer sk-MYAPIKEY"
+ /// },
+ /// )
+ /// if response.status_code == 202:
+ /// print("Generation in-progress, try again in 10 seconds.")
+ /// elif response.status_code == 200:
+ /// print("Generation complete!")
+ /// with open("upscaled.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task> GetStableImageUpscaleCreativeResultByIdAsBytesAsResponseAsync( + string id, + global::StabilityAI.GetStableImageUpscaleCreativeResultAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + } +} \ No newline at end of file diff --git a/src/libs/StabilityAI/Generated/StabilityAI.IStableAudio2Client.CreateAudioStableAudio2AudioToAudioAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.IStableAudio2Client.CreateAudioStableAudio2AudioToAudioAsBytes.g.cs new file mode 100644 index 0000000..d0af820 --- /dev/null +++ b/src/libs/StabilityAI/Generated/StabilityAI.IStableAudio2Client.CreateAudioStableAudio2AudioToAudioAsBytes.g.cs @@ -0,0 +1,953 @@ +#nullable enable + +namespace StabilityAI +{ + public partial interface IStableAudio2Client + { + /// + /// Audio-to-Audio
+ /// Stable Audio transforms existing audio samples into new high-quality compositions up to three minutes
+ /// long at 44.1kHz stereo using text instructions. Discover techniques for sample transformation in our
+ /// [Audio to Audio Guide](https://www.stableaudio.com/user-guide/audio-to-audio) to maximize creative control.
+ /// Read more about the model capabilities [here](https://stability.ai/news/stable-audio-2-0).
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to
+ /// [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Audio_API.ipynb)
+ /// or try Stable Audio 2.0 for free at [stableaudio.com](https://stableaudio.com).
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`. The `accept` header should be set to one of the following:
+ /// - `audio/*` to receive the audio in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the audio encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `prompt` - text to generate the audio from. Check our
+ /// [prompt guide](https://www.stableaudio.com/user-guide/audio-to-audio) for tips
+ /// - `audio` - the audio to use as the starting point for the generation
+ /// > **Notes:**
+ /// > - We do not allow copyrighted content to be uploaded to our platform.
+ /// > - Maximum request size is 50Mb.
+ /// #### **Optional Parameters:**
+ /// The body may optionally include:
+ /// - `output_format` - the format of the output audio
+ /// - `seed` - the randomness seed to use for the generation
+ /// - `steps` - the number of sampling steps
+ /// - `duration` - the number of seconds of the generated audio
+ /// - `cfg_scale` - controls how strictly the diffusion process adheres to the prompt text (only for `stable-audio-2`)
+ /// - `model` - the model to use [`stable-audio-2`, `stable-audio-2.5`]
+ /// - `strength` - controls how much influence the `audio` parameter has on the output audio
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// **Stable Audio 2.0**
+ /// By default, 20 credits per successful generation. The number of credits is determined
+ /// by the following formula: `credits = 17 + 0.06 * steps`.
+ /// Examples:
+ /// - 50 steps = 20 credits [default]
+ /// - 100 steps = 23 credits
+ /// **Stable Audio 2.5**
+ /// Requests made using the Stable Audio 2.5 model have a flat rate of 20 credits per successful result.
+ /// As always, you will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `audio/*` to receive the bytes of the audio directly. Otherwise specify `application/json` to receive the audio as base64 encoded JSON.
+ /// Default Value: audio/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/audio/stable-audio-2/audio-to-audio",
+ /// headers={"authorization": f"Bearer sk-MYAPIKEY", "accept": "audio/*"},
+ /// files={
+ /// "audio": open("./uk-bass-base.mp3", "rb"),
+ /// },
+ /// data={
+ /// "prompt": "A song in the 3/4 time signature that features cheerful acoustic guitar, live recorded drums, and rhythmic claps, The mood is happy and up-lifting.",
+ /// "output_format": "mp3",
+ /// "duration": 20,
+ /// "model": "stable-audio-2.5",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./output.mp3", "wb") as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateAudioStableAudio2AudioToAudioAsBytesAsync( + string contentType, + + global::StabilityAI.CreateAudioStableAudio2AudioToAudioRequest request, + global::StabilityAI.CreateAudioStableAudio2AudioToAudioAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Audio-to-Audio
+ /// Stable Audio transforms existing audio samples into new high-quality compositions up to three minutes
+ /// long at 44.1kHz stereo using text instructions. Discover techniques for sample transformation in our
+ /// [Audio to Audio Guide](https://www.stableaudio.com/user-guide/audio-to-audio) to maximize creative control.
+ /// Read more about the model capabilities [here](https://stability.ai/news/stable-audio-2-0).
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to
+ /// [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Audio_API.ipynb)
+ /// or try Stable Audio 2.0 for free at [stableaudio.com](https://stableaudio.com).
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`. The `accept` header should be set to one of the following:
+ /// - `audio/*` to receive the audio in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the audio encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `prompt` - text to generate the audio from. Check our
+ /// [prompt guide](https://www.stableaudio.com/user-guide/audio-to-audio) for tips
+ /// - `audio` - the audio to use as the starting point for the generation
+ /// > **Notes:**
+ /// > - We do not allow copyrighted content to be uploaded to our platform.
+ /// > - Maximum request size is 50Mb.
+ /// #### **Optional Parameters:**
+ /// The body may optionally include:
+ /// - `output_format` - the format of the output audio
+ /// - `seed` - the randomness seed to use for the generation
+ /// - `steps` - the number of sampling steps
+ /// - `duration` - the number of seconds of the generated audio
+ /// - `cfg_scale` - controls how strictly the diffusion process adheres to the prompt text (only for `stable-audio-2`)
+ /// - `model` - the model to use [`stable-audio-2`, `stable-audio-2.5`]
+ /// - `strength` - controls how much influence the `audio` parameter has on the output audio
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// **Stable Audio 2.0**
+ /// By default, 20 credits per successful generation. The number of credits is determined
+ /// by the following formula: `credits = 17 + 0.06 * steps`.
+ /// Examples:
+ /// - 50 steps = 20 credits [default]
+ /// - 100 steps = 23 credits
+ /// **Stable Audio 2.5**
+ /// Requests made using the Stable Audio 2.5 model have a flat rate of 20 credits per successful result.
+ /// As always, you will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `audio/*` to receive the bytes of the audio directly. Otherwise specify `application/json` to receive the audio as base64 encoded JSON.
+ /// Default Value: audio/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/audio/stable-audio-2/audio-to-audio",
+ /// headers={"authorization": f"Bearer sk-MYAPIKEY", "accept": "audio/*"},
+ /// files={
+ /// "audio": open("./uk-bass-base.mp3", "rb"),
+ /// },
+ /// data={
+ /// "prompt": "A song in the 3/4 time signature that features cheerful acoustic guitar, live recorded drums, and rhythmic claps, The mood is happy and up-lifting.",
+ /// "output_format": "mp3",
+ /// "duration": 20,
+ /// "model": "stable-audio-2.5",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./output.mp3", "wb") as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateAudioStableAudio2AudioToAudioAsBytesAsStreamAsync( + string contentType, + + global::StabilityAI.CreateAudioStableAudio2AudioToAudioRequest request, + global::StabilityAI.CreateAudioStableAudio2AudioToAudioAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Audio-to-Audio
+ /// Stable Audio transforms existing audio samples into new high-quality compositions up to three minutes
+ /// long at 44.1kHz stereo using text instructions. Discover techniques for sample transformation in our
+ /// [Audio to Audio Guide](https://www.stableaudio.com/user-guide/audio-to-audio) to maximize creative control.
+ /// Read more about the model capabilities [here](https://stability.ai/news/stable-audio-2-0).
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to
+ /// [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Audio_API.ipynb)
+ /// or try Stable Audio 2.0 for free at [stableaudio.com](https://stableaudio.com).
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`. The `accept` header should be set to one of the following:
+ /// - `audio/*` to receive the audio in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the audio encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `prompt` - text to generate the audio from. Check our
+ /// [prompt guide](https://www.stableaudio.com/user-guide/audio-to-audio) for tips
+ /// - `audio` - the audio to use as the starting point for the generation
+ /// > **Notes:**
+ /// > - We do not allow copyrighted content to be uploaded to our platform.
+ /// > - Maximum request size is 50Mb.
+ /// #### **Optional Parameters:**
+ /// The body may optionally include:
+ /// - `output_format` - the format of the output audio
+ /// - `seed` - the randomness seed to use for the generation
+ /// - `steps` - the number of sampling steps
+ /// - `duration` - the number of seconds of the generated audio
+ /// - `cfg_scale` - controls how strictly the diffusion process adheres to the prompt text (only for `stable-audio-2`)
+ /// - `model` - the model to use [`stable-audio-2`, `stable-audio-2.5`]
+ /// - `strength` - controls how much influence the `audio` parameter has on the output audio
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// **Stable Audio 2.0**
+ /// By default, 20 credits per successful generation. The number of credits is determined
+ /// by the following formula: `credits = 17 + 0.06 * steps`.
+ /// Examples:
+ /// - 50 steps = 20 credits [default]
+ /// - 100 steps = 23 credits
+ /// **Stable Audio 2.5**
+ /// Requests made using the Stable Audio 2.5 model have a flat rate of 20 credits per successful result.
+ /// As always, you will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `audio/*` to receive the bytes of the audio directly. Otherwise specify `application/json` to receive the audio as base64 encoded JSON.
+ /// Default Value: audio/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/audio/stable-audio-2/audio-to-audio",
+ /// headers={"authorization": f"Bearer sk-MYAPIKEY", "accept": "audio/*"},
+ /// files={
+ /// "audio": open("./uk-bass-base.mp3", "rb"),
+ /// },
+ /// data={
+ /// "prompt": "A song in the 3/4 time signature that features cheerful acoustic guitar, live recorded drums, and rhythmic claps, The mood is happy and up-lifting.",
+ /// "output_format": "mp3",
+ /// "duration": 20,
+ /// "model": "stable-audio-2.5",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./output.mp3", "wb") as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task> CreateAudioStableAudio2AudioToAudioAsBytesAsResponseAsync( + string contentType, + + global::StabilityAI.CreateAudioStableAudio2AudioToAudioRequest request, + global::StabilityAI.CreateAudioStableAudio2AudioToAudioAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Audio-to-Audio
+ /// Stable Audio transforms existing audio samples into new high-quality compositions up to three minutes
+ /// long at 44.1kHz stereo using text instructions. Discover techniques for sample transformation in our
+ /// [Audio to Audio Guide](https://www.stableaudio.com/user-guide/audio-to-audio) to maximize creative control.
+ /// Read more about the model capabilities [here](https://stability.ai/news/stable-audio-2-0).
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to
+ /// [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Audio_API.ipynb)
+ /// or try Stable Audio 2.0 for free at [stableaudio.com](https://stableaudio.com).
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`. The `accept` header should be set to one of the following:
+ /// - `audio/*` to receive the audio in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the audio encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `prompt` - text to generate the audio from. Check our
+ /// [prompt guide](https://www.stableaudio.com/user-guide/audio-to-audio) for tips
+ /// - `audio` - the audio to use as the starting point for the generation
+ /// > **Notes:**
+ /// > - We do not allow copyrighted content to be uploaded to our platform.
+ /// > - Maximum request size is 50Mb.
+ /// #### **Optional Parameters:**
+ /// The body may optionally include:
+ /// - `output_format` - the format of the output audio
+ /// - `seed` - the randomness seed to use for the generation
+ /// - `steps` - the number of sampling steps
+ /// - `duration` - the number of seconds of the generated audio
+ /// - `cfg_scale` - controls how strictly the diffusion process adheres to the prompt text (only for `stable-audio-2`)
+ /// - `model` - the model to use [`stable-audio-2`, `stable-audio-2.5`]
+ /// - `strength` - controls how much influence the `audio` parameter has on the output audio
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// **Stable Audio 2.0**
+ /// By default, 20 credits per successful generation. The number of credits is determined
+ /// by the following formula: `credits = 17 + 0.06 * steps`.
+ /// Examples:
+ /// - 50 steps = 20 credits [default]
+ /// - 100 steps = 23 credits
+ /// **Stable Audio 2.5**
+ /// Requests made using the Stable Audio 2.5 model have a flat rate of 20 credits per successful result.
+ /// As always, you will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `audio/*` to receive the bytes of the audio directly. Otherwise specify `application/json` to receive the audio as base64 encoded JSON.
+ /// Default Value: audio/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// What you wish the output audio to be. A strong, descriptive prompt that clearly defines
+ /// instruments, moods, styles, and genre will lead to better results.
+ /// You can make a prompt as simple or complex as you like. Simple prompts are good for clean
+ /// output audio. Complex prompts are good for adding texture and depth to the output audio.
+ /// Check our [prompt guide](https://www.stableaudio.com/user-guide/audio-to-audio) for tips. + /// + /// + /// Controls the duration in seconds of the generated audio.
+ /// Default Value: 190 + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Controls the number of sampling steps.
+ /// - For `stable-audio-2`: accepts steps between `30` and `100` (defaults to `50`).
+ /// - For `stable-audio-2.5`: accepts steps between `4` and `8` (defaults to `8`). + /// + /// + /// How strictly the diffusion process adheres to the prompt text (higher values make your
+ /// audio closer to your prompt).
+ /// Defaults to 7 for `stable-audio-2` and 1 for `stable-audio-2.5` if not specified. + /// + /// + /// The model to use for generation.
+ /// - `stable-audio-2.5` requires 20 credits per generation
+ /// - `stable-audio-2` requires 20 credits per generation
+ /// Default Value: stable-audio-2 + /// + /// + /// Dictates the `content-type` of the generated audio.
+ /// Default Value: mp3 + /// + /// + /// The audio to be use as the starting point for the generation.
+ /// Supported Formats:
+ /// - mp3
+ /// - wav
+ /// Validation Rule:
+ /// - Audio must be between 6 and 190 seconds long
+ /// Example: ./some/audio.mp3 + /// + /// + /// The audio to be use as the starting point for the generation.
+ /// Supported Formats:
+ /// - mp3
+ /// - wav
+ /// Validation Rule:
+ /// - Audio must be between 6 and 190 seconds long
+ /// Example: ./some/audio.mp3 + /// + /// + /// Sometimes referred to as _denoising_, this parameter controls how much influence the
+ /// `audio` parameter has on the generated audio.
+ /// A value of 0 would yield audio that is identical to the input.
+ /// A value of 1 would be as if you passed in no audio at all.
+ /// Minimum value for `stable-audio-2.5` is 0.01.
+ /// Default Value: 1 + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + global::System.Threading.Tasks.Task CreateAudioStableAudio2AudioToAudioAsBytesAsync( + string contentType, + string prompt, + byte[] audio, + string audioname, + global::StabilityAI.CreateAudioStableAudio2AudioToAudioAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + double? duration = default, + double? seed = default, + int? steps = default, + double? cfgScale = default, + global::StabilityAI.CreateAudioStableAudio2AudioToAudioRequestModel? model = default, + global::StabilityAI.CreateAudioStableAudio2AudioToAudioRequestOutputFormat? outputFormat = default, + double? strength = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + + /// + /// Audio-to-Audio
+ /// Stable Audio transforms existing audio samples into new high-quality compositions up to three minutes
+ /// long at 44.1kHz stereo using text instructions. Discover techniques for sample transformation in our
+ /// [Audio to Audio Guide](https://www.stableaudio.com/user-guide/audio-to-audio) to maximize creative control.
+ /// Read more about the model capabilities [here](https://stability.ai/news/stable-audio-2-0).
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to
+ /// [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Audio_API.ipynb)
+ /// or try Stable Audio 2.0 for free at [stableaudio.com](https://stableaudio.com).
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`. The `accept` header should be set to one of the following:
+ /// - `audio/*` to receive the audio in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the audio encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `prompt` - text to generate the audio from. Check our
+ /// [prompt guide](https://www.stableaudio.com/user-guide/audio-to-audio) for tips
+ /// - `audio` - the audio to use as the starting point for the generation
+ /// > **Notes:**
+ /// > - We do not allow copyrighted content to be uploaded to our platform.
+ /// > - Maximum request size is 50Mb.
+ /// #### **Optional Parameters:**
+ /// The body may optionally include:
+ /// - `output_format` - the format of the output audio
+ /// - `seed` - the randomness seed to use for the generation
+ /// - `steps` - the number of sampling steps
+ /// - `duration` - the number of seconds of the generated audio
+ /// - `cfg_scale` - controls how strictly the diffusion process adheres to the prompt text (only for `stable-audio-2`)
+ /// - `model` - the model to use [`stable-audio-2`, `stable-audio-2.5`]
+ /// - `strength` - controls how much influence the `audio` parameter has on the output audio
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// **Stable Audio 2.0**
+ /// By default, 20 credits per successful generation. The number of credits is determined
+ /// by the following formula: `credits = 17 + 0.06 * steps`.
+ /// Examples:
+ /// - 50 steps = 20 credits [default]
+ /// - 100 steps = 23 credits
+ /// **Stable Audio 2.5**
+ /// Requests made using the Stable Audio 2.5 model have a flat rate of 20 credits per successful result.
+ /// As always, you will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `audio/*` to receive the bytes of the audio directly. Otherwise specify `application/json` to receive the audio as base64 encoded JSON.
+ /// Default Value: audio/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// What you wish the output audio to be. A strong, descriptive prompt that clearly defines
+ /// instruments, moods, styles, and genre will lead to better results.
+ /// You can make a prompt as simple or complex as you like. Simple prompts are good for clean
+ /// output audio. Complex prompts are good for adding texture and depth to the output audio.
+ /// Check our [prompt guide](https://www.stableaudio.com/user-guide/audio-to-audio) for tips. + /// + /// + /// Controls the duration in seconds of the generated audio.
+ /// Default Value: 190 + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Controls the number of sampling steps.
+ /// - For `stable-audio-2`: accepts steps between `30` and `100` (defaults to `50`).
+ /// - For `stable-audio-2.5`: accepts steps between `4` and `8` (defaults to `8`). + /// + /// + /// How strictly the diffusion process adheres to the prompt text (higher values make your
+ /// audio closer to your prompt).
+ /// Defaults to 7 for `stable-audio-2` and 1 for `stable-audio-2.5` if not specified. + /// + /// + /// The model to use for generation.
+ /// - `stable-audio-2.5` requires 20 credits per generation
+ /// - `stable-audio-2` requires 20 credits per generation
+ /// Default Value: stable-audio-2 + /// + /// + /// Dictates the `content-type` of the generated audio.
+ /// Default Value: mp3 + /// + /// + /// The audio to be use as the starting point for the generation.
+ /// Supported Formats:
+ /// - mp3
+ /// - wav
+ /// Validation Rule:
+ /// - Audio must be between 6 and 190 seconds long
+ /// Example: ./some/audio.mp3 + /// + /// + /// The audio to be use as the starting point for the generation.
+ /// Supported Formats:
+ /// - mp3
+ /// - wav
+ /// Validation Rule:
+ /// - Audio must be between 6 and 190 seconds long
+ /// Example: ./some/audio.mp3 + /// + /// + /// Sometimes referred to as _denoising_, this parameter controls how much influence the
+ /// `audio` parameter has on the generated audio.
+ /// A value of 0 would yield audio that is identical to the input.
+ /// A value of 1 would be as if you passed in no audio at all.
+ /// Minimum value for `stable-audio-2.5` is 0.01.
+ /// Default Value: 1 + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/audio/stable-audio-2/audio-to-audio",
+ /// headers={"authorization": f"Bearer sk-MYAPIKEY", "accept": "audio/*"},
+ /// files={
+ /// "audio": open("./uk-bass-base.mp3", "rb"),
+ /// },
+ /// data={
+ /// "prompt": "A song in the 3/4 time signature that features cheerful acoustic guitar, live recorded drums, and rhythmic claps, The mood is happy and up-lifting.",
+ /// "output_format": "mp3",
+ /// "duration": 20,
+ /// "model": "stable-audio-2.5",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./output.mp3", "wb") as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateAudioStableAudio2AudioToAudioAsBytesAsync( + string contentType, + string prompt, + global::System.IO.Stream audio, + string audioname, + global::StabilityAI.CreateAudioStableAudio2AudioToAudioAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + double? duration = default, + double? seed = default, + int? steps = default, + double? cfgScale = default, + global::StabilityAI.CreateAudioStableAudio2AudioToAudioRequestModel? model = default, + global::StabilityAI.CreateAudioStableAudio2AudioToAudioRequestOutputFormat? outputFormat = default, + double? strength = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Audio-to-Audio
+ /// Stable Audio transforms existing audio samples into new high-quality compositions up to three minutes
+ /// long at 44.1kHz stereo using text instructions. Discover techniques for sample transformation in our
+ /// [Audio to Audio Guide](https://www.stableaudio.com/user-guide/audio-to-audio) to maximize creative control.
+ /// Read more about the model capabilities [here](https://stability.ai/news/stable-audio-2-0).
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to
+ /// [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Audio_API.ipynb)
+ /// or try Stable Audio 2.0 for free at [stableaudio.com](https://stableaudio.com).
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`. The `accept` header should be set to one of the following:
+ /// - `audio/*` to receive the audio in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the audio encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `prompt` - text to generate the audio from. Check our
+ /// [prompt guide](https://www.stableaudio.com/user-guide/audio-to-audio) for tips
+ /// - `audio` - the audio to use as the starting point for the generation
+ /// > **Notes:**
+ /// > - We do not allow copyrighted content to be uploaded to our platform.
+ /// > - Maximum request size is 50Mb.
+ /// #### **Optional Parameters:**
+ /// The body may optionally include:
+ /// - `output_format` - the format of the output audio
+ /// - `seed` - the randomness seed to use for the generation
+ /// - `steps` - the number of sampling steps
+ /// - `duration` - the number of seconds of the generated audio
+ /// - `cfg_scale` - controls how strictly the diffusion process adheres to the prompt text (only for `stable-audio-2`)
+ /// - `model` - the model to use [`stable-audio-2`, `stable-audio-2.5`]
+ /// - `strength` - controls how much influence the `audio` parameter has on the output audio
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// **Stable Audio 2.0**
+ /// By default, 20 credits per successful generation. The number of credits is determined
+ /// by the following formula: `credits = 17 + 0.06 * steps`.
+ /// Examples:
+ /// - 50 steps = 20 credits [default]
+ /// - 100 steps = 23 credits
+ /// **Stable Audio 2.5**
+ /// Requests made using the Stable Audio 2.5 model have a flat rate of 20 credits per successful result.
+ /// As always, you will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `audio/*` to receive the bytes of the audio directly. Otherwise specify `application/json` to receive the audio as base64 encoded JSON.
+ /// Default Value: audio/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// What you wish the output audio to be. A strong, descriptive prompt that clearly defines
+ /// instruments, moods, styles, and genre will lead to better results.
+ /// You can make a prompt as simple or complex as you like. Simple prompts are good for clean
+ /// output audio. Complex prompts are good for adding texture and depth to the output audio.
+ /// Check our [prompt guide](https://www.stableaudio.com/user-guide/audio-to-audio) for tips. + /// + /// + /// Controls the duration in seconds of the generated audio.
+ /// Default Value: 190 + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Controls the number of sampling steps.
+ /// - For `stable-audio-2`: accepts steps between `30` and `100` (defaults to `50`).
+ /// - For `stable-audio-2.5`: accepts steps between `4` and `8` (defaults to `8`). + /// + /// + /// How strictly the diffusion process adheres to the prompt text (higher values make your
+ /// audio closer to your prompt).
+ /// Defaults to 7 for `stable-audio-2` and 1 for `stable-audio-2.5` if not specified. + /// + /// + /// The model to use for generation.
+ /// - `stable-audio-2.5` requires 20 credits per generation
+ /// - `stable-audio-2` requires 20 credits per generation
+ /// Default Value: stable-audio-2 + /// + /// + /// Dictates the `content-type` of the generated audio.
+ /// Default Value: mp3 + /// + /// + /// The audio to be use as the starting point for the generation.
+ /// Supported Formats:
+ /// - mp3
+ /// - wav
+ /// Validation Rule:
+ /// - Audio must be between 6 and 190 seconds long
+ /// Example: ./some/audio.mp3 + /// + /// + /// The audio to be use as the starting point for the generation.
+ /// Supported Formats:
+ /// - mp3
+ /// - wav
+ /// Validation Rule:
+ /// - Audio must be between 6 and 190 seconds long
+ /// Example: ./some/audio.mp3 + /// + /// + /// Sometimes referred to as _denoising_, this parameter controls how much influence the
+ /// `audio` parameter has on the generated audio.
+ /// A value of 0 would yield audio that is identical to the input.
+ /// A value of 1 would be as if you passed in no audio at all.
+ /// Minimum value for `stable-audio-2.5` is 0.01.
+ /// Default Value: 1 + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/audio/stable-audio-2/audio-to-audio",
+ /// headers={"authorization": f"Bearer sk-MYAPIKEY", "accept": "audio/*"},
+ /// files={
+ /// "audio": open("./uk-bass-base.mp3", "rb"),
+ /// },
+ /// data={
+ /// "prompt": "A song in the 3/4 time signature that features cheerful acoustic guitar, live recorded drums, and rhythmic claps, The mood is happy and up-lifting.",
+ /// "output_format": "mp3",
+ /// "duration": 20,
+ /// "model": "stable-audio-2.5",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./output.mp3", "wb") as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateAudioStableAudio2AudioToAudioAsBytesAsStreamAsync( + string contentType, + string prompt, + global::System.IO.Stream audio, + string audioname, + global::StabilityAI.CreateAudioStableAudio2AudioToAudioAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + double? duration = default, + double? seed = default, + int? steps = default, + double? cfgScale = default, + global::StabilityAI.CreateAudioStableAudio2AudioToAudioRequestModel? model = default, + global::StabilityAI.CreateAudioStableAudio2AudioToAudioRequestOutputFormat? outputFormat = default, + double? strength = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Audio-to-Audio
+ /// Stable Audio transforms existing audio samples into new high-quality compositions up to three minutes
+ /// long at 44.1kHz stereo using text instructions. Discover techniques for sample transformation in our
+ /// [Audio to Audio Guide](https://www.stableaudio.com/user-guide/audio-to-audio) to maximize creative control.
+ /// Read more about the model capabilities [here](https://stability.ai/news/stable-audio-2-0).
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to
+ /// [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Audio_API.ipynb)
+ /// or try Stable Audio 2.0 for free at [stableaudio.com](https://stableaudio.com).
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`. The `accept` header should be set to one of the following:
+ /// - `audio/*` to receive the audio in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the audio encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `prompt` - text to generate the audio from. Check our
+ /// [prompt guide](https://www.stableaudio.com/user-guide/audio-to-audio) for tips
+ /// - `audio` - the audio to use as the starting point for the generation
+ /// > **Notes:**
+ /// > - We do not allow copyrighted content to be uploaded to our platform.
+ /// > - Maximum request size is 50Mb.
+ /// #### **Optional Parameters:**
+ /// The body may optionally include:
+ /// - `output_format` - the format of the output audio
+ /// - `seed` - the randomness seed to use for the generation
+ /// - `steps` - the number of sampling steps
+ /// - `duration` - the number of seconds of the generated audio
+ /// - `cfg_scale` - controls how strictly the diffusion process adheres to the prompt text (only for `stable-audio-2`)
+ /// - `model` - the model to use [`stable-audio-2`, `stable-audio-2.5`]
+ /// - `strength` - controls how much influence the `audio` parameter has on the output audio
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// **Stable Audio 2.0**
+ /// By default, 20 credits per successful generation. The number of credits is determined
+ /// by the following formula: `credits = 17 + 0.06 * steps`.
+ /// Examples:
+ /// - 50 steps = 20 credits [default]
+ /// - 100 steps = 23 credits
+ /// **Stable Audio 2.5**
+ /// Requests made using the Stable Audio 2.5 model have a flat rate of 20 credits per successful result.
+ /// As always, you will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `audio/*` to receive the bytes of the audio directly. Otherwise specify `application/json` to receive the audio as base64 encoded JSON.
+ /// Default Value: audio/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// What you wish the output audio to be. A strong, descriptive prompt that clearly defines
+ /// instruments, moods, styles, and genre will lead to better results.
+ /// You can make a prompt as simple or complex as you like. Simple prompts are good for clean
+ /// output audio. Complex prompts are good for adding texture and depth to the output audio.
+ /// Check our [prompt guide](https://www.stableaudio.com/user-guide/audio-to-audio) for tips. + /// + /// + /// Controls the duration in seconds of the generated audio.
+ /// Default Value: 190 + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Controls the number of sampling steps.
+ /// - For `stable-audio-2`: accepts steps between `30` and `100` (defaults to `50`).
+ /// - For `stable-audio-2.5`: accepts steps between `4` and `8` (defaults to `8`). + /// + /// + /// How strictly the diffusion process adheres to the prompt text (higher values make your
+ /// audio closer to your prompt).
+ /// Defaults to 7 for `stable-audio-2` and 1 for `stable-audio-2.5` if not specified. + /// + /// + /// The model to use for generation.
+ /// - `stable-audio-2.5` requires 20 credits per generation
+ /// - `stable-audio-2` requires 20 credits per generation
+ /// Default Value: stable-audio-2 + /// + /// + /// Dictates the `content-type` of the generated audio.
+ /// Default Value: mp3 + /// + /// + /// The audio to be use as the starting point for the generation.
+ /// Supported Formats:
+ /// - mp3
+ /// - wav
+ /// Validation Rule:
+ /// - Audio must be between 6 and 190 seconds long
+ /// Example: ./some/audio.mp3 + /// + /// + /// The audio to be use as the starting point for the generation.
+ /// Supported Formats:
+ /// - mp3
+ /// - wav
+ /// Validation Rule:
+ /// - Audio must be between 6 and 190 seconds long
+ /// Example: ./some/audio.mp3 + /// + /// + /// Sometimes referred to as _denoising_, this parameter controls how much influence the
+ /// `audio` parameter has on the generated audio.
+ /// A value of 0 would yield audio that is identical to the input.
+ /// A value of 1 would be as if you passed in no audio at all.
+ /// Minimum value for `stable-audio-2.5` is 0.01.
+ /// Default Value: 1 + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/audio/stable-audio-2/audio-to-audio",
+ /// headers={"authorization": f"Bearer sk-MYAPIKEY", "accept": "audio/*"},
+ /// files={
+ /// "audio": open("./uk-bass-base.mp3", "rb"),
+ /// },
+ /// data={
+ /// "prompt": "A song in the 3/4 time signature that features cheerful acoustic guitar, live recorded drums, and rhythmic claps, The mood is happy and up-lifting.",
+ /// "output_format": "mp3",
+ /// "duration": 20,
+ /// "model": "stable-audio-2.5",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./output.mp3", "wb") as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task> CreateAudioStableAudio2AudioToAudioAsBytesAsResponseAsync( + string contentType, + string prompt, + global::System.IO.Stream audio, + string audioname, + global::StabilityAI.CreateAudioStableAudio2AudioToAudioAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + double? duration = default, + double? seed = default, + int? steps = default, + double? cfgScale = default, + global::StabilityAI.CreateAudioStableAudio2AudioToAudioRequestModel? model = default, + global::StabilityAI.CreateAudioStableAudio2AudioToAudioRequestOutputFormat? outputFormat = default, + double? strength = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + } +} \ No newline at end of file diff --git a/src/libs/StabilityAI/Generated/StabilityAI.IStableAudio2Client.CreateAudioStableAudio2InpaintAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.IStableAudio2Client.CreateAudioStableAudio2InpaintAsBytes.g.cs new file mode 100644 index 0000000..2cb4df1 --- /dev/null +++ b/src/libs/StabilityAI/Generated/StabilityAI.IStableAudio2Client.CreateAudioStableAudio2InpaintAsBytes.g.cs @@ -0,0 +1,806 @@ +#nullable enable + +namespace StabilityAI +{ + public partial interface IStableAudio2Client + { + /// + /// Inpaint
+ /// Stable Audio 2.5 transforms existing audio samples into new high-quality compositions up to three minutes
+ /// long at 44.1kHz stereo using text instructions.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to
+ /// [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Audio_API.ipynb).
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`. The `accept` header should be set to one of the following:
+ /// - `audio/*` to receive the audio in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the audio encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `prompt` - text to generate the audio from
+ /// - `audio` - the audio to use as the starting point for the generation
+ /// > **Notes:**
+ /// > - We do not allow copyrighted content to be uploaded to our platform.
+ /// > - Maximum request size is 50Mb.
+ /// #### **Optional Parameters:**
+ /// The body may optionally include:
+ /// - `output_format` - the format of the output audio
+ /// - `seed` - the randomness seed to use for the generation
+ /// - `duration` - the number of seconds of the generated audio
+ /// - `steps` - the number of sampling steps
+ /// - `mask_start` - start time in seconds for the audio segment to be inpainted (e.g., 30.0 for 30.0 seconds)
+ /// - `mask_end` - end time in seconds for the audio segment to be inpainted (e.g., 190.0 for 190.0 seconds)
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// **Stable Audio 2.5**
+ /// Flat rate of 20 credits per successful generation.
+ /// As always, you will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `audio/*` to receive the bytes of the audio directly. Otherwise specify `application/json` to receive the audio as base64 encoded JSON.
+ /// Default Value: audio/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/audio/stable-audio-2/inpaint",
+ /// headers={"authorization": f"Bearer sk-MYAPIKEY", "accept": "audio/*"},
+ /// files={
+ /// "audio": open("./uk-bass-base.mp3", "rb"),
+ /// },
+ /// data={
+ /// "prompt": "A song in the 3/4 time signature that features cheerful acoustic guitar, live recorded drums, and rhythmic claps, The mood is happy and up-lifting.",
+ /// "output_format": "mp3",
+ /// "duration": 20,
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./output.mp3", "wb") as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateAudioStableAudio2InpaintAsBytesAsync( + string contentType, + + global::StabilityAI.CreateAudioStableAudio2InpaintRequest request, + global::StabilityAI.CreateAudioStableAudio2InpaintAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Inpaint
+ /// Stable Audio 2.5 transforms existing audio samples into new high-quality compositions up to three minutes
+ /// long at 44.1kHz stereo using text instructions.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to
+ /// [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Audio_API.ipynb).
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`. The `accept` header should be set to one of the following:
+ /// - `audio/*` to receive the audio in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the audio encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `prompt` - text to generate the audio from
+ /// - `audio` - the audio to use as the starting point for the generation
+ /// > **Notes:**
+ /// > - We do not allow copyrighted content to be uploaded to our platform.
+ /// > - Maximum request size is 50Mb.
+ /// #### **Optional Parameters:**
+ /// The body may optionally include:
+ /// - `output_format` - the format of the output audio
+ /// - `seed` - the randomness seed to use for the generation
+ /// - `duration` - the number of seconds of the generated audio
+ /// - `steps` - the number of sampling steps
+ /// - `mask_start` - start time in seconds for the audio segment to be inpainted (e.g., 30.0 for 30.0 seconds)
+ /// - `mask_end` - end time in seconds for the audio segment to be inpainted (e.g., 190.0 for 190.0 seconds)
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// **Stable Audio 2.5**
+ /// Flat rate of 20 credits per successful generation.
+ /// As always, you will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `audio/*` to receive the bytes of the audio directly. Otherwise specify `application/json` to receive the audio as base64 encoded JSON.
+ /// Default Value: audio/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/audio/stable-audio-2/inpaint",
+ /// headers={"authorization": f"Bearer sk-MYAPIKEY", "accept": "audio/*"},
+ /// files={
+ /// "audio": open("./uk-bass-base.mp3", "rb"),
+ /// },
+ /// data={
+ /// "prompt": "A song in the 3/4 time signature that features cheerful acoustic guitar, live recorded drums, and rhythmic claps, The mood is happy and up-lifting.",
+ /// "output_format": "mp3",
+ /// "duration": 20,
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./output.mp3", "wb") as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateAudioStableAudio2InpaintAsBytesAsStreamAsync( + string contentType, + + global::StabilityAI.CreateAudioStableAudio2InpaintRequest request, + global::StabilityAI.CreateAudioStableAudio2InpaintAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Inpaint
+ /// Stable Audio 2.5 transforms existing audio samples into new high-quality compositions up to three minutes
+ /// long at 44.1kHz stereo using text instructions.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to
+ /// [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Audio_API.ipynb).
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`. The `accept` header should be set to one of the following:
+ /// - `audio/*` to receive the audio in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the audio encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `prompt` - text to generate the audio from
+ /// - `audio` - the audio to use as the starting point for the generation
+ /// > **Notes:**
+ /// > - We do not allow copyrighted content to be uploaded to our platform.
+ /// > - Maximum request size is 50Mb.
+ /// #### **Optional Parameters:**
+ /// The body may optionally include:
+ /// - `output_format` - the format of the output audio
+ /// - `seed` - the randomness seed to use for the generation
+ /// - `duration` - the number of seconds of the generated audio
+ /// - `steps` - the number of sampling steps
+ /// - `mask_start` - start time in seconds for the audio segment to be inpainted (e.g., 30.0 for 30.0 seconds)
+ /// - `mask_end` - end time in seconds for the audio segment to be inpainted (e.g., 190.0 for 190.0 seconds)
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// **Stable Audio 2.5**
+ /// Flat rate of 20 credits per successful generation.
+ /// As always, you will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `audio/*` to receive the bytes of the audio directly. Otherwise specify `application/json` to receive the audio as base64 encoded JSON.
+ /// Default Value: audio/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/audio/stable-audio-2/inpaint",
+ /// headers={"authorization": f"Bearer sk-MYAPIKEY", "accept": "audio/*"},
+ /// files={
+ /// "audio": open("./uk-bass-base.mp3", "rb"),
+ /// },
+ /// data={
+ /// "prompt": "A song in the 3/4 time signature that features cheerful acoustic guitar, live recorded drums, and rhythmic claps, The mood is happy and up-lifting.",
+ /// "output_format": "mp3",
+ /// "duration": 20,
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./output.mp3", "wb") as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task> CreateAudioStableAudio2InpaintAsBytesAsResponseAsync( + string contentType, + + global::StabilityAI.CreateAudioStableAudio2InpaintRequest request, + global::StabilityAI.CreateAudioStableAudio2InpaintAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Inpaint
+ /// Stable Audio 2.5 transforms existing audio samples into new high-quality compositions up to three minutes
+ /// long at 44.1kHz stereo using text instructions.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to
+ /// [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Audio_API.ipynb).
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`. The `accept` header should be set to one of the following:
+ /// - `audio/*` to receive the audio in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the audio encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `prompt` - text to generate the audio from
+ /// - `audio` - the audio to use as the starting point for the generation
+ /// > **Notes:**
+ /// > - We do not allow copyrighted content to be uploaded to our platform.
+ /// > - Maximum request size is 50Mb.
+ /// #### **Optional Parameters:**
+ /// The body may optionally include:
+ /// - `output_format` - the format of the output audio
+ /// - `seed` - the randomness seed to use for the generation
+ /// - `duration` - the number of seconds of the generated audio
+ /// - `steps` - the number of sampling steps
+ /// - `mask_start` - start time in seconds for the audio segment to be inpainted (e.g., 30.0 for 30.0 seconds)
+ /// - `mask_end` - end time in seconds for the audio segment to be inpainted (e.g., 190.0 for 190.0 seconds)
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// **Stable Audio 2.5**
+ /// Flat rate of 20 credits per successful generation.
+ /// As always, you will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `audio/*` to receive the bytes of the audio directly. Otherwise specify `application/json` to receive the audio as base64 encoded JSON.
+ /// Default Value: audio/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// What you wish the output audio to be. A strong, descriptive prompt that clearly defines
+ /// instruments, moods, styles, and genre will lead to better results.
+ /// You can make a prompt as simple or complex as you like. Simple prompts are good for clean
+ /// output audio. Complex prompts are good for adding texture and depth to the output audio. + /// + /// + /// Controls the duration in seconds of the generated audio.
+ /// Default Value: 190 + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Controls the number of sampling steps.
+ /// Default Value: 8 + /// + /// + /// Dictates the `content-type` of the generated audio.
+ /// Default Value: mp3 + /// + /// + /// The audio to be use as the starting point for the generation.
+ /// Supported Formats:
+ /// - mp3
+ /// - wav
+ /// Validation Rule:
+ /// - Audio must be between 6 and 190 seconds long
+ /// Example: ./some/audio.mp3 + /// + /// + /// The audio to be use as the starting point for the generation.
+ /// Supported Formats:
+ /// - mp3
+ /// - wav
+ /// Validation Rule:
+ /// - Audio must be between 6 and 190 seconds long
+ /// Example: ./some/audio.mp3 + /// + /// + /// Default Value: 30 + /// + /// + /// Default Value: 190 + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + global::System.Threading.Tasks.Task CreateAudioStableAudio2InpaintAsBytesAsync( + string contentType, + string prompt, + byte[] audio, + string audioname, + global::StabilityAI.CreateAudioStableAudio2InpaintAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + double? duration = default, + double? seed = default, + int? steps = default, + global::StabilityAI.CreateAudioStableAudio2InpaintRequestOutputFormat? outputFormat = default, + double? maskStart = default, + double? maskEnd = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + + /// + /// Inpaint
+ /// Stable Audio 2.5 transforms existing audio samples into new high-quality compositions up to three minutes
+ /// long at 44.1kHz stereo using text instructions.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to
+ /// [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Audio_API.ipynb).
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`. The `accept` header should be set to one of the following:
+ /// - `audio/*` to receive the audio in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the audio encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `prompt` - text to generate the audio from
+ /// - `audio` - the audio to use as the starting point for the generation
+ /// > **Notes:**
+ /// > - We do not allow copyrighted content to be uploaded to our platform.
+ /// > - Maximum request size is 50Mb.
+ /// #### **Optional Parameters:**
+ /// The body may optionally include:
+ /// - `output_format` - the format of the output audio
+ /// - `seed` - the randomness seed to use for the generation
+ /// - `duration` - the number of seconds of the generated audio
+ /// - `steps` - the number of sampling steps
+ /// - `mask_start` - start time in seconds for the audio segment to be inpainted (e.g., 30.0 for 30.0 seconds)
+ /// - `mask_end` - end time in seconds for the audio segment to be inpainted (e.g., 190.0 for 190.0 seconds)
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// **Stable Audio 2.5**
+ /// Flat rate of 20 credits per successful generation.
+ /// As always, you will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `audio/*` to receive the bytes of the audio directly. Otherwise specify `application/json` to receive the audio as base64 encoded JSON.
+ /// Default Value: audio/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// What you wish the output audio to be. A strong, descriptive prompt that clearly defines
+ /// instruments, moods, styles, and genre will lead to better results.
+ /// You can make a prompt as simple or complex as you like. Simple prompts are good for clean
+ /// output audio. Complex prompts are good for adding texture and depth to the output audio. + /// + /// + /// Controls the duration in seconds of the generated audio.
+ /// Default Value: 190 + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Controls the number of sampling steps.
+ /// Default Value: 8 + /// + /// + /// Dictates the `content-type` of the generated audio.
+ /// Default Value: mp3 + /// + /// + /// The audio to be use as the starting point for the generation.
+ /// Supported Formats:
+ /// - mp3
+ /// - wav
+ /// Validation Rule:
+ /// - Audio must be between 6 and 190 seconds long
+ /// Example: ./some/audio.mp3 + /// + /// + /// The audio to be use as the starting point for the generation.
+ /// Supported Formats:
+ /// - mp3
+ /// - wav
+ /// Validation Rule:
+ /// - Audio must be between 6 and 190 seconds long
+ /// Example: ./some/audio.mp3 + /// + /// + /// Default Value: 30 + /// + /// + /// Default Value: 190 + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/audio/stable-audio-2/inpaint",
+ /// headers={"authorization": f"Bearer sk-MYAPIKEY", "accept": "audio/*"},
+ /// files={
+ /// "audio": open("./uk-bass-base.mp3", "rb"),
+ /// },
+ /// data={
+ /// "prompt": "A song in the 3/4 time signature that features cheerful acoustic guitar, live recorded drums, and rhythmic claps, The mood is happy and up-lifting.",
+ /// "output_format": "mp3",
+ /// "duration": 20,
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./output.mp3", "wb") as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateAudioStableAudio2InpaintAsBytesAsync( + string contentType, + string prompt, + global::System.IO.Stream audio, + string audioname, + global::StabilityAI.CreateAudioStableAudio2InpaintAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + double? duration = default, + double? seed = default, + int? steps = default, + global::StabilityAI.CreateAudioStableAudio2InpaintRequestOutputFormat? outputFormat = default, + double? maskStart = default, + double? maskEnd = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Inpaint
+ /// Stable Audio 2.5 transforms existing audio samples into new high-quality compositions up to three minutes
+ /// long at 44.1kHz stereo using text instructions.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to
+ /// [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Audio_API.ipynb).
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`. The `accept` header should be set to one of the following:
+ /// - `audio/*` to receive the audio in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the audio encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `prompt` - text to generate the audio from
+ /// - `audio` - the audio to use as the starting point for the generation
+ /// > **Notes:**
+ /// > - We do not allow copyrighted content to be uploaded to our platform.
+ /// > - Maximum request size is 50Mb.
+ /// #### **Optional Parameters:**
+ /// The body may optionally include:
+ /// - `output_format` - the format of the output audio
+ /// - `seed` - the randomness seed to use for the generation
+ /// - `duration` - the number of seconds of the generated audio
+ /// - `steps` - the number of sampling steps
+ /// - `mask_start` - start time in seconds for the audio segment to be inpainted (e.g., 30.0 for 30.0 seconds)
+ /// - `mask_end` - end time in seconds for the audio segment to be inpainted (e.g., 190.0 for 190.0 seconds)
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// **Stable Audio 2.5**
+ /// Flat rate of 20 credits per successful generation.
+ /// As always, you will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `audio/*` to receive the bytes of the audio directly. Otherwise specify `application/json` to receive the audio as base64 encoded JSON.
+ /// Default Value: audio/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// What you wish the output audio to be. A strong, descriptive prompt that clearly defines
+ /// instruments, moods, styles, and genre will lead to better results.
+ /// You can make a prompt as simple or complex as you like. Simple prompts are good for clean
+ /// output audio. Complex prompts are good for adding texture and depth to the output audio. + /// + /// + /// Controls the duration in seconds of the generated audio.
+ /// Default Value: 190 + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Controls the number of sampling steps.
+ /// Default Value: 8 + /// + /// + /// Dictates the `content-type` of the generated audio.
+ /// Default Value: mp3 + /// + /// + /// The audio to be use as the starting point for the generation.
+ /// Supported Formats:
+ /// - mp3
+ /// - wav
+ /// Validation Rule:
+ /// - Audio must be between 6 and 190 seconds long
+ /// Example: ./some/audio.mp3 + /// + /// + /// The audio to be use as the starting point for the generation.
+ /// Supported Formats:
+ /// - mp3
+ /// - wav
+ /// Validation Rule:
+ /// - Audio must be between 6 and 190 seconds long
+ /// Example: ./some/audio.mp3 + /// + /// + /// Default Value: 30 + /// + /// + /// Default Value: 190 + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/audio/stable-audio-2/inpaint",
+ /// headers={"authorization": f"Bearer sk-MYAPIKEY", "accept": "audio/*"},
+ /// files={
+ /// "audio": open("./uk-bass-base.mp3", "rb"),
+ /// },
+ /// data={
+ /// "prompt": "A song in the 3/4 time signature that features cheerful acoustic guitar, live recorded drums, and rhythmic claps, The mood is happy and up-lifting.",
+ /// "output_format": "mp3",
+ /// "duration": 20,
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./output.mp3", "wb") as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateAudioStableAudio2InpaintAsBytesAsStreamAsync( + string contentType, + string prompt, + global::System.IO.Stream audio, + string audioname, + global::StabilityAI.CreateAudioStableAudio2InpaintAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + double? duration = default, + double? seed = default, + int? steps = default, + global::StabilityAI.CreateAudioStableAudio2InpaintRequestOutputFormat? outputFormat = default, + double? maskStart = default, + double? maskEnd = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Inpaint
+ /// Stable Audio 2.5 transforms existing audio samples into new high-quality compositions up to three minutes
+ /// long at 44.1kHz stereo using text instructions.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to
+ /// [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Audio_API.ipynb).
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`. The `accept` header should be set to one of the following:
+ /// - `audio/*` to receive the audio in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the audio encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `prompt` - text to generate the audio from
+ /// - `audio` - the audio to use as the starting point for the generation
+ /// > **Notes:**
+ /// > - We do not allow copyrighted content to be uploaded to our platform.
+ /// > - Maximum request size is 50Mb.
+ /// #### **Optional Parameters:**
+ /// The body may optionally include:
+ /// - `output_format` - the format of the output audio
+ /// - `seed` - the randomness seed to use for the generation
+ /// - `duration` - the number of seconds of the generated audio
+ /// - `steps` - the number of sampling steps
+ /// - `mask_start` - start time in seconds for the audio segment to be inpainted (e.g., 30.0 for 30.0 seconds)
+ /// - `mask_end` - end time in seconds for the audio segment to be inpainted (e.g., 190.0 for 190.0 seconds)
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// **Stable Audio 2.5**
+ /// Flat rate of 20 credits per successful generation.
+ /// As always, you will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `audio/*` to receive the bytes of the audio directly. Otherwise specify `application/json` to receive the audio as base64 encoded JSON.
+ /// Default Value: audio/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// What you wish the output audio to be. A strong, descriptive prompt that clearly defines
+ /// instruments, moods, styles, and genre will lead to better results.
+ /// You can make a prompt as simple or complex as you like. Simple prompts are good for clean
+ /// output audio. Complex prompts are good for adding texture and depth to the output audio. + /// + /// + /// Controls the duration in seconds of the generated audio.
+ /// Default Value: 190 + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Controls the number of sampling steps.
+ /// Default Value: 8 + /// + /// + /// Dictates the `content-type` of the generated audio.
+ /// Default Value: mp3 + /// + /// + /// The audio to be use as the starting point for the generation.
+ /// Supported Formats:
+ /// - mp3
+ /// - wav
+ /// Validation Rule:
+ /// - Audio must be between 6 and 190 seconds long
+ /// Example: ./some/audio.mp3 + /// + /// + /// The audio to be use as the starting point for the generation.
+ /// Supported Formats:
+ /// - mp3
+ /// - wav
+ /// Validation Rule:
+ /// - Audio must be between 6 and 190 seconds long
+ /// Example: ./some/audio.mp3 + /// + /// + /// Default Value: 30 + /// + /// + /// Default Value: 190 + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/audio/stable-audio-2/inpaint",
+ /// headers={"authorization": f"Bearer sk-MYAPIKEY", "accept": "audio/*"},
+ /// files={
+ /// "audio": open("./uk-bass-base.mp3", "rb"),
+ /// },
+ /// data={
+ /// "prompt": "A song in the 3/4 time signature that features cheerful acoustic guitar, live recorded drums, and rhythmic claps, The mood is happy and up-lifting.",
+ /// "output_format": "mp3",
+ /// "duration": 20,
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./output.mp3", "wb") as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task> CreateAudioStableAudio2InpaintAsBytesAsResponseAsync( + string contentType, + string prompt, + global::System.IO.Stream audio, + string audioname, + global::StabilityAI.CreateAudioStableAudio2InpaintAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + double? duration = default, + double? seed = default, + int? steps = default, + global::StabilityAI.CreateAudioStableAudio2InpaintRequestOutputFormat? outputFormat = default, + double? maskStart = default, + double? maskEnd = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + } +} \ No newline at end of file diff --git a/src/libs/StabilityAI/Generated/StabilityAI.IStableAudio2Client.CreateAudioStableAudio2TextToAudioAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.IStableAudio2Client.CreateAudioStableAudio2TextToAudioAsBytes.g.cs new file mode 100644 index 0000000..61179ae --- /dev/null +++ b/src/libs/StabilityAI/Generated/StabilityAI.IStableAudio2Client.CreateAudioStableAudio2TextToAudioAsBytes.g.cs @@ -0,0 +1,396 @@ +#nullable enable + +namespace StabilityAI +{ + public partial interface IStableAudio2Client + { + /// + /// Text-to-Audio
+ /// Stable Audio generates high-quality music and sound effects up to three minutes long at
+ /// 44.1kHz stereo from text descriptions. Learn how to craft effective prompts in our
+ /// [Prompt Guide](https://www.stableaudio.com/user-guide/text-to-audio) to get the best results
+ /// from your generations.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to
+ /// [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Audio_API.ipynb)
+ /// or try Stable Audio 2.0 for free at [stableaudio.com](https://stableaudio.com).
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`. The `accept` header should be set to one of the following:
+ /// - `audio/*` to receive the audio in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the audio encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `prompt` - text to generate the audio from. Check our
+ /// [prompt guide](https://www.stableaudio.com/user-guide/text-to-audio) for tips
+ /// #### **Optional Parameters:**
+ /// The body may optionally include:
+ /// - `output_format` - the format of the output audio
+ /// - `seed` - the randomness seed to use for the generation
+ /// - `steps` - the number of sampling steps
+ /// - `duration` - the number of seconds of the generated audio
+ /// - `cfg_scale` - controls how strictly the diffusion process adheres to the prompt text (only for `stable-audio-2`)
+ /// - `model` - the model to use [`stable-audio-2`, `stable-audio-2.5`]
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// **Stable Audio 2.0**
+ /// By default, 20 credits per successful generation. The number of credits is determined
+ /// by the following formula: `credits = 17 + 0.06 * steps`.
+ /// Examples:
+ /// - 50 steps = 20 credits [default]
+ /// - 100 steps = 23 credits
+ /// **Stable Audio 2.5**
+ /// Requests made using the Stable Audio 2.5 model have a flat rate of 20 credits per successful result.
+ /// As always, you will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `audio/*` to receive the bytes of the audio directly. Otherwise specify `application/json` to receive the audio as base64 encoded JSON.
+ /// Default Value: audio/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/audio/stable-audio-2/text-to-audio",
+ /// headers={"authorization": f"Bearer sk-MYAPIKEY", "accept": "audio/*"},
+ /// files={"none": ""},
+ /// data={
+ /// "prompt": "A song in the 3/4 time signature that features cheerful acoustic guitar, live recorded drums, and rhythmic claps, The mood is happy and up-lifting.",
+ /// "output_format": "mp3",
+ /// "duration": 20,
+ /// "model": "stable-audio-2.5",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./output.mp3", "wb") as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateAudioStableAudio2TextToAudioAsBytesAsync( + string contentType, + + global::StabilityAI.CreateAudioStableAudio2TextToAudioRequest request, + global::StabilityAI.CreateAudioStableAudio2TextToAudioAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Text-to-Audio
+ /// Stable Audio generates high-quality music and sound effects up to three minutes long at
+ /// 44.1kHz stereo from text descriptions. Learn how to craft effective prompts in our
+ /// [Prompt Guide](https://www.stableaudio.com/user-guide/text-to-audio) to get the best results
+ /// from your generations.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to
+ /// [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Audio_API.ipynb)
+ /// or try Stable Audio 2.0 for free at [stableaudio.com](https://stableaudio.com).
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`. The `accept` header should be set to one of the following:
+ /// - `audio/*` to receive the audio in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the audio encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `prompt` - text to generate the audio from. Check our
+ /// [prompt guide](https://www.stableaudio.com/user-guide/text-to-audio) for tips
+ /// #### **Optional Parameters:**
+ /// The body may optionally include:
+ /// - `output_format` - the format of the output audio
+ /// - `seed` - the randomness seed to use for the generation
+ /// - `steps` - the number of sampling steps
+ /// - `duration` - the number of seconds of the generated audio
+ /// - `cfg_scale` - controls how strictly the diffusion process adheres to the prompt text (only for `stable-audio-2`)
+ /// - `model` - the model to use [`stable-audio-2`, `stable-audio-2.5`]
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// **Stable Audio 2.0**
+ /// By default, 20 credits per successful generation. The number of credits is determined
+ /// by the following formula: `credits = 17 + 0.06 * steps`.
+ /// Examples:
+ /// - 50 steps = 20 credits [default]
+ /// - 100 steps = 23 credits
+ /// **Stable Audio 2.5**
+ /// Requests made using the Stable Audio 2.5 model have a flat rate of 20 credits per successful result.
+ /// As always, you will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `audio/*` to receive the bytes of the audio directly. Otherwise specify `application/json` to receive the audio as base64 encoded JSON.
+ /// Default Value: audio/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/audio/stable-audio-2/text-to-audio",
+ /// headers={"authorization": f"Bearer sk-MYAPIKEY", "accept": "audio/*"},
+ /// files={"none": ""},
+ /// data={
+ /// "prompt": "A song in the 3/4 time signature that features cheerful acoustic guitar, live recorded drums, and rhythmic claps, The mood is happy and up-lifting.",
+ /// "output_format": "mp3",
+ /// "duration": 20,
+ /// "model": "stable-audio-2.5",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./output.mp3", "wb") as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateAudioStableAudio2TextToAudioAsBytesAsStreamAsync( + string contentType, + + global::StabilityAI.CreateAudioStableAudio2TextToAudioRequest request, + global::StabilityAI.CreateAudioStableAudio2TextToAudioAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Text-to-Audio
+ /// Stable Audio generates high-quality music and sound effects up to three minutes long at
+ /// 44.1kHz stereo from text descriptions. Learn how to craft effective prompts in our
+ /// [Prompt Guide](https://www.stableaudio.com/user-guide/text-to-audio) to get the best results
+ /// from your generations.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to
+ /// [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Audio_API.ipynb)
+ /// or try Stable Audio 2.0 for free at [stableaudio.com](https://stableaudio.com).
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`. The `accept` header should be set to one of the following:
+ /// - `audio/*` to receive the audio in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the audio encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `prompt` - text to generate the audio from. Check our
+ /// [prompt guide](https://www.stableaudio.com/user-guide/text-to-audio) for tips
+ /// #### **Optional Parameters:**
+ /// The body may optionally include:
+ /// - `output_format` - the format of the output audio
+ /// - `seed` - the randomness seed to use for the generation
+ /// - `steps` - the number of sampling steps
+ /// - `duration` - the number of seconds of the generated audio
+ /// - `cfg_scale` - controls how strictly the diffusion process adheres to the prompt text (only for `stable-audio-2`)
+ /// - `model` - the model to use [`stable-audio-2`, `stable-audio-2.5`]
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// **Stable Audio 2.0**
+ /// By default, 20 credits per successful generation. The number of credits is determined
+ /// by the following formula: `credits = 17 + 0.06 * steps`.
+ /// Examples:
+ /// - 50 steps = 20 credits [default]
+ /// - 100 steps = 23 credits
+ /// **Stable Audio 2.5**
+ /// Requests made using the Stable Audio 2.5 model have a flat rate of 20 credits per successful result.
+ /// As always, you will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `audio/*` to receive the bytes of the audio directly. Otherwise specify `application/json` to receive the audio as base64 encoded JSON.
+ /// Default Value: audio/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/audio/stable-audio-2/text-to-audio",
+ /// headers={"authorization": f"Bearer sk-MYAPIKEY", "accept": "audio/*"},
+ /// files={"none": ""},
+ /// data={
+ /// "prompt": "A song in the 3/4 time signature that features cheerful acoustic guitar, live recorded drums, and rhythmic claps, The mood is happy and up-lifting.",
+ /// "output_format": "mp3",
+ /// "duration": 20,
+ /// "model": "stable-audio-2.5",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./output.mp3", "wb") as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task> CreateAudioStableAudio2TextToAudioAsBytesAsResponseAsync( + string contentType, + + global::StabilityAI.CreateAudioStableAudio2TextToAudioRequest request, + global::StabilityAI.CreateAudioStableAudio2TextToAudioAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Text-to-Audio
+ /// Stable Audio generates high-quality music and sound effects up to three minutes long at
+ /// 44.1kHz stereo from text descriptions. Learn how to craft effective prompts in our
+ /// [Prompt Guide](https://www.stableaudio.com/user-guide/text-to-audio) to get the best results
+ /// from your generations.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to
+ /// [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Audio_API.ipynb)
+ /// or try Stable Audio 2.0 for free at [stableaudio.com](https://stableaudio.com).
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`. The `accept` header should be set to one of the following:
+ /// - `audio/*` to receive the audio in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the audio encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `prompt` - text to generate the audio from. Check our
+ /// [prompt guide](https://www.stableaudio.com/user-guide/text-to-audio) for tips
+ /// #### **Optional Parameters:**
+ /// The body may optionally include:
+ /// - `output_format` - the format of the output audio
+ /// - `seed` - the randomness seed to use for the generation
+ /// - `steps` - the number of sampling steps
+ /// - `duration` - the number of seconds of the generated audio
+ /// - `cfg_scale` - controls how strictly the diffusion process adheres to the prompt text (only for `stable-audio-2`)
+ /// - `model` - the model to use [`stable-audio-2`, `stable-audio-2.5`]
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// **Stable Audio 2.0**
+ /// By default, 20 credits per successful generation. The number of credits is determined
+ /// by the following formula: `credits = 17 + 0.06 * steps`.
+ /// Examples:
+ /// - 50 steps = 20 credits [default]
+ /// - 100 steps = 23 credits
+ /// **Stable Audio 2.5**
+ /// Requests made using the Stable Audio 2.5 model have a flat rate of 20 credits per successful result.
+ /// As always, you will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `audio/*` to receive the bytes of the audio directly. Otherwise specify `application/json` to receive the audio as base64 encoded JSON.
+ /// Default Value: audio/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// What you wish the output audio to be. A strong, descriptive prompt that clearly defines
+ /// instruments, moods, styles, and genre will lead to better results.
+ /// You can make a prompt as simple or complex as you like. Simple prompts are good for clean
+ /// output audio. Complex prompts are good for adding texture and depth to the output audio.
+ /// Check our [prompt guide](https://www.stableaudio.com/user-guide/text-to-audio) for tips. + /// + /// + /// Controls the duration in seconds of the generated audio.
+ /// Default Value: 190 + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Controls the number of sampling steps.
+ /// - For `stable-audio-2`: accepts steps between `30` and `100` (defaults to `50`).
+ /// - For `stable-audio-2.5`: accepts steps between `4` and `8` (defaults to `8`). + /// + /// + /// How strictly the diffusion process adheres to the prompt text (higher values make your
+ /// audio closer to your prompt).
+ /// Defaults to 7 for `stable-audio-2` and 1 for `stable-audio-2.5` if not specified. + /// + /// + /// The model to use for generation.
+ /// - `stable-audio-2.5` requires 20 credits per generation
+ /// - `stable-audio-2` requires 20 credits per generation
+ /// Default Value: stable-audio-2 + /// + /// + /// Dictates the `content-type` of the generated audio.
+ /// Default Value: mp3 + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + global::System.Threading.Tasks.Task CreateAudioStableAudio2TextToAudioAsBytesAsync( + string contentType, + string prompt, + global::StabilityAI.CreateAudioStableAudio2TextToAudioAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + double? duration = default, + double? seed = default, + int? steps = default, + double? cfgScale = default, + global::StabilityAI.CreateAudioStableAudio2TextToAudioRequestModel? model = default, + global::StabilityAI.CreateAudioStableAudio2TextToAudioRequestOutputFormat? outputFormat = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + } +} \ No newline at end of file diff --git a/src/libs/StabilityAI/Generated/StabilityAI.IUpscaleClient.CreateStableImageUpscaleConservativeAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.IUpscaleClient.CreateStableImageUpscaleConservativeAsBytes.g.cs new file mode 100644 index 0000000..7079057 --- /dev/null +++ b/src/libs/StabilityAI/Generated/StabilityAI.IUpscaleClient.CreateStableImageUpscaleConservativeAsBytes.g.cs @@ -0,0 +1,762 @@ +#nullable enable + +namespace StabilityAI +{ + public partial interface IUpscaleClient + { + /// + /// Conservative
+ /// Takes images between 64x64 and 1 megapixel and upscales them all the way to 4K resolution. Put more generally, it can upscale images ~20-40x times while preserving all aspects. Conservative Upscale minimizes alterations to the image and should not be used to reimagine an image.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// - `prompt`
+ /// Optionally, the body of the request may also include:
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `creativity`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 40 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/upscale/conservative",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./low-res-flower.jpg", "rb"),
+ /// },
+ /// data={
+ /// "prompt": "a flower",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./flower.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateStableImageUpscaleConservativeAsBytesAsync( + string contentType, + + global::StabilityAI.CreateStableImageUpscaleConservativeRequest request, + global::StabilityAI.CreateStableImageUpscaleConservativeAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Conservative
+ /// Takes images between 64x64 and 1 megapixel and upscales them all the way to 4K resolution. Put more generally, it can upscale images ~20-40x times while preserving all aspects. Conservative Upscale minimizes alterations to the image and should not be used to reimagine an image.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// - `prompt`
+ /// Optionally, the body of the request may also include:
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `creativity`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 40 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/upscale/conservative",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./low-res-flower.jpg", "rb"),
+ /// },
+ /// data={
+ /// "prompt": "a flower",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./flower.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateStableImageUpscaleConservativeAsBytesAsStreamAsync( + string contentType, + + global::StabilityAI.CreateStableImageUpscaleConservativeRequest request, + global::StabilityAI.CreateStableImageUpscaleConservativeAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Conservative
+ /// Takes images between 64x64 and 1 megapixel and upscales them all the way to 4K resolution. Put more generally, it can upscale images ~20-40x times while preserving all aspects. Conservative Upscale minimizes alterations to the image and should not be used to reimagine an image.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// - `prompt`
+ /// Optionally, the body of the request may also include:
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `creativity`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 40 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/upscale/conservative",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./low-res-flower.jpg", "rb"),
+ /// },
+ /// data={
+ /// "prompt": "a flower",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./flower.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task> CreateStableImageUpscaleConservativeAsBytesAsResponseAsync( + string contentType, + + global::StabilityAI.CreateStableImageUpscaleConservativeRequest request, + global::StabilityAI.CreateStableImageUpscaleConservativeAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Conservative
+ /// Takes images between 64x64 and 1 megapixel and upscales them all the way to 4K resolution. Put more generally, it can upscale images ~20-40x times while preserving all aspects. Conservative Upscale minimizes alterations to the image and should not be used to reimagine an image.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// - `prompt`
+ /// Optionally, the body of the request may also include:
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `creativity`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 40 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// The image you wish to upscale.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// The image you wish to upscale.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Controls the likelihood of creating additional details not heavily conditioned by the init image.
+ /// Default Value: 0.35F + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + global::System.Threading.Tasks.Task CreateStableImageUpscaleConservativeAsBytesAsync( + string contentType, + byte[] image, + string imagename, + string prompt, + global::StabilityAI.CreateStableImageUpscaleConservativeAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + string? negativePrompt = default, + double? seed = default, + global::StabilityAI.CreateStableImageUpscaleConservativeRequestOutputFormat? outputFormat = default, + double? creativity = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + + /// + /// Conservative
+ /// Takes images between 64x64 and 1 megapixel and upscales them all the way to 4K resolution. Put more generally, it can upscale images ~20-40x times while preserving all aspects. Conservative Upscale minimizes alterations to the image and should not be used to reimagine an image.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// - `prompt`
+ /// Optionally, the body of the request may also include:
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `creativity`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 40 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// The image you wish to upscale.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// The image you wish to upscale.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Controls the likelihood of creating additional details not heavily conditioned by the init image.
+ /// Default Value: 0.35F + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/upscale/conservative",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./low-res-flower.jpg", "rb"),
+ /// },
+ /// data={
+ /// "prompt": "a flower",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./flower.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateStableImageUpscaleConservativeAsBytesAsync( + string contentType, + global::System.IO.Stream image, + string imagename, + string prompt, + global::StabilityAI.CreateStableImageUpscaleConservativeAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + string? negativePrompt = default, + double? seed = default, + global::StabilityAI.CreateStableImageUpscaleConservativeRequestOutputFormat? outputFormat = default, + double? creativity = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Conservative
+ /// Takes images between 64x64 and 1 megapixel and upscales them all the way to 4K resolution. Put more generally, it can upscale images ~20-40x times while preserving all aspects. Conservative Upscale minimizes alterations to the image and should not be used to reimagine an image.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// - `prompt`
+ /// Optionally, the body of the request may also include:
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `creativity`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 40 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// The image you wish to upscale.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// The image you wish to upscale.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Controls the likelihood of creating additional details not heavily conditioned by the init image.
+ /// Default Value: 0.35F + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/upscale/conservative",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./low-res-flower.jpg", "rb"),
+ /// },
+ /// data={
+ /// "prompt": "a flower",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./flower.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateStableImageUpscaleConservativeAsBytesAsStreamAsync( + string contentType, + global::System.IO.Stream image, + string imagename, + string prompt, + global::StabilityAI.CreateStableImageUpscaleConservativeAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + string? negativePrompt = default, + double? seed = default, + global::StabilityAI.CreateStableImageUpscaleConservativeRequestOutputFormat? outputFormat = default, + double? creativity = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Conservative
+ /// Takes images between 64x64 and 1 megapixel and upscales them all the way to 4K resolution. Put more generally, it can upscale images ~20-40x times while preserving all aspects. Conservative Upscale minimizes alterations to the image and should not be used to reimagine an image.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// - `prompt`
+ /// Optionally, the body of the request may also include:
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `creativity`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 40 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// The image you wish to upscale.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// The image you wish to upscale.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Controls the likelihood of creating additional details not heavily conditioned by the init image.
+ /// Default Value: 0.35F + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/upscale/conservative",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./low-res-flower.jpg", "rb"),
+ /// },
+ /// data={
+ /// "prompt": "a flower",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./flower.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task> CreateStableImageUpscaleConservativeAsBytesAsResponseAsync( + string contentType, + global::System.IO.Stream image, + string imagename, + string prompt, + global::StabilityAI.CreateStableImageUpscaleConservativeAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + string? negativePrompt = default, + double? seed = default, + global::StabilityAI.CreateStableImageUpscaleConservativeRequestOutputFormat? outputFormat = default, + double? creativity = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + } +} \ No newline at end of file diff --git a/src/libs/StabilityAI/Generated/StabilityAI.IUpscaleClient.CreateStableImageUpscaleFastAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.IUpscaleClient.CreateStableImageUpscaleFastAsBytes.g.cs new file mode 100644 index 0000000..a34ebf7 --- /dev/null +++ b/src/libs/StabilityAI/Generated/StabilityAI.IUpscaleClient.CreateStableImageUpscaleFastAsBytes.g.cs @@ -0,0 +1,632 @@ +#nullable enable + +namespace StabilityAI +{ + public partial interface IUpscaleClient + { + /// + /// Fast
+ /// Our Fast Upscaler service enhances image resolution by 4x using predictive and generative AI. This lightweight and fast service (processing in ~1 second) is ideal for enhancing the quality of compressed images, making it suitable for social media posts and other applications.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// Optionally, the body of the request may also include:
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image is 4 times that of the input image with a maximum size of 16 megapixels.
+ /// ### Credits
+ /// Flat rate of 2 credit per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/upscale/fast",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./low-res-flower.jpg", "rb"),
+ /// },
+ /// data={
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./flower.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateStableImageUpscaleFastAsBytesAsync( + string contentType, + + global::StabilityAI.CreateStableImageUpscaleFastRequest request, + global::StabilityAI.CreateStableImageUpscaleFastAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Fast
+ /// Our Fast Upscaler service enhances image resolution by 4x using predictive and generative AI. This lightweight and fast service (processing in ~1 second) is ideal for enhancing the quality of compressed images, making it suitable for social media posts and other applications.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// Optionally, the body of the request may also include:
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image is 4 times that of the input image with a maximum size of 16 megapixels.
+ /// ### Credits
+ /// Flat rate of 2 credit per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/upscale/fast",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./low-res-flower.jpg", "rb"),
+ /// },
+ /// data={
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./flower.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateStableImageUpscaleFastAsBytesAsStreamAsync( + string contentType, + + global::StabilityAI.CreateStableImageUpscaleFastRequest request, + global::StabilityAI.CreateStableImageUpscaleFastAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Fast
+ /// Our Fast Upscaler service enhances image resolution by 4x using predictive and generative AI. This lightweight and fast service (processing in ~1 second) is ideal for enhancing the quality of compressed images, making it suitable for social media posts and other applications.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// Optionally, the body of the request may also include:
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image is 4 times that of the input image with a maximum size of 16 megapixels.
+ /// ### Credits
+ /// Flat rate of 2 credit per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/upscale/fast",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./low-res-flower.jpg", "rb"),
+ /// },
+ /// data={
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./flower.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task> CreateStableImageUpscaleFastAsBytesAsResponseAsync( + string contentType, + + global::StabilityAI.CreateStableImageUpscaleFastRequest request, + global::StabilityAI.CreateStableImageUpscaleFastAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Fast
+ /// Our Fast Upscaler service enhances image resolution by 4x using predictive and generative AI. This lightweight and fast service (processing in ~1 second) is ideal for enhancing the quality of compressed images, making it suitable for social media posts and other applications.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// Optionally, the body of the request may also include:
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image is 4 times that of the input image with a maximum size of 16 megapixels.
+ /// ### Credits
+ /// Flat rate of 2 credit per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// The image you wish to upscale.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 32 and 1,536 pixels
+ /// - Height must be between 32 and 1,536 pixels
+ /// - Total pixel count must be between 1,024 and 1,048,576 pixels
+ /// Example: ./some/image.png + /// + /// + /// The image you wish to upscale.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 32 and 1,536 pixels
+ /// - Height must be between 32 and 1,536 pixels
+ /// - Total pixel count must be between 1,024 and 1,048,576 pixels
+ /// Example: ./some/image.png + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + global::System.Threading.Tasks.Task CreateStableImageUpscaleFastAsBytesAsync( + string contentType, + byte[] image, + string imagename, + global::StabilityAI.CreateStableImageUpscaleFastAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.CreateStableImageUpscaleFastRequestOutputFormat? outputFormat = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + + /// + /// Fast
+ /// Our Fast Upscaler service enhances image resolution by 4x using predictive and generative AI. This lightweight and fast service (processing in ~1 second) is ideal for enhancing the quality of compressed images, making it suitable for social media posts and other applications.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// Optionally, the body of the request may also include:
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image is 4 times that of the input image with a maximum size of 16 megapixels.
+ /// ### Credits
+ /// Flat rate of 2 credit per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// The image you wish to upscale.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 32 and 1,536 pixels
+ /// - Height must be between 32 and 1,536 pixels
+ /// - Total pixel count must be between 1,024 and 1,048,576 pixels
+ /// Example: ./some/image.png + /// + /// + /// The image you wish to upscale.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 32 and 1,536 pixels
+ /// - Height must be between 32 and 1,536 pixels
+ /// - Total pixel count must be between 1,024 and 1,048,576 pixels
+ /// Example: ./some/image.png + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/upscale/fast",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./low-res-flower.jpg", "rb"),
+ /// },
+ /// data={
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./flower.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateStableImageUpscaleFastAsBytesAsync( + string contentType, + global::System.IO.Stream image, + string imagename, + global::StabilityAI.CreateStableImageUpscaleFastAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.CreateStableImageUpscaleFastRequestOutputFormat? outputFormat = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Fast
+ /// Our Fast Upscaler service enhances image resolution by 4x using predictive and generative AI. This lightweight and fast service (processing in ~1 second) is ideal for enhancing the quality of compressed images, making it suitable for social media posts and other applications.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// Optionally, the body of the request may also include:
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image is 4 times that of the input image with a maximum size of 16 megapixels.
+ /// ### Credits
+ /// Flat rate of 2 credit per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// The image you wish to upscale.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 32 and 1,536 pixels
+ /// - Height must be between 32 and 1,536 pixels
+ /// - Total pixel count must be between 1,024 and 1,048,576 pixels
+ /// Example: ./some/image.png + /// + /// + /// The image you wish to upscale.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 32 and 1,536 pixels
+ /// - Height must be between 32 and 1,536 pixels
+ /// - Total pixel count must be between 1,024 and 1,048,576 pixels
+ /// Example: ./some/image.png + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/upscale/fast",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./low-res-flower.jpg", "rb"),
+ /// },
+ /// data={
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./flower.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateStableImageUpscaleFastAsBytesAsStreamAsync( + string contentType, + global::System.IO.Stream image, + string imagename, + global::StabilityAI.CreateStableImageUpscaleFastAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.CreateStableImageUpscaleFastRequestOutputFormat? outputFormat = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// Fast
+ /// Our Fast Upscaler service enhances image resolution by 4x using predictive and generative AI. This lightweight and fast service (processing in ~1 second) is ideal for enhancing the quality of compressed images, making it suitable for social media posts and other applications.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// Optionally, the body of the request may also include:
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image is 4 times that of the input image with a maximum size of 16 megapixels.
+ /// ### Credits
+ /// Flat rate of 2 credit per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// The image you wish to upscale.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 32 and 1,536 pixels
+ /// - Height must be between 32 and 1,536 pixels
+ /// - Total pixel count must be between 1,024 and 1,048,576 pixels
+ /// Example: ./some/image.png + /// + /// + /// The image you wish to upscale.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 32 and 1,536 pixels
+ /// - Height must be between 32 and 1,536 pixels
+ /// - Total pixel count must be between 1,024 and 1,048,576 pixels
+ /// Example: ./some/image.png + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/upscale/fast",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./low-res-flower.jpg", "rb"),
+ /// },
+ /// data={
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./flower.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task> CreateStableImageUpscaleFastAsBytesAsResponseAsync( + string contentType, + global::System.IO.Stream image, + string imagename, + global::StabilityAI.CreateStableImageUpscaleFastAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.CreateStableImageUpscaleFastRequestOutputFormat? outputFormat = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + } +} \ No newline at end of file diff --git a/src/libs/StabilityAI/Generated/StabilityAI.IV1GenerationClient.ImageToImageAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.IV1GenerationClient.ImageToImageAsBytes.g.cs new file mode 100644 index 0000000..e98d9c7 --- /dev/null +++ b/src/libs/StabilityAI/Generated/StabilityAI.IV1GenerationClient.ImageToImageAsBytes.g.cs @@ -0,0 +1,610 @@ +#nullable enable + +namespace StabilityAI +{ + public partial interface IV1GenerationClient + { + /// + /// image-to-image
+ /// Modify an image based on a text prompt + ///
+ /// + /// Example: stable-diffusion-v1-5 + /// + /// + /// Default Value: application/json + /// + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// if [ -z "$STABILITY_API_KEY" ]; then
+ /// echo "STABILITY_API_KEY environment variable is not set"
+ /// exit 1
+ /// fi
+ /// OUTPUT_FILE=./out/v1_img2img.png
+ /// BASE_URL=${API_HOST:-https://api.stability.ai}
+ /// URL="$BASE_URL/v1/generation/stable-diffusion-v1-5/image-to-image"
+ /// curl -f -sS -X POST "$URL" \
+ /// -H 'Content-Type: multipart/form-data' \
+ /// -H 'Accept: image/png' \
+ /// -H "Authorization: Bearer $STABILITY_API_KEY" \
+ /// -F 'init_image=@"../init_image.png"' \
+ /// -F 'init_image_mode=IMAGE_STRENGTH' \
+ /// -F 'image_strength=0.35' \
+ /// -F 'text_prompts[0][text]=A galactic dog in space' \
+ /// -F 'cfg_scale=7' \
+ /// -F 'clip_guidance_preset=FAST_BLUE' \
+ /// -F 'samples=1' \
+ /// -F 'steps=30' \
+ /// -o "$OUTPUT_FILE" + ///
+ global::System.Threading.Tasks.Task ImageToImageAsBytesAsync( + string engineId, + + global::StabilityAI.ImageToImageRequestBody request, + global::StabilityAI.ImageToImageAccept? accept = default, + string? organization = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// image-to-image
+ /// Modify an image based on a text prompt + ///
+ /// + /// Example: stable-diffusion-v1-5 + /// + /// + /// Default Value: application/json + /// + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// if [ -z "$STABILITY_API_KEY" ]; then
+ /// echo "STABILITY_API_KEY environment variable is not set"
+ /// exit 1
+ /// fi
+ /// OUTPUT_FILE=./out/v1_img2img.png
+ /// BASE_URL=${API_HOST:-https://api.stability.ai}
+ /// URL="$BASE_URL/v1/generation/stable-diffusion-v1-5/image-to-image"
+ /// curl -f -sS -X POST "$URL" \
+ /// -H 'Content-Type: multipart/form-data' \
+ /// -H 'Accept: image/png' \
+ /// -H "Authorization: Bearer $STABILITY_API_KEY" \
+ /// -F 'init_image=@"../init_image.png"' \
+ /// -F 'init_image_mode=IMAGE_STRENGTH' \
+ /// -F 'image_strength=0.35' \
+ /// -F 'text_prompts[0][text]=A galactic dog in space' \
+ /// -F 'cfg_scale=7' \
+ /// -F 'clip_guidance_preset=FAST_BLUE' \
+ /// -F 'samples=1' \
+ /// -F 'steps=30' \
+ /// -o "$OUTPUT_FILE" + ///
+ global::System.Threading.Tasks.Task ImageToImageAsBytesAsStreamAsync( + string engineId, + + global::StabilityAI.ImageToImageRequestBody request, + global::StabilityAI.ImageToImageAccept? accept = default, + string? organization = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// image-to-image
+ /// Modify an image based on a text prompt + ///
+ /// + /// Example: stable-diffusion-v1-5 + /// + /// + /// Default Value: application/json + /// + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// if [ -z "$STABILITY_API_KEY" ]; then
+ /// echo "STABILITY_API_KEY environment variable is not set"
+ /// exit 1
+ /// fi
+ /// OUTPUT_FILE=./out/v1_img2img.png
+ /// BASE_URL=${API_HOST:-https://api.stability.ai}
+ /// URL="$BASE_URL/v1/generation/stable-diffusion-v1-5/image-to-image"
+ /// curl -f -sS -X POST "$URL" \
+ /// -H 'Content-Type: multipart/form-data' \
+ /// -H 'Accept: image/png' \
+ /// -H "Authorization: Bearer $STABILITY_API_KEY" \
+ /// -F 'init_image=@"../init_image.png"' \
+ /// -F 'init_image_mode=IMAGE_STRENGTH' \
+ /// -F 'image_strength=0.35' \
+ /// -F 'text_prompts[0][text]=A galactic dog in space' \
+ /// -F 'cfg_scale=7' \
+ /// -F 'clip_guidance_preset=FAST_BLUE' \
+ /// -F 'samples=1' \
+ /// -F 'steps=30' \
+ /// -o "$OUTPUT_FILE" + ///
+ global::System.Threading.Tasks.Task> ImageToImageAsBytesAsResponseAsync( + string engineId, + + global::StabilityAI.ImageToImageRequestBody request, + global::StabilityAI.ImageToImageAccept? accept = default, + string? organization = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// image-to-image
+ /// Modify an image based on a text prompt + ///
+ /// + /// Example: stable-diffusion-v1-5 + /// + /// + /// Default Value: application/json + /// + /// + /// + /// An array of text prompts to use for generation.
+ /// Due to how arrays are represented in `multipart/form-data` requests, prompts must adhear to the format `text_prompts[index][text|weight]`,
+ /// where `index` is some integer used to tie the text and weight together. While `index` does not have to be sequential, duplicate entries
+ /// will override previous entries, so it is recommended to use sequential indices.
+ /// Given a text prompt with the text `A lighthouse on a cliff` and a weight of `0.5`, it would be represented as:
+ /// ```
+ /// text_prompts[0][text]: "A lighthouse on a cliff"
+ /// text_prompts[0][weight]: 0.5
+ /// ```
+ /// To add another prompt to that request simply provide the values under a new `index`:
+ /// ```
+ /// text_prompts[0][text]: "A lighthouse on a cliff"
+ /// text_prompts[0][weight]: 0.5
+ /// text_prompts[1][text]: "land, ground, dirt, grass"
+ /// text_prompts[1][weight]: -0.9
+ /// ``` + /// + /// + /// Image used to initialize the diffusion process, in lieu of random noise.
+ /// Example: <image binary> + /// + /// + /// Image used to initialize the diffusion process, in lieu of random noise.
+ /// Example: <image binary> + /// + /// + /// How much influence the `init_image` has on the diffusion process. Values close to `1` will yield images very similar to the `init_image` while values close to `0` will yield images wildly different than the `init_image`. The behavior of this is meant to mirror DreamStudio's "Image Strength" slider. <br/> <br/> This parameter is just an alternate way to set `step_schedule_start`, which is done via the calculation `1 - image_strength`. For example, passing in an Image Strength of 35% (`0.35`) would result in a `step_schedule_start` of `0.65`.
+ /// Default Value: 0.35F
+ /// Example: 0.4F + /// + /// + /// Skips a proportion of the start of the diffusion steps, allowing the init_image to influence the final generated image. Lower values will result in more influence from the init_image, while higher values will result in more influence from the diffusion steps. (e.g. a value of `0` would simply return you the init_image, where a value of `1` would return you a completely different image.)
+ /// Default Value: 0.65F
+ /// Example: 0.4F + /// + /// + /// Skips a proportion of the end of the diffusion steps, allowing the init_image to influence the final generated image. Lower values will result in more influence from the init_image, while higher values will result in more influence from the diffusion steps.
+ /// Example: 0.01F + /// + /// + /// How strictly the diffusion process adheres to the prompt text (higher values keep your image closer to your prompt)
+ /// Default Value: 7
+ /// Example: 7 + /// + /// + /// Default Value: NONE
+ /// Example: FAST_BLUE + /// + /// + /// Which sampler to use for the diffusion process. If this value is omitted we'll automatically select an appropriate sampler for you.
+ /// Example: K_DPM_2_ANCESTRAL + /// + /// + /// Number of images to generate
+ /// Default Value: 1
+ /// Example: 1 + /// + /// + /// Random noise seed (omit this option or use `0` for a random seed)
+ /// Default Value: 0
+ /// Example: 0 + /// + /// + /// Number of diffusion steps to run
+ /// Default Value: 50
+ /// Example: 75 + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + global::System.Threading.Tasks.Task ImageToImageAsBytesAsync( + string engineId, + global::System.Collections.Generic.IList textPrompts, + byte[] initImage, + string initImagename, + global::StabilityAI.ImageToImageAccept? accept = default, + string? organization = default, + float? imageStrength = default, + double? stepScheduleStart = default, + double? stepScheduleEnd = default, + double? cfgScale = default, + global::StabilityAI.ClipGuidancePreset? clipGuidancePreset = default, + global::StabilityAI.Sampler? sampler = default, + int? samples = default, + long? seed = default, + int? steps = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + + /// + /// image-to-image
+ /// Modify an image based on a text prompt + ///
+ /// + /// Example: stable-diffusion-v1-5 + /// + /// + /// Default Value: application/json + /// + /// + /// + /// An array of text prompts to use for generation.
+ /// Due to how arrays are represented in `multipart/form-data` requests, prompts must adhear to the format `text_prompts[index][text|weight]`,
+ /// where `index` is some integer used to tie the text and weight together. While `index` does not have to be sequential, duplicate entries
+ /// will override previous entries, so it is recommended to use sequential indices.
+ /// Given a text prompt with the text `A lighthouse on a cliff` and a weight of `0.5`, it would be represented as:
+ /// ```
+ /// text_prompts[0][text]: "A lighthouse on a cliff"
+ /// text_prompts[0][weight]: 0.5
+ /// ```
+ /// To add another prompt to that request simply provide the values under a new `index`:
+ /// ```
+ /// text_prompts[0][text]: "A lighthouse on a cliff"
+ /// text_prompts[0][weight]: 0.5
+ /// text_prompts[1][text]: "land, ground, dirt, grass"
+ /// text_prompts[1][weight]: -0.9
+ /// ``` + /// + /// + /// Image used to initialize the diffusion process, in lieu of random noise.
+ /// Example: <image binary> + /// + /// + /// Image used to initialize the diffusion process, in lieu of random noise.
+ /// Example: <image binary> + /// + /// + /// How much influence the `init_image` has on the diffusion process. Values close to `1` will yield images very similar to the `init_image` while values close to `0` will yield images wildly different than the `init_image`. The behavior of this is meant to mirror DreamStudio's "Image Strength" slider. <br/> <br/> This parameter is just an alternate way to set `step_schedule_start`, which is done via the calculation `1 - image_strength`. For example, passing in an Image Strength of 35% (`0.35`) would result in a `step_schedule_start` of `0.65`.
+ /// Default Value: 0.35F
+ /// Example: 0.4F + /// + /// + /// Skips a proportion of the start of the diffusion steps, allowing the init_image to influence the final generated image. Lower values will result in more influence from the init_image, while higher values will result in more influence from the diffusion steps. (e.g. a value of `0` would simply return you the init_image, where a value of `1` would return you a completely different image.)
+ /// Default Value: 0.65F
+ /// Example: 0.4F + /// + /// + /// Skips a proportion of the end of the diffusion steps, allowing the init_image to influence the final generated image. Lower values will result in more influence from the init_image, while higher values will result in more influence from the diffusion steps.
+ /// Example: 0.01F + /// + /// + /// How strictly the diffusion process adheres to the prompt text (higher values keep your image closer to your prompt)
+ /// Default Value: 7
+ /// Example: 7 + /// + /// + /// Default Value: NONE
+ /// Example: FAST_BLUE + /// + /// + /// Which sampler to use for the diffusion process. If this value is omitted we'll automatically select an appropriate sampler for you.
+ /// Example: K_DPM_2_ANCESTRAL + /// + /// + /// Number of images to generate
+ /// Default Value: 1
+ /// Example: 1 + /// + /// + /// Random noise seed (omit this option or use `0` for a random seed)
+ /// Default Value: 0
+ /// Example: 0 + /// + /// + /// Number of diffusion steps to run
+ /// Default Value: 50
+ /// Example: 75 + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// if [ -z "$STABILITY_API_KEY" ]; then
+ /// echo "STABILITY_API_KEY environment variable is not set"
+ /// exit 1
+ /// fi
+ /// OUTPUT_FILE=./out/v1_img2img.png
+ /// BASE_URL=${API_HOST:-https://api.stability.ai}
+ /// URL="$BASE_URL/v1/generation/stable-diffusion-v1-5/image-to-image"
+ /// curl -f -sS -X POST "$URL" \
+ /// -H 'Content-Type: multipart/form-data' \
+ /// -H 'Accept: image/png' \
+ /// -H "Authorization: Bearer $STABILITY_API_KEY" \
+ /// -F 'init_image=@"../init_image.png"' \
+ /// -F 'init_image_mode=IMAGE_STRENGTH' \
+ /// -F 'image_strength=0.35' \
+ /// -F 'text_prompts[0][text]=A galactic dog in space' \
+ /// -F 'cfg_scale=7' \
+ /// -F 'clip_guidance_preset=FAST_BLUE' \
+ /// -F 'samples=1' \
+ /// -F 'steps=30' \
+ /// -o "$OUTPUT_FILE" + ///
+ global::System.Threading.Tasks.Task ImageToImageAsBytesAsync( + string engineId, + global::System.Collections.Generic.IList textPrompts, + global::System.IO.Stream initImage, + string initImagename, + global::StabilityAI.ImageToImageAccept? accept = default, + string? organization = default, + float? imageStrength = default, + double? stepScheduleStart = default, + double? stepScheduleEnd = default, + double? cfgScale = default, + global::StabilityAI.ClipGuidancePreset? clipGuidancePreset = default, + global::StabilityAI.Sampler? sampler = default, + int? samples = default, + long? seed = default, + int? steps = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// image-to-image
+ /// Modify an image based on a text prompt + ///
+ /// + /// Example: stable-diffusion-v1-5 + /// + /// + /// Default Value: application/json + /// + /// + /// + /// An array of text prompts to use for generation.
+ /// Due to how arrays are represented in `multipart/form-data` requests, prompts must adhear to the format `text_prompts[index][text|weight]`,
+ /// where `index` is some integer used to tie the text and weight together. While `index` does not have to be sequential, duplicate entries
+ /// will override previous entries, so it is recommended to use sequential indices.
+ /// Given a text prompt with the text `A lighthouse on a cliff` and a weight of `0.5`, it would be represented as:
+ /// ```
+ /// text_prompts[0][text]: "A lighthouse on a cliff"
+ /// text_prompts[0][weight]: 0.5
+ /// ```
+ /// To add another prompt to that request simply provide the values under a new `index`:
+ /// ```
+ /// text_prompts[0][text]: "A lighthouse on a cliff"
+ /// text_prompts[0][weight]: 0.5
+ /// text_prompts[1][text]: "land, ground, dirt, grass"
+ /// text_prompts[1][weight]: -0.9
+ /// ``` + /// + /// + /// Image used to initialize the diffusion process, in lieu of random noise.
+ /// Example: <image binary> + /// + /// + /// Image used to initialize the diffusion process, in lieu of random noise.
+ /// Example: <image binary> + /// + /// + /// How much influence the `init_image` has on the diffusion process. Values close to `1` will yield images very similar to the `init_image` while values close to `0` will yield images wildly different than the `init_image`. The behavior of this is meant to mirror DreamStudio's "Image Strength" slider. <br/> <br/> This parameter is just an alternate way to set `step_schedule_start`, which is done via the calculation `1 - image_strength`. For example, passing in an Image Strength of 35% (`0.35`) would result in a `step_schedule_start` of `0.65`.
+ /// Default Value: 0.35F
+ /// Example: 0.4F + /// + /// + /// Skips a proportion of the start of the diffusion steps, allowing the init_image to influence the final generated image. Lower values will result in more influence from the init_image, while higher values will result in more influence from the diffusion steps. (e.g. a value of `0` would simply return you the init_image, where a value of `1` would return you a completely different image.)
+ /// Default Value: 0.65F
+ /// Example: 0.4F + /// + /// + /// Skips a proportion of the end of the diffusion steps, allowing the init_image to influence the final generated image. Lower values will result in more influence from the init_image, while higher values will result in more influence from the diffusion steps.
+ /// Example: 0.01F + /// + /// + /// How strictly the diffusion process adheres to the prompt text (higher values keep your image closer to your prompt)
+ /// Default Value: 7
+ /// Example: 7 + /// + /// + /// Default Value: NONE
+ /// Example: FAST_BLUE + /// + /// + /// Which sampler to use for the diffusion process. If this value is omitted we'll automatically select an appropriate sampler for you.
+ /// Example: K_DPM_2_ANCESTRAL + /// + /// + /// Number of images to generate
+ /// Default Value: 1
+ /// Example: 1 + /// + /// + /// Random noise seed (omit this option or use `0` for a random seed)
+ /// Default Value: 0
+ /// Example: 0 + /// + /// + /// Number of diffusion steps to run
+ /// Default Value: 50
+ /// Example: 75 + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// if [ -z "$STABILITY_API_KEY" ]; then
+ /// echo "STABILITY_API_KEY environment variable is not set"
+ /// exit 1
+ /// fi
+ /// OUTPUT_FILE=./out/v1_img2img.png
+ /// BASE_URL=${API_HOST:-https://api.stability.ai}
+ /// URL="$BASE_URL/v1/generation/stable-diffusion-v1-5/image-to-image"
+ /// curl -f -sS -X POST "$URL" \
+ /// -H 'Content-Type: multipart/form-data' \
+ /// -H 'Accept: image/png' \
+ /// -H "Authorization: Bearer $STABILITY_API_KEY" \
+ /// -F 'init_image=@"../init_image.png"' \
+ /// -F 'init_image_mode=IMAGE_STRENGTH' \
+ /// -F 'image_strength=0.35' \
+ /// -F 'text_prompts[0][text]=A galactic dog in space' \
+ /// -F 'cfg_scale=7' \
+ /// -F 'clip_guidance_preset=FAST_BLUE' \
+ /// -F 'samples=1' \
+ /// -F 'steps=30' \
+ /// -o "$OUTPUT_FILE" + ///
+ global::System.Threading.Tasks.Task ImageToImageAsBytesAsStreamAsync( + string engineId, + global::System.Collections.Generic.IList textPrompts, + global::System.IO.Stream initImage, + string initImagename, + global::StabilityAI.ImageToImageAccept? accept = default, + string? organization = default, + float? imageStrength = default, + double? stepScheduleStart = default, + double? stepScheduleEnd = default, + double? cfgScale = default, + global::StabilityAI.ClipGuidancePreset? clipGuidancePreset = default, + global::StabilityAI.Sampler? sampler = default, + int? samples = default, + long? seed = default, + int? steps = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// image-to-image
+ /// Modify an image based on a text prompt + ///
+ /// + /// Example: stable-diffusion-v1-5 + /// + /// + /// Default Value: application/json + /// + /// + /// + /// An array of text prompts to use for generation.
+ /// Due to how arrays are represented in `multipart/form-data` requests, prompts must adhear to the format `text_prompts[index][text|weight]`,
+ /// where `index` is some integer used to tie the text and weight together. While `index` does not have to be sequential, duplicate entries
+ /// will override previous entries, so it is recommended to use sequential indices.
+ /// Given a text prompt with the text `A lighthouse on a cliff` and a weight of `0.5`, it would be represented as:
+ /// ```
+ /// text_prompts[0][text]: "A lighthouse on a cliff"
+ /// text_prompts[0][weight]: 0.5
+ /// ```
+ /// To add another prompt to that request simply provide the values under a new `index`:
+ /// ```
+ /// text_prompts[0][text]: "A lighthouse on a cliff"
+ /// text_prompts[0][weight]: 0.5
+ /// text_prompts[1][text]: "land, ground, dirt, grass"
+ /// text_prompts[1][weight]: -0.9
+ /// ``` + /// + /// + /// Image used to initialize the diffusion process, in lieu of random noise.
+ /// Example: <image binary> + /// + /// + /// Image used to initialize the diffusion process, in lieu of random noise.
+ /// Example: <image binary> + /// + /// + /// How much influence the `init_image` has on the diffusion process. Values close to `1` will yield images very similar to the `init_image` while values close to `0` will yield images wildly different than the `init_image`. The behavior of this is meant to mirror DreamStudio's "Image Strength" slider. <br/> <br/> This parameter is just an alternate way to set `step_schedule_start`, which is done via the calculation `1 - image_strength`. For example, passing in an Image Strength of 35% (`0.35`) would result in a `step_schedule_start` of `0.65`.
+ /// Default Value: 0.35F
+ /// Example: 0.4F + /// + /// + /// Skips a proportion of the start of the diffusion steps, allowing the init_image to influence the final generated image. Lower values will result in more influence from the init_image, while higher values will result in more influence from the diffusion steps. (e.g. a value of `0` would simply return you the init_image, where a value of `1` would return you a completely different image.)
+ /// Default Value: 0.65F
+ /// Example: 0.4F + /// + /// + /// Skips a proportion of the end of the diffusion steps, allowing the init_image to influence the final generated image. Lower values will result in more influence from the init_image, while higher values will result in more influence from the diffusion steps.
+ /// Example: 0.01F + /// + /// + /// How strictly the diffusion process adheres to the prompt text (higher values keep your image closer to your prompt)
+ /// Default Value: 7
+ /// Example: 7 + /// + /// + /// Default Value: NONE
+ /// Example: FAST_BLUE + /// + /// + /// Which sampler to use for the diffusion process. If this value is omitted we'll automatically select an appropriate sampler for you.
+ /// Example: K_DPM_2_ANCESTRAL + /// + /// + /// Number of images to generate
+ /// Default Value: 1
+ /// Example: 1 + /// + /// + /// Random noise seed (omit this option or use `0` for a random seed)
+ /// Default Value: 0
+ /// Example: 0 + /// + /// + /// Number of diffusion steps to run
+ /// Default Value: 50
+ /// Example: 75 + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// if [ -z "$STABILITY_API_KEY" ]; then
+ /// echo "STABILITY_API_KEY environment variable is not set"
+ /// exit 1
+ /// fi
+ /// OUTPUT_FILE=./out/v1_img2img.png
+ /// BASE_URL=${API_HOST:-https://api.stability.ai}
+ /// URL="$BASE_URL/v1/generation/stable-diffusion-v1-5/image-to-image"
+ /// curl -f -sS -X POST "$URL" \
+ /// -H 'Content-Type: multipart/form-data' \
+ /// -H 'Accept: image/png' \
+ /// -H "Authorization: Bearer $STABILITY_API_KEY" \
+ /// -F 'init_image=@"../init_image.png"' \
+ /// -F 'init_image_mode=IMAGE_STRENGTH' \
+ /// -F 'image_strength=0.35' \
+ /// -F 'text_prompts[0][text]=A galactic dog in space' \
+ /// -F 'cfg_scale=7' \
+ /// -F 'clip_guidance_preset=FAST_BLUE' \
+ /// -F 'samples=1' \
+ /// -F 'steps=30' \
+ /// -o "$OUTPUT_FILE" + ///
+ global::System.Threading.Tasks.Task> ImageToImageAsBytesAsResponseAsync( + string engineId, + global::System.Collections.Generic.IList textPrompts, + global::System.IO.Stream initImage, + string initImagename, + global::StabilityAI.ImageToImageAccept? accept = default, + string? organization = default, + float? imageStrength = default, + double? stepScheduleStart = default, + double? stepScheduleEnd = default, + double? cfgScale = default, + global::StabilityAI.ClipGuidancePreset? clipGuidancePreset = default, + global::StabilityAI.Sampler? sampler = default, + int? samples = default, + long? seed = default, + int? steps = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + } +} \ No newline at end of file diff --git a/src/libs/StabilityAI/Generated/StabilityAI.IV1GenerationClient.MaskingAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.IV1GenerationClient.MaskingAsBytes.g.cs new file mode 100644 index 0000000..3aa523e --- /dev/null +++ b/src/libs/StabilityAI/Generated/StabilityAI.IV1GenerationClient.MaskingAsBytes.g.cs @@ -0,0 +1,580 @@ +#nullable enable + +namespace StabilityAI +{ + public partial interface IV1GenerationClient + { + /// + /// image-to-image/masking
+ /// Selectively modify portions of an image using a mask + ///
+ /// + /// + /// Default Value: application/json + /// + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// #!/bin/sh
+ /// set -e
+ /// if [ -z "$STABILITY_API_KEY" ]; then
+ /// echo "STABILITY_API_KEY environment variable is not set"
+ /// exit 1
+ /// fi
+ /// OUTPUT_FILE=./out/v1_img2img_masking.png
+ /// BASE_URL=${API_HOST:-https://api.stability.ai}
+ /// URL="$BASE_URL/v1/generation/stable-inpainting-512-v2-0/image-to-image/masking"
+ /// curl -f -sS -X POST "$URL" \
+ /// -H 'Content-Type: multipart/form-data' \
+ /// -H 'Accept: image/png' \
+ /// -H "Authorization: Bearer $STABILITY_API_KEY" \
+ /// -F 'init_image=@"../init_image.png"' \
+ /// -F 'mask_image=@"../mask_image_white.png"' \
+ /// -F 'mask_source=MASK_IMAGE_WHITE' \
+ /// -F 'text_prompts[0][text]=A large spiral galaxy with a bright central bulge and a ring of stars around it' \
+ /// -F 'cfg_scale=7' \
+ /// -F 'clip_guidance_preset=FAST_BLUE' \
+ /// -F 'samples=1' \
+ /// -F 'steps=30' \
+ /// -o "$OUTPUT_FILE" + ///
+ global::System.Threading.Tasks.Task MaskingAsBytesAsync( + string engineId, + + global::StabilityAI.MaskingRequestBody request, + global::StabilityAI.MaskingAccept? accept = default, + string? organization = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// image-to-image/masking
+ /// Selectively modify portions of an image using a mask + ///
+ /// + /// + /// Default Value: application/json + /// + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// #!/bin/sh
+ /// set -e
+ /// if [ -z "$STABILITY_API_KEY" ]; then
+ /// echo "STABILITY_API_KEY environment variable is not set"
+ /// exit 1
+ /// fi
+ /// OUTPUT_FILE=./out/v1_img2img_masking.png
+ /// BASE_URL=${API_HOST:-https://api.stability.ai}
+ /// URL="$BASE_URL/v1/generation/stable-inpainting-512-v2-0/image-to-image/masking"
+ /// curl -f -sS -X POST "$URL" \
+ /// -H 'Content-Type: multipart/form-data' \
+ /// -H 'Accept: image/png' \
+ /// -H "Authorization: Bearer $STABILITY_API_KEY" \
+ /// -F 'init_image=@"../init_image.png"' \
+ /// -F 'mask_image=@"../mask_image_white.png"' \
+ /// -F 'mask_source=MASK_IMAGE_WHITE' \
+ /// -F 'text_prompts[0][text]=A large spiral galaxy with a bright central bulge and a ring of stars around it' \
+ /// -F 'cfg_scale=7' \
+ /// -F 'clip_guidance_preset=FAST_BLUE' \
+ /// -F 'samples=1' \
+ /// -F 'steps=30' \
+ /// -o "$OUTPUT_FILE" + ///
+ global::System.Threading.Tasks.Task MaskingAsBytesAsStreamAsync( + string engineId, + + global::StabilityAI.MaskingRequestBody request, + global::StabilityAI.MaskingAccept? accept = default, + string? organization = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// image-to-image/masking
+ /// Selectively modify portions of an image using a mask + ///
+ /// + /// + /// Default Value: application/json + /// + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// #!/bin/sh
+ /// set -e
+ /// if [ -z "$STABILITY_API_KEY" ]; then
+ /// echo "STABILITY_API_KEY environment variable is not set"
+ /// exit 1
+ /// fi
+ /// OUTPUT_FILE=./out/v1_img2img_masking.png
+ /// BASE_URL=${API_HOST:-https://api.stability.ai}
+ /// URL="$BASE_URL/v1/generation/stable-inpainting-512-v2-0/image-to-image/masking"
+ /// curl -f -sS -X POST "$URL" \
+ /// -H 'Content-Type: multipart/form-data' \
+ /// -H 'Accept: image/png' \
+ /// -H "Authorization: Bearer $STABILITY_API_KEY" \
+ /// -F 'init_image=@"../init_image.png"' \
+ /// -F 'mask_image=@"../mask_image_white.png"' \
+ /// -F 'mask_source=MASK_IMAGE_WHITE' \
+ /// -F 'text_prompts[0][text]=A large spiral galaxy with a bright central bulge and a ring of stars around it' \
+ /// -F 'cfg_scale=7' \
+ /// -F 'clip_guidance_preset=FAST_BLUE' \
+ /// -F 'samples=1' \
+ /// -F 'steps=30' \
+ /// -o "$OUTPUT_FILE" + ///
+ global::System.Threading.Tasks.Task> MaskingAsBytesAsResponseAsync( + string engineId, + + global::StabilityAI.MaskingRequestBody request, + global::StabilityAI.MaskingAccept? accept = default, + string? organization = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// image-to-image/masking
+ /// Selectively modify portions of an image using a mask + ///
+ /// + /// + /// Default Value: application/json + /// + /// + /// + /// Image used to initialize the diffusion process, in lieu of random noise.
+ /// Example: <image binary> + /// + /// + /// Image used to initialize the diffusion process, in lieu of random noise.
+ /// Example: <image binary> + /// + /// + /// Optional grayscale mask that allows for influence over which pixels are eligible for diffusion and at what strength. Must be the same dimensions as the `init_image`. Use the `mask_source` option to specify whether the white or black pixels should be inpainted.
+ /// Example: <image binary> + /// + /// + /// Optional grayscale mask that allows for influence over which pixels are eligible for diffusion and at what strength. Must be the same dimensions as the `init_image`. Use the `mask_source` option to specify whether the white or black pixels should be inpainted.
+ /// Example: <image binary> + /// + /// + /// An array of text prompts to use for generation.
+ /// Due to how arrays are represented in `multipart/form-data` requests, prompts must adhear to the format `text_prompts[index][text|weight]`,
+ /// where `index` is some integer used to tie the text and weight together. While `index` does not have to be sequential, duplicate entries
+ /// will override previous entries, so it is recommended to use sequential indices.
+ /// Given a text prompt with the text `A lighthouse on a cliff` and a weight of `0.5`, it would be represented as:
+ /// ```
+ /// text_prompts[0][text]: "A lighthouse on a cliff"
+ /// text_prompts[0][weight]: 0.5
+ /// ```
+ /// To add another prompt to that request simply provide the values under a new `index`:
+ /// ```
+ /// text_prompts[0][text]: "A lighthouse on a cliff"
+ /// text_prompts[0][weight]: 0.5
+ /// text_prompts[1][text]: "land, ground, dirt, grass"
+ /// text_prompts[1][weight]: -0.9
+ /// ``` + /// + /// + /// How strictly the diffusion process adheres to the prompt text (higher values keep your image closer to your prompt)
+ /// Default Value: 7
+ /// Example: 7 + /// + /// + /// Default Value: NONE
+ /// Example: FAST_BLUE + /// + /// + /// Which sampler to use for the diffusion process. If this value is omitted we'll automatically select an appropriate sampler for you.
+ /// Example: K_DPM_2_ANCESTRAL + /// + /// + /// Number of images to generate
+ /// Default Value: 1
+ /// Example: 1 + /// + /// + /// Random noise seed (omit this option or use `0` for a random seed)
+ /// Default Value: 0
+ /// Example: 0 + /// + /// + /// Number of diffusion steps to run
+ /// Default Value: 50
+ /// Example: 75 + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + global::System.Threading.Tasks.Task MaskingAsBytesAsync( + string engineId, + byte[] initImage, + string initImagename, + global::System.Collections.Generic.IList textPrompts, + global::StabilityAI.MaskingAccept? accept = default, + string? organization = default, + byte[]? maskImage = default, + string? maskImagename = default, + double? cfgScale = default, + global::StabilityAI.ClipGuidancePreset? clipGuidancePreset = default, + global::StabilityAI.Sampler? sampler = default, + int? samples = default, + long? seed = default, + int? steps = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + + /// + /// image-to-image/masking
+ /// Selectively modify portions of an image using a mask + ///
+ /// + /// + /// Default Value: application/json + /// + /// + /// + /// Image used to initialize the diffusion process, in lieu of random noise.
+ /// Example: <image binary> + /// + /// + /// Image used to initialize the diffusion process, in lieu of random noise.
+ /// Example: <image binary> + /// + /// + /// Optional grayscale mask that allows for influence over which pixels are eligible for diffusion and at what strength. Must be the same dimensions as the `init_image`. Use the `mask_source` option to specify whether the white or black pixels should be inpainted.
+ /// Example: <image binary> + /// + /// + /// Optional grayscale mask that allows for influence over which pixels are eligible for diffusion and at what strength. Must be the same dimensions as the `init_image`. Use the `mask_source` option to specify whether the white or black pixels should be inpainted.
+ /// Example: <image binary> + /// + /// + /// An array of text prompts to use for generation.
+ /// Due to how arrays are represented in `multipart/form-data` requests, prompts must adhear to the format `text_prompts[index][text|weight]`,
+ /// where `index` is some integer used to tie the text and weight together. While `index` does not have to be sequential, duplicate entries
+ /// will override previous entries, so it is recommended to use sequential indices.
+ /// Given a text prompt with the text `A lighthouse on a cliff` and a weight of `0.5`, it would be represented as:
+ /// ```
+ /// text_prompts[0][text]: "A lighthouse on a cliff"
+ /// text_prompts[0][weight]: 0.5
+ /// ```
+ /// To add another prompt to that request simply provide the values under a new `index`:
+ /// ```
+ /// text_prompts[0][text]: "A lighthouse on a cliff"
+ /// text_prompts[0][weight]: 0.5
+ /// text_prompts[1][text]: "land, ground, dirt, grass"
+ /// text_prompts[1][weight]: -0.9
+ /// ``` + /// + /// + /// How strictly the diffusion process adheres to the prompt text (higher values keep your image closer to your prompt)
+ /// Default Value: 7
+ /// Example: 7 + /// + /// + /// Default Value: NONE
+ /// Example: FAST_BLUE + /// + /// + /// Which sampler to use for the diffusion process. If this value is omitted we'll automatically select an appropriate sampler for you.
+ /// Example: K_DPM_2_ANCESTRAL + /// + /// + /// Number of images to generate
+ /// Default Value: 1
+ /// Example: 1 + /// + /// + /// Random noise seed (omit this option or use `0` for a random seed)
+ /// Default Value: 0
+ /// Example: 0 + /// + /// + /// Number of diffusion steps to run
+ /// Default Value: 50
+ /// Example: 75 + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// #!/bin/sh
+ /// set -e
+ /// if [ -z "$STABILITY_API_KEY" ]; then
+ /// echo "STABILITY_API_KEY environment variable is not set"
+ /// exit 1
+ /// fi
+ /// OUTPUT_FILE=./out/v1_img2img_masking.png
+ /// BASE_URL=${API_HOST:-https://api.stability.ai}
+ /// URL="$BASE_URL/v1/generation/stable-inpainting-512-v2-0/image-to-image/masking"
+ /// curl -f -sS -X POST "$URL" \
+ /// -H 'Content-Type: multipart/form-data' \
+ /// -H 'Accept: image/png' \
+ /// -H "Authorization: Bearer $STABILITY_API_KEY" \
+ /// -F 'init_image=@"../init_image.png"' \
+ /// -F 'mask_image=@"../mask_image_white.png"' \
+ /// -F 'mask_source=MASK_IMAGE_WHITE' \
+ /// -F 'text_prompts[0][text]=A large spiral galaxy with a bright central bulge and a ring of stars around it' \
+ /// -F 'cfg_scale=7' \
+ /// -F 'clip_guidance_preset=FAST_BLUE' \
+ /// -F 'samples=1' \
+ /// -F 'steps=30' \
+ /// -o "$OUTPUT_FILE" + ///
+ global::System.Threading.Tasks.Task MaskingAsBytesAsync( + string engineId, + global::System.IO.Stream initImage, + string initImagename, + global::System.Collections.Generic.IList textPrompts, + global::StabilityAI.MaskingAccept? accept = default, + string? organization = default, + global::System.IO.Stream? maskImage = default, + string? maskImagename = default, + double? cfgScale = default, + global::StabilityAI.ClipGuidancePreset? clipGuidancePreset = default, + global::StabilityAI.Sampler? sampler = default, + int? samples = default, + long? seed = default, + int? steps = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// image-to-image/masking
+ /// Selectively modify portions of an image using a mask + ///
+ /// + /// + /// Default Value: application/json + /// + /// + /// + /// Image used to initialize the diffusion process, in lieu of random noise.
+ /// Example: <image binary> + /// + /// + /// Image used to initialize the diffusion process, in lieu of random noise.
+ /// Example: <image binary> + /// + /// + /// Optional grayscale mask that allows for influence over which pixels are eligible for diffusion and at what strength. Must be the same dimensions as the `init_image`. Use the `mask_source` option to specify whether the white or black pixels should be inpainted.
+ /// Example: <image binary> + /// + /// + /// Optional grayscale mask that allows for influence over which pixels are eligible for diffusion and at what strength. Must be the same dimensions as the `init_image`. Use the `mask_source` option to specify whether the white or black pixels should be inpainted.
+ /// Example: <image binary> + /// + /// + /// An array of text prompts to use for generation.
+ /// Due to how arrays are represented in `multipart/form-data` requests, prompts must adhear to the format `text_prompts[index][text|weight]`,
+ /// where `index` is some integer used to tie the text and weight together. While `index` does not have to be sequential, duplicate entries
+ /// will override previous entries, so it is recommended to use sequential indices.
+ /// Given a text prompt with the text `A lighthouse on a cliff` and a weight of `0.5`, it would be represented as:
+ /// ```
+ /// text_prompts[0][text]: "A lighthouse on a cliff"
+ /// text_prompts[0][weight]: 0.5
+ /// ```
+ /// To add another prompt to that request simply provide the values under a new `index`:
+ /// ```
+ /// text_prompts[0][text]: "A lighthouse on a cliff"
+ /// text_prompts[0][weight]: 0.5
+ /// text_prompts[1][text]: "land, ground, dirt, grass"
+ /// text_prompts[1][weight]: -0.9
+ /// ``` + /// + /// + /// How strictly the diffusion process adheres to the prompt text (higher values keep your image closer to your prompt)
+ /// Default Value: 7
+ /// Example: 7 + /// + /// + /// Default Value: NONE
+ /// Example: FAST_BLUE + /// + /// + /// Which sampler to use for the diffusion process. If this value is omitted we'll automatically select an appropriate sampler for you.
+ /// Example: K_DPM_2_ANCESTRAL + /// + /// + /// Number of images to generate
+ /// Default Value: 1
+ /// Example: 1 + /// + /// + /// Random noise seed (omit this option or use `0` for a random seed)
+ /// Default Value: 0
+ /// Example: 0 + /// + /// + /// Number of diffusion steps to run
+ /// Default Value: 50
+ /// Example: 75 + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// #!/bin/sh
+ /// set -e
+ /// if [ -z "$STABILITY_API_KEY" ]; then
+ /// echo "STABILITY_API_KEY environment variable is not set"
+ /// exit 1
+ /// fi
+ /// OUTPUT_FILE=./out/v1_img2img_masking.png
+ /// BASE_URL=${API_HOST:-https://api.stability.ai}
+ /// URL="$BASE_URL/v1/generation/stable-inpainting-512-v2-0/image-to-image/masking"
+ /// curl -f -sS -X POST "$URL" \
+ /// -H 'Content-Type: multipart/form-data' \
+ /// -H 'Accept: image/png' \
+ /// -H "Authorization: Bearer $STABILITY_API_KEY" \
+ /// -F 'init_image=@"../init_image.png"' \
+ /// -F 'mask_image=@"../mask_image_white.png"' \
+ /// -F 'mask_source=MASK_IMAGE_WHITE' \
+ /// -F 'text_prompts[0][text]=A large spiral galaxy with a bright central bulge and a ring of stars around it' \
+ /// -F 'cfg_scale=7' \
+ /// -F 'clip_guidance_preset=FAST_BLUE' \
+ /// -F 'samples=1' \
+ /// -F 'steps=30' \
+ /// -o "$OUTPUT_FILE" + ///
+ global::System.Threading.Tasks.Task MaskingAsBytesAsStreamAsync( + string engineId, + global::System.IO.Stream initImage, + string initImagename, + global::System.Collections.Generic.IList textPrompts, + global::StabilityAI.MaskingAccept? accept = default, + string? organization = default, + global::System.IO.Stream? maskImage = default, + string? maskImagename = default, + double? cfgScale = default, + global::StabilityAI.ClipGuidancePreset? clipGuidancePreset = default, + global::StabilityAI.Sampler? sampler = default, + int? samples = default, + long? seed = default, + int? steps = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// image-to-image/masking
+ /// Selectively modify portions of an image using a mask + ///
+ /// + /// + /// Default Value: application/json + /// + /// + /// + /// Image used to initialize the diffusion process, in lieu of random noise.
+ /// Example: <image binary> + /// + /// + /// Image used to initialize the diffusion process, in lieu of random noise.
+ /// Example: <image binary> + /// + /// + /// Optional grayscale mask that allows for influence over which pixels are eligible for diffusion and at what strength. Must be the same dimensions as the `init_image`. Use the `mask_source` option to specify whether the white or black pixels should be inpainted.
+ /// Example: <image binary> + /// + /// + /// Optional grayscale mask that allows for influence over which pixels are eligible for diffusion and at what strength. Must be the same dimensions as the `init_image`. Use the `mask_source` option to specify whether the white or black pixels should be inpainted.
+ /// Example: <image binary> + /// + /// + /// An array of text prompts to use for generation.
+ /// Due to how arrays are represented in `multipart/form-data` requests, prompts must adhear to the format `text_prompts[index][text|weight]`,
+ /// where `index` is some integer used to tie the text and weight together. While `index` does not have to be sequential, duplicate entries
+ /// will override previous entries, so it is recommended to use sequential indices.
+ /// Given a text prompt with the text `A lighthouse on a cliff` and a weight of `0.5`, it would be represented as:
+ /// ```
+ /// text_prompts[0][text]: "A lighthouse on a cliff"
+ /// text_prompts[0][weight]: 0.5
+ /// ```
+ /// To add another prompt to that request simply provide the values under a new `index`:
+ /// ```
+ /// text_prompts[0][text]: "A lighthouse on a cliff"
+ /// text_prompts[0][weight]: 0.5
+ /// text_prompts[1][text]: "land, ground, dirt, grass"
+ /// text_prompts[1][weight]: -0.9
+ /// ``` + /// + /// + /// How strictly the diffusion process adheres to the prompt text (higher values keep your image closer to your prompt)
+ /// Default Value: 7
+ /// Example: 7 + /// + /// + /// Default Value: NONE
+ /// Example: FAST_BLUE + /// + /// + /// Which sampler to use for the diffusion process. If this value is omitted we'll automatically select an appropriate sampler for you.
+ /// Example: K_DPM_2_ANCESTRAL + /// + /// + /// Number of images to generate
+ /// Default Value: 1
+ /// Example: 1 + /// + /// + /// Random noise seed (omit this option or use `0` for a random seed)
+ /// Default Value: 0
+ /// Example: 0 + /// + /// + /// Number of diffusion steps to run
+ /// Default Value: 50
+ /// Example: 75 + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// #!/bin/sh
+ /// set -e
+ /// if [ -z "$STABILITY_API_KEY" ]; then
+ /// echo "STABILITY_API_KEY environment variable is not set"
+ /// exit 1
+ /// fi
+ /// OUTPUT_FILE=./out/v1_img2img_masking.png
+ /// BASE_URL=${API_HOST:-https://api.stability.ai}
+ /// URL="$BASE_URL/v1/generation/stable-inpainting-512-v2-0/image-to-image/masking"
+ /// curl -f -sS -X POST "$URL" \
+ /// -H 'Content-Type: multipart/form-data' \
+ /// -H 'Accept: image/png' \
+ /// -H "Authorization: Bearer $STABILITY_API_KEY" \
+ /// -F 'init_image=@"../init_image.png"' \
+ /// -F 'mask_image=@"../mask_image_white.png"' \
+ /// -F 'mask_source=MASK_IMAGE_WHITE' \
+ /// -F 'text_prompts[0][text]=A large spiral galaxy with a bright central bulge and a ring of stars around it' \
+ /// -F 'cfg_scale=7' \
+ /// -F 'clip_guidance_preset=FAST_BLUE' \
+ /// -F 'samples=1' \
+ /// -F 'steps=30' \
+ /// -o "$OUTPUT_FILE" + ///
+ global::System.Threading.Tasks.Task> MaskingAsBytesAsResponseAsync( + string engineId, + global::System.IO.Stream initImage, + string initImagename, + global::System.Collections.Generic.IList textPrompts, + global::StabilityAI.MaskingAccept? accept = default, + string? organization = default, + global::System.IO.Stream? maskImage = default, + string? maskImagename = default, + double? cfgScale = default, + global::StabilityAI.ClipGuidancePreset? clipGuidancePreset = default, + global::StabilityAI.Sampler? sampler = default, + int? samples = default, + long? seed = default, + int? steps = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + } +} \ No newline at end of file diff --git a/src/libs/StabilityAI/Generated/StabilityAI.IV1GenerationClient.TextToImageAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.IV1GenerationClient.TextToImageAsBytes.g.cs new file mode 100644 index 0000000..18f27c7 --- /dev/null +++ b/src/libs/StabilityAI/Generated/StabilityAI.IV1GenerationClient.TextToImageAsBytes.g.cs @@ -0,0 +1,178 @@ +#nullable enable + +namespace StabilityAI +{ + public partial interface IV1GenerationClient + { + /// + /// text-to-image
+ /// Generate a new image from a text prompt + ///
+ /// + /// Example: stable-diffusion-v1-5 + /// + /// + /// Default Value: application/json + /// + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// if [ -z "$STABILITY_API_KEY" ]; then
+ /// echo "STABILITY_API_KEY environment variable is not set"
+ /// exit 1
+ /// fi
+ /// OUTPUT_FILE=./out/v1_txt2img.png
+ /// BASE_URL=${API_HOST:-https://api.stability.ai}
+ /// URL="$BASE_URL/v1/generation/stable-diffusion-v1-5/text-to-image"
+ /// curl -f -sS -X POST "$URL" \
+ /// -H 'Content-Type: application/json' \
+ /// -H 'Accept: image/png' \
+ /// -H "Authorization: Bearer $STABILITY_API_KEY" \
+ /// --data-raw '{
+ /// "text_prompts": [
+ /// {
+ /// "text": "A lighthouse on a cliff"
+ /// }
+ /// ],
+ /// "cfg_scale": 7,
+ /// "clip_guidance_preset": "FAST_BLUE",
+ /// "height": 512,
+ /// "width": 512,
+ /// "samples": 1,
+ /// "steps": 30
+ /// }' \
+ /// -o "$OUTPUT_FILE" + ///
+ global::System.Threading.Tasks.Task TextToImageAsBytesAsync( + string engineId, + + global::StabilityAI.TextToImageRequestBody request, + global::StabilityAI.TextToImageAccept? accept = default, + string? organization = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// text-to-image
+ /// Generate a new image from a text prompt + ///
+ /// + /// Example: stable-diffusion-v1-5 + /// + /// + /// Default Value: application/json + /// + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// if [ -z "$STABILITY_API_KEY" ]; then
+ /// echo "STABILITY_API_KEY environment variable is not set"
+ /// exit 1
+ /// fi
+ /// OUTPUT_FILE=./out/v1_txt2img.png
+ /// BASE_URL=${API_HOST:-https://api.stability.ai}
+ /// URL="$BASE_URL/v1/generation/stable-diffusion-v1-5/text-to-image"
+ /// curl -f -sS -X POST "$URL" \
+ /// -H 'Content-Type: application/json' \
+ /// -H 'Accept: image/png' \
+ /// -H "Authorization: Bearer $STABILITY_API_KEY" \
+ /// --data-raw '{
+ /// "text_prompts": [
+ /// {
+ /// "text": "A lighthouse on a cliff"
+ /// }
+ /// ],
+ /// "cfg_scale": 7,
+ /// "clip_guidance_preset": "FAST_BLUE",
+ /// "height": 512,
+ /// "width": 512,
+ /// "samples": 1,
+ /// "steps": 30
+ /// }' \
+ /// -o "$OUTPUT_FILE" + ///
+ global::System.Threading.Tasks.Task TextToImageAsBytesAsStreamAsync( + string engineId, + + global::StabilityAI.TextToImageRequestBody request, + global::StabilityAI.TextToImageAccept? accept = default, + string? organization = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// text-to-image
+ /// Generate a new image from a text prompt + ///
+ /// + /// Example: stable-diffusion-v1-5 + /// + /// + /// Default Value: application/json + /// + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// if [ -z "$STABILITY_API_KEY" ]; then
+ /// echo "STABILITY_API_KEY environment variable is not set"
+ /// exit 1
+ /// fi
+ /// OUTPUT_FILE=./out/v1_txt2img.png
+ /// BASE_URL=${API_HOST:-https://api.stability.ai}
+ /// URL="$BASE_URL/v1/generation/stable-diffusion-v1-5/text-to-image"
+ /// curl -f -sS -X POST "$URL" \
+ /// -H 'Content-Type: application/json' \
+ /// -H 'Accept: image/png' \
+ /// -H "Authorization: Bearer $STABILITY_API_KEY" \
+ /// --data-raw '{
+ /// "text_prompts": [
+ /// {
+ /// "text": "A lighthouse on a cliff"
+ /// }
+ /// ],
+ /// "cfg_scale": 7,
+ /// "clip_guidance_preset": "FAST_BLUE",
+ /// "height": 512,
+ /// "width": 512,
+ /// "samples": 1,
+ /// "steps": 30
+ /// }' \
+ /// -o "$OUTPUT_FILE" + ///
+ global::System.Threading.Tasks.Task> TextToImageAsBytesAsResponseAsync( + string engineId, + + global::StabilityAI.TextToImageRequestBody request, + global::StabilityAI.TextToImageAccept? accept = default, + string? organization = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// text-to-image
+ /// Generate a new image from a text prompt + ///
+ /// + /// Example: stable-diffusion-v1-5 + /// + /// + /// Default Value: application/json + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + global::System.Threading.Tasks.Task TextToImageAsBytesAsync( + string engineId, + global::StabilityAI.TextToImageAccept? accept = default, + string? organization = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + } +} \ No newline at end of file diff --git a/src/libs/StabilityAI/Generated/StabilityAI.IV1GenerationClient.UpscaleImageAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.IV1GenerationClient.UpscaleImageAsBytes.g.cs new file mode 100644 index 0000000..c4d83b1 --- /dev/null +++ b/src/libs/StabilityAI/Generated/StabilityAI.IV1GenerationClient.UpscaleImageAsBytes.g.cs @@ -0,0 +1,318 @@ +#nullable enable + +namespace StabilityAI +{ + public partial interface IV1GenerationClient + { + /// + /// image-to-image/upscale
+ /// Create a higher resolution version of an input image.
+ /// This operation outputs an image with a maximum pixel count of **4,194,304**. This is equivalent to dimensions such as `2048x2048` and `4096x1024`.
+ /// By default, the input image will be upscaled by a factor of 2. For additional control over the output dimensions, a `width` or `height` parameter may be specified. + ///
+ /// + /// + /// Default Value: application/json + /// + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// if [ -z "$STABILITY_API_KEY" ]; then
+ /// echo "STABILITY_API_KEY environment variable is not set"
+ /// exit 1
+ /// fi
+ /// OUTPUT_FILE=./out/v1_upscaled_image.png
+ /// BASE_URL=${API_HOST:-https://api.stability.ai}
+ /// URL="$BASE_URL/v1/generation/esrgan-v1-x2plus/image-to-image/upscale"
+ /// curl -f -sS -X POST "$URL" \
+ /// -H 'Content-Type: multipart/form-data' \
+ /// -H 'Accept: image/png' \
+ /// -H "Authorization: Bearer $STABILITY_API_KEY" \
+ /// -F 'image=@"../init_image.png"' \
+ /// -F 'width=1024' \
+ /// -o "$OUTPUT_FILE" + ///
+ global::System.Threading.Tasks.Task UpscaleImageAsBytesAsync( + string engineId, + + global::StabilityAI.UpscaleImageRequestBody request, + global::StabilityAI.UpscaleImageAccept? accept = default, + string? organization = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// image-to-image/upscale
+ /// Create a higher resolution version of an input image.
+ /// This operation outputs an image with a maximum pixel count of **4,194,304**. This is equivalent to dimensions such as `2048x2048` and `4096x1024`.
+ /// By default, the input image will be upscaled by a factor of 2. For additional control over the output dimensions, a `width` or `height` parameter may be specified. + ///
+ /// + /// + /// Default Value: application/json + /// + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// if [ -z "$STABILITY_API_KEY" ]; then
+ /// echo "STABILITY_API_KEY environment variable is not set"
+ /// exit 1
+ /// fi
+ /// OUTPUT_FILE=./out/v1_upscaled_image.png
+ /// BASE_URL=${API_HOST:-https://api.stability.ai}
+ /// URL="$BASE_URL/v1/generation/esrgan-v1-x2plus/image-to-image/upscale"
+ /// curl -f -sS -X POST "$URL" \
+ /// -H 'Content-Type: multipart/form-data' \
+ /// -H 'Accept: image/png' \
+ /// -H "Authorization: Bearer $STABILITY_API_KEY" \
+ /// -F 'image=@"../init_image.png"' \
+ /// -F 'width=1024' \
+ /// -o "$OUTPUT_FILE" + ///
+ global::System.Threading.Tasks.Task UpscaleImageAsBytesAsStreamAsync( + string engineId, + + global::StabilityAI.UpscaleImageRequestBody request, + global::StabilityAI.UpscaleImageAccept? accept = default, + string? organization = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// image-to-image/upscale
+ /// Create a higher resolution version of an input image.
+ /// This operation outputs an image with a maximum pixel count of **4,194,304**. This is equivalent to dimensions such as `2048x2048` and `4096x1024`.
+ /// By default, the input image will be upscaled by a factor of 2. For additional control over the output dimensions, a `width` or `height` parameter may be specified. + ///
+ /// + /// + /// Default Value: application/json + /// + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// if [ -z "$STABILITY_API_KEY" ]; then
+ /// echo "STABILITY_API_KEY environment variable is not set"
+ /// exit 1
+ /// fi
+ /// OUTPUT_FILE=./out/v1_upscaled_image.png
+ /// BASE_URL=${API_HOST:-https://api.stability.ai}
+ /// URL="$BASE_URL/v1/generation/esrgan-v1-x2plus/image-to-image/upscale"
+ /// curl -f -sS -X POST "$URL" \
+ /// -H 'Content-Type: multipart/form-data' \
+ /// -H 'Accept: image/png' \
+ /// -H "Authorization: Bearer $STABILITY_API_KEY" \
+ /// -F 'image=@"../init_image.png"' \
+ /// -F 'width=1024' \
+ /// -o "$OUTPUT_FILE" + ///
+ global::System.Threading.Tasks.Task> UpscaleImageAsBytesAsResponseAsync( + string engineId, + + global::StabilityAI.UpscaleImageRequestBody request, + global::StabilityAI.UpscaleImageAccept? accept = default, + string? organization = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// image-to-image/upscale
+ /// Create a higher resolution version of an input image.
+ /// This operation outputs an image with a maximum pixel count of **4,194,304**. This is equivalent to dimensions such as `2048x2048` and `4096x1024`.
+ /// By default, the input image will be upscaled by a factor of 2. For additional control over the output dimensions, a `width` or `height` parameter may be specified. + ///
+ /// + /// + /// Default Value: application/json + /// + /// + /// + /// Example: <image binary> + /// + /// + /// Example: <image binary> + /// + /// + /// Desired width of the output image. Only one of `width` or `height` may be specified. + /// + /// + /// Desired height of the output image. Only one of `width` or `height` may be specified. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + global::System.Threading.Tasks.Task UpscaleImageAsBytesAsync( + string engineId, + byte[] image, + string imagename, + global::StabilityAI.UpscaleImageAccept? accept = default, + string? organization = default, + int? width = default, + int? height = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + + /// + /// image-to-image/upscale
+ /// Create a higher resolution version of an input image.
+ /// This operation outputs an image with a maximum pixel count of **4,194,304**. This is equivalent to dimensions such as `2048x2048` and `4096x1024`.
+ /// By default, the input image will be upscaled by a factor of 2. For additional control over the output dimensions, a `width` or `height` parameter may be specified. + ///
+ /// + /// + /// Default Value: application/json + /// + /// + /// + /// Example: <image binary> + /// + /// + /// Example: <image binary> + /// + /// + /// Desired width of the output image. Only one of `width` or `height` may be specified. + /// + /// + /// Desired height of the output image. Only one of `width` or `height` may be specified. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// if [ -z "$STABILITY_API_KEY" ]; then
+ /// echo "STABILITY_API_KEY environment variable is not set"
+ /// exit 1
+ /// fi
+ /// OUTPUT_FILE=./out/v1_upscaled_image.png
+ /// BASE_URL=${API_HOST:-https://api.stability.ai}
+ /// URL="$BASE_URL/v1/generation/esrgan-v1-x2plus/image-to-image/upscale"
+ /// curl -f -sS -X POST "$URL" \
+ /// -H 'Content-Type: multipart/form-data' \
+ /// -H 'Accept: image/png' \
+ /// -H "Authorization: Bearer $STABILITY_API_KEY" \
+ /// -F 'image=@"../init_image.png"' \
+ /// -F 'width=1024' \
+ /// -o "$OUTPUT_FILE" + ///
+ global::System.Threading.Tasks.Task UpscaleImageAsBytesAsync( + string engineId, + global::System.IO.Stream image, + string imagename, + global::StabilityAI.UpscaleImageAccept? accept = default, + string? organization = default, + int? width = default, + int? height = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// image-to-image/upscale
+ /// Create a higher resolution version of an input image.
+ /// This operation outputs an image with a maximum pixel count of **4,194,304**. This is equivalent to dimensions such as `2048x2048` and `4096x1024`.
+ /// By default, the input image will be upscaled by a factor of 2. For additional control over the output dimensions, a `width` or `height` parameter may be specified. + ///
+ /// + /// + /// Default Value: application/json + /// + /// + /// + /// Example: <image binary> + /// + /// + /// Example: <image binary> + /// + /// + /// Desired width of the output image. Only one of `width` or `height` may be specified. + /// + /// + /// Desired height of the output image. Only one of `width` or `height` may be specified. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// if [ -z "$STABILITY_API_KEY" ]; then
+ /// echo "STABILITY_API_KEY environment variable is not set"
+ /// exit 1
+ /// fi
+ /// OUTPUT_FILE=./out/v1_upscaled_image.png
+ /// BASE_URL=${API_HOST:-https://api.stability.ai}
+ /// URL="$BASE_URL/v1/generation/esrgan-v1-x2plus/image-to-image/upscale"
+ /// curl -f -sS -X POST "$URL" \
+ /// -H 'Content-Type: multipart/form-data' \
+ /// -H 'Accept: image/png' \
+ /// -H "Authorization: Bearer $STABILITY_API_KEY" \
+ /// -F 'image=@"../init_image.png"' \
+ /// -F 'width=1024' \
+ /// -o "$OUTPUT_FILE" + ///
+ global::System.Threading.Tasks.Task UpscaleImageAsBytesAsStreamAsync( + string engineId, + global::System.IO.Stream image, + string imagename, + global::StabilityAI.UpscaleImageAccept? accept = default, + string? organization = default, + int? width = default, + int? height = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// image-to-image/upscale
+ /// Create a higher resolution version of an input image.
+ /// This operation outputs an image with a maximum pixel count of **4,194,304**. This is equivalent to dimensions such as `2048x2048` and `4096x1024`.
+ /// By default, the input image will be upscaled by a factor of 2. For additional control over the output dimensions, a `width` or `height` parameter may be specified. + ///
+ /// + /// + /// Default Value: application/json + /// + /// + /// + /// Example: <image binary> + /// + /// + /// Example: <image binary> + /// + /// + /// Desired width of the output image. Only one of `width` or `height` may be specified. + /// + /// + /// Desired height of the output image. Only one of `width` or `height` may be specified. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// if [ -z "$STABILITY_API_KEY" ]; then
+ /// echo "STABILITY_API_KEY environment variable is not set"
+ /// exit 1
+ /// fi
+ /// OUTPUT_FILE=./out/v1_upscaled_image.png
+ /// BASE_URL=${API_HOST:-https://api.stability.ai}
+ /// URL="$BASE_URL/v1/generation/esrgan-v1-x2plus/image-to-image/upscale"
+ /// curl -f -sS -X POST "$URL" \
+ /// -H 'Content-Type: multipart/form-data' \
+ /// -H 'Accept: image/png' \
+ /// -H "Authorization: Bearer $STABILITY_API_KEY" \
+ /// -F 'image=@"../init_image.png"' \
+ /// -F 'width=1024' \
+ /// -o "$OUTPUT_FILE" + ///
+ global::System.Threading.Tasks.Task> UpscaleImageAsBytesAsResponseAsync( + string engineId, + global::System.IO.Stream image, + string imagename, + global::StabilityAI.UpscaleImageAccept? accept = default, + string? organization = default, + int? width = default, + int? height = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + } +} \ No newline at end of file diff --git a/src/libs/StabilityAI/Generated/StabilityAI.IV2alphaGenerationClient.CreateV2alphaGenerationStableImageInpaintAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.IV2alphaGenerationClient.CreateV2alphaGenerationStableImageInpaintAsBytes.g.cs new file mode 100644 index 0000000..bb43b0a --- /dev/null +++ b/src/libs/StabilityAI/Generated/StabilityAI.IV2alphaGenerationClient.CreateV2alphaGenerationStableImageInpaintAsBytes.g.cs @@ -0,0 +1,234 @@ +#nullable enable + +namespace StabilityAI +{ + public partial interface IV2alphaGenerationClient + { + /// + /// stable-image/inpaint
+ /// Inpaint an existing image, with or without a mask, using our latest-and-greatest inpainting model.
+ /// ### Search-and-Replace Mode
+ /// This mode is ideal for individuals of all levels of skill in design. It can be used for straightforward
+ /// adjustments to images. The service will automatically mask the most appropriate object based on the contents
+ /// of the `search_prompt`, and replace it with a generated result based on the `prompt`.
+ /// **How to use:** set the `mode` parameter to `search` and provide a short description of what to
+ /// search-and-replace in the `search_prompt` parameter.
+ /// ### Mask Mode
+ /// This mode allows for precise control of generative fill tasks on an image, down to the level of
+ /// individual pixels. Design professionals can provide a `mask` for the section of the image to be replaced,
+ /// and use standard image prompting to describe the full image as it should appear after the editing.
+ /// The resulting image will incorporate all of the elements described in the `prompt`.
+ /// **How to use:** set the `mode` parameter to `mask` and either pass in an `image` with an alpha channel
+ /// or provide an explicit mask image to the `mask` parameter. If both are present the `mask` parameter will
+ /// take precedence.
+ /// ### Price
+ /// - Requests with `mode` set to `search` cost 4 cents.
+ /// - Requests with `mode` set to `mask` cost 3 cents. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to get the image bytes directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2alpha/generation/stable-image/inpaint",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY"
+ /// },
+ /// files={
+ /// "image": open("./husky-in-a-field.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "golden retriever in a field",
+ /// "mode": "search",
+ /// "search_prompt": "dog",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./golden-retriever-in-a-field.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateV2alphaGenerationStableImageInpaintAsBytesAsync( + string contentType, + + global::StabilityAI.CreateV2alphaGenerationStableImageInpaintRequest request, + global::StabilityAI.CreateV2alphaGenerationStableImageInpaintAccept? accept = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// stable-image/inpaint
+ /// Inpaint an existing image, with or without a mask, using our latest-and-greatest inpainting model.
+ /// ### Search-and-Replace Mode
+ /// This mode is ideal for individuals of all levels of skill in design. It can be used for straightforward
+ /// adjustments to images. The service will automatically mask the most appropriate object based on the contents
+ /// of the `search_prompt`, and replace it with a generated result based on the `prompt`.
+ /// **How to use:** set the `mode` parameter to `search` and provide a short description of what to
+ /// search-and-replace in the `search_prompt` parameter.
+ /// ### Mask Mode
+ /// This mode allows for precise control of generative fill tasks on an image, down to the level of
+ /// individual pixels. Design professionals can provide a `mask` for the section of the image to be replaced,
+ /// and use standard image prompting to describe the full image as it should appear after the editing.
+ /// The resulting image will incorporate all of the elements described in the `prompt`.
+ /// **How to use:** set the `mode` parameter to `mask` and either pass in an `image` with an alpha channel
+ /// or provide an explicit mask image to the `mask` parameter. If both are present the `mask` parameter will
+ /// take precedence.
+ /// ### Price
+ /// - Requests with `mode` set to `search` cost 4 cents.
+ /// - Requests with `mode` set to `mask` cost 3 cents. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to get the image bytes directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2alpha/generation/stable-image/inpaint",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY"
+ /// },
+ /// files={
+ /// "image": open("./husky-in-a-field.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "golden retriever in a field",
+ /// "mode": "search",
+ /// "search_prompt": "dog",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./golden-retriever-in-a-field.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task CreateV2alphaGenerationStableImageInpaintAsBytesAsStreamAsync( + string contentType, + + global::StabilityAI.CreateV2alphaGenerationStableImageInpaintRequest request, + global::StabilityAI.CreateV2alphaGenerationStableImageInpaintAccept? accept = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// stable-image/inpaint
+ /// Inpaint an existing image, with or without a mask, using our latest-and-greatest inpainting model.
+ /// ### Search-and-Replace Mode
+ /// This mode is ideal for individuals of all levels of skill in design. It can be used for straightforward
+ /// adjustments to images. The service will automatically mask the most appropriate object based on the contents
+ /// of the `search_prompt`, and replace it with a generated result based on the `prompt`.
+ /// **How to use:** set the `mode` parameter to `search` and provide a short description of what to
+ /// search-and-replace in the `search_prompt` parameter.
+ /// ### Mask Mode
+ /// This mode allows for precise control of generative fill tasks on an image, down to the level of
+ /// individual pixels. Design professionals can provide a `mask` for the section of the image to be replaced,
+ /// and use standard image prompting to describe the full image as it should appear after the editing.
+ /// The resulting image will incorporate all of the elements described in the `prompt`.
+ /// **How to use:** set the `mode` parameter to `mask` and either pass in an `image` with an alpha channel
+ /// or provide an explicit mask image to the `mask` parameter. If both are present the `mask` parameter will
+ /// take precedence.
+ /// ### Price
+ /// - Requests with `mode` set to `search` cost 4 cents.
+ /// - Requests with `mode` set to `mask` cost 3 cents. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to get the image bytes directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2alpha/generation/stable-image/inpaint",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY"
+ /// },
+ /// files={
+ /// "image": open("./husky-in-a-field.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "golden retriever in a field",
+ /// "mode": "search",
+ /// "search_prompt": "dog",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./golden-retriever-in-a-field.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task> CreateV2alphaGenerationStableImageInpaintAsBytesAsResponseAsync( + string contentType, + + global::StabilityAI.CreateV2alphaGenerationStableImageInpaintRequest request, + global::StabilityAI.CreateV2alphaGenerationStableImageInpaintAccept? accept = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// stable-image/inpaint
+ /// Inpaint an existing image, with or without a mask, using our latest-and-greatest inpainting model.
+ /// ### Search-and-Replace Mode
+ /// This mode is ideal for individuals of all levels of skill in design. It can be used for straightforward
+ /// adjustments to images. The service will automatically mask the most appropriate object based on the contents
+ /// of the `search_prompt`, and replace it with a generated result based on the `prompt`.
+ /// **How to use:** set the `mode` parameter to `search` and provide a short description of what to
+ /// search-and-replace in the `search_prompt` parameter.
+ /// ### Mask Mode
+ /// This mode allows for precise control of generative fill tasks on an image, down to the level of
+ /// individual pixels. Design professionals can provide a `mask` for the section of the image to be replaced,
+ /// and use standard image prompting to describe the full image as it should appear after the editing.
+ /// The resulting image will incorporate all of the elements described in the `prompt`.
+ /// **How to use:** set the `mode` parameter to `mask` and either pass in an `image` with an alpha channel
+ /// or provide an explicit mask image to the `mask` parameter. If both are present the `mask` parameter will
+ /// take precedence.
+ /// ### Price
+ /// - Requests with `mode` set to `search` cost 4 cents.
+ /// - Requests with `mode` set to `mask` cost 3 cents. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to get the image bytes directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + global::System.Threading.Tasks.Task CreateV2alphaGenerationStableImageInpaintAsBytesAsync( + string contentType, + global::StabilityAI.CreateV2alphaGenerationStableImageInpaintAccept? accept = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + } +} \ No newline at end of file diff --git a/src/libs/StabilityAI/Generated/StabilityAI.IV2alphaGenerationClient.GetV2alphaGenerationStableImageUpscaleResultByIdAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.IV2alphaGenerationClient.GetV2alphaGenerationStableImageUpscaleResultByIdAsBytes.g.cs new file mode 100644 index 0000000..da8e712 --- /dev/null +++ b/src/libs/StabilityAI/Generated/StabilityAI.IV2alphaGenerationClient.GetV2alphaGenerationStableImageUpscaleResultByIdAsBytes.g.cs @@ -0,0 +1,146 @@ +#nullable enable + +namespace StabilityAI +{ + public partial interface IV2alphaGenerationClient + { + /// + /// stable-image/upscale/result
+ /// Fetch the result of an upscale generation by ID. Make sure to use the same API key to fetch the generation result
+ /// that you used to create the generation, otherwise you will receive a `404` response.
+ /// ### How is progress reported?
+ /// Your generation is either `in-progress` (i.e. status code `202`) or it is complete (i.e. status code `200`).
+ /// We may add more fine-grained progress reporting in the future (e.g. a numerical progress).
+ /// ### How long are results stored?
+ /// Results are stored for 24 hours after generation. After that, the results are deleted. + ///
+ /// + /// The `id` of a generation, typically used for async generations, that can be used to check the status of the generation or retrieve the result.
+ /// Example: a6dc6c6e20acda010fe14d71f180658f2896ed9b4ec25aa99a6ff06c796987c4 + /// + /// + /// Specify `image/*` to get the image bytes directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// generation_id = "e52772ac75b..."
+ /// response = requests.request(
+ /// "GET",
+ /// f"https://api.stability.ai/v2alpha/generation/stable-image/upscale/result/{generation_id}",
+ /// headers={
+ /// 'Accept': "image/*", # Use 'application/json' to receive base64 encoded JSON
+ /// 'authorization': f"Bearer sk-MYAPIKEY"
+ /// },
+ /// )
+ /// if response.status_code == 202:
+ /// print("Generation in-progress, try again in 10 seconds.")
+ /// elif response.status_code == 200:
+ /// print("Generation complete!")
+ /// with open("upscaled.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task GetV2alphaGenerationStableImageUpscaleResultByIdAsBytesAsync( + string id, + global::StabilityAI.GetV2alphaGenerationStableImageUpscaleResultAccept? accept = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// stable-image/upscale/result
+ /// Fetch the result of an upscale generation by ID. Make sure to use the same API key to fetch the generation result
+ /// that you used to create the generation, otherwise you will receive a `404` response.
+ /// ### How is progress reported?
+ /// Your generation is either `in-progress` (i.e. status code `202`) or it is complete (i.e. status code `200`).
+ /// We may add more fine-grained progress reporting in the future (e.g. a numerical progress).
+ /// ### How long are results stored?
+ /// Results are stored for 24 hours after generation. After that, the results are deleted. + ///
+ /// + /// The `id` of a generation, typically used for async generations, that can be used to check the status of the generation or retrieve the result.
+ /// Example: a6dc6c6e20acda010fe14d71f180658f2896ed9b4ec25aa99a6ff06c796987c4 + /// + /// + /// Specify `image/*` to get the image bytes directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// generation_id = "e52772ac75b..."
+ /// response = requests.request(
+ /// "GET",
+ /// f"https://api.stability.ai/v2alpha/generation/stable-image/upscale/result/{generation_id}",
+ /// headers={
+ /// 'Accept': "image/*", # Use 'application/json' to receive base64 encoded JSON
+ /// 'authorization': f"Bearer sk-MYAPIKEY"
+ /// },
+ /// )
+ /// if response.status_code == 202:
+ /// print("Generation in-progress, try again in 10 seconds.")
+ /// elif response.status_code == 200:
+ /// print("Generation complete!")
+ /// with open("upscaled.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task GetV2alphaGenerationStableImageUpscaleResultByIdAsBytesAsStreamAsync( + string id, + global::StabilityAI.GetV2alphaGenerationStableImageUpscaleResultAccept? accept = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + /// + /// stable-image/upscale/result
+ /// Fetch the result of an upscale generation by ID. Make sure to use the same API key to fetch the generation result
+ /// that you used to create the generation, otherwise you will receive a `404` response.
+ /// ### How is progress reported?
+ /// Your generation is either `in-progress` (i.e. status code `202`) or it is complete (i.e. status code `200`).
+ /// We may add more fine-grained progress reporting in the future (e.g. a numerical progress).
+ /// ### How long are results stored?
+ /// Results are stored for 24 hours after generation. After that, the results are deleted. + ///
+ /// + /// The `id` of a generation, typically used for async generations, that can be used to check the status of the generation or retrieve the result.
+ /// Example: a6dc6c6e20acda010fe14d71f180658f2896ed9b4ec25aa99a6ff06c796987c4 + /// + /// + /// Specify `image/*` to get the image bytes directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// generation_id = "e52772ac75b..."
+ /// response = requests.request(
+ /// "GET",
+ /// f"https://api.stability.ai/v2alpha/generation/stable-image/upscale/result/{generation_id}",
+ /// headers={
+ /// 'Accept': "image/*", # Use 'application/json' to receive base64 encoded JSON
+ /// 'authorization': f"Bearer sk-MYAPIKEY"
+ /// },
+ /// )
+ /// if response.status_code == 202:
+ /// print("Generation in-progress, try again in 10 seconds.")
+ /// elif response.status_code == 200:
+ /// print("Generation complete!")
+ /// with open("upscaled.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ global::System.Threading.Tasks.Task> GetV2alphaGenerationStableImageUpscaleResultByIdAsBytesAsResponseAsync( + string id, + global::StabilityAI.GetV2alphaGenerationStableImageUpscaleResultAccept? accept = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default); + } +} \ No newline at end of file diff --git a/src/libs/StabilityAI/Generated/StabilityAI.ResultsClient.GetResultsById.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.ResultsClient.GetResultsById.g.cs index c9f0a86..36a4a47 100644 --- a/src/libs/StabilityAI/Generated/StabilityAI.ResultsClient.GetResultsById.g.cs +++ b/src/libs/StabilityAI/Generated/StabilityAI.ResultsClient.GetResultsById.g.cs @@ -244,6 +244,10 @@ partial void ProcessGetResultsByIdResponseContent( __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || diff --git a/src/libs/StabilityAI/Generated/StabilityAI.ResultsClient.GetResultsByIdAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.ResultsClient.GetResultsByIdAsBytes.g.cs new file mode 100644 index 0000000..28b1f75 --- /dev/null +++ b/src/libs/StabilityAI/Generated/StabilityAI.ResultsClient.GetResultsByIdAsBytes.g.cs @@ -0,0 +1,1189 @@ + +#nullable enable + +namespace StabilityAI +{ + public partial class ResultsClient + { + + + private static readonly global::StabilityAI.EndPointSecurityRequirement s_GetResultsByIdAsBytesSecurityRequirement0 = + new global::StabilityAI.EndPointSecurityRequirement + { + Authorizations = new global::StabilityAI.EndPointAuthorizationRequirement[] + { new global::StabilityAI.EndPointAuthorizationRequirement + { + Type = "Http", + SchemeId = "HttpBearer", + Location = "Header", + Name = "Bearer", + FriendlyName = "Bearer", + }, + }, + }; + private static readonly global::StabilityAI.EndPointSecurityRequirement[] s_GetResultsByIdAsBytesSecurityRequirements = + new global::StabilityAI.EndPointSecurityRequirement[] + { s_GetResultsByIdAsBytesSecurityRequirement0, + }; + partial void PrepareGetResultsByIdAsBytesArguments( + global::System.Net.Http.HttpClient httpClient, + ref string id, + ref global::StabilityAI.GetResultsAccept? accept, + ref string? stabilityClientId, + ref string? stabilityClientUserId, + ref string? stabilityClientVersion); + partial void PrepareGetResultsByIdAsBytesRequest( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpRequestMessage httpRequestMessage, + string id, + global::StabilityAI.GetResultsAccept? accept, + string? stabilityClientId, + string? stabilityClientUserId, + string? stabilityClientVersion); + partial void ProcessGetResultsByIdAsBytesResponse( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpResponseMessage httpResponseMessage); + + partial void ProcessGetResultsByIdAsBytesResponseContent( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpResponseMessage httpResponseMessage, + ref byte[] content); + + /// + /// Fetch async generation result
+ /// Fetch the result of a generation by ID.
+ /// Make sure to use the same API key to fetch the generation result that you used to create the generation,
+ /// otherwise you will receive a `404` response.
+ /// ### How to use
+ /// Please invoke this endpoint with a `GET` request.
+ /// The headers of the request must include an API key in the `authorization` field and the ID
+ /// of your generation must be in the path.
+ /// ### How is progress reported?
+ /// Your generation is either `in-progress` (i.e. status code `202`) or it is complete (i.e. status code `200`).
+ /// We may add more fine-grained progress reporting in the future (e.g. a numerical progress).
+ /// ### How long are results stored?
+ /// Results are stored for 24 hours after generation. After that, the results are deleted. + ///
+ /// + /// The `id` of a generation, typically used for async generations, that can be used to check the status of the generation or retrieve the result.
+ /// Example: a6dc6c6e20acda010fe14d71f180658f2896ed9b4ec25aa99a6ff06c796987c4 + /// + /// + /// Specify `*/*` to receive the bytes of the result directly. Otherwise specify `application/json` to receive the result as base64 encoded JSON.
+ /// Default Value: */* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// generation_id = "e52772ac75b..."
+ /// response = requests.request(
+ /// "GET",
+ /// f"https://api.stability.ai/v2beta/results/{generation_id}",
+ /// headers={
+ /// 'accept': "image/*", # Use 'application/json' to receive base64 encoded JSON
+ /// 'authorization': f"Bearer sk-MYAPIKEY"
+ /// },
+ /// )
+ /// if response.status_code == 202:
+ /// print("Generation in-progress, try again in 10 seconds.")
+ /// elif response.status_code == 200:
+ /// print("Generation complete!")
+ /// with open("result.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task GetResultsByIdAsBytesAsync( + string id, + global::StabilityAI.GetResultsAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + var __response = await GetResultsByIdAsBytesAsResponseAsync( + id: id, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + requestOptions: requestOptions, + cancellationToken: cancellationToken + ).ConfigureAwait(false); + + return __response.Body; + } + /// + /// Fetch async generation result
+ /// Fetch the result of a generation by ID.
+ /// Make sure to use the same API key to fetch the generation result that you used to create the generation,
+ /// otherwise you will receive a `404` response.
+ /// ### How to use
+ /// Please invoke this endpoint with a `GET` request.
+ /// The headers of the request must include an API key in the `authorization` field and the ID
+ /// of your generation must be in the path.
+ /// ### How is progress reported?
+ /// Your generation is either `in-progress` (i.e. status code `202`) or it is complete (i.e. status code `200`).
+ /// We may add more fine-grained progress reporting in the future (e.g. a numerical progress).
+ /// ### How long are results stored?
+ /// Results are stored for 24 hours after generation. After that, the results are deleted. + ///
+ /// + /// The `id` of a generation, typically used for async generations, that can be used to check the status of the generation or retrieve the result.
+ /// Example: a6dc6c6e20acda010fe14d71f180658f2896ed9b4ec25aa99a6ff06c796987c4 + /// + /// + /// Specify `*/*` to receive the bytes of the result directly. Otherwise specify `application/json` to receive the result as base64 encoded JSON.
+ /// Default Value: */* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// generation_id = "e52772ac75b..."
+ /// response = requests.request(
+ /// "GET",
+ /// f"https://api.stability.ai/v2beta/results/{generation_id}",
+ /// headers={
+ /// 'accept': "image/*", # Use 'application/json' to receive base64 encoded JSON
+ /// 'authorization': f"Bearer sk-MYAPIKEY"
+ /// },
+ /// )
+ /// if response.status_code == 202:
+ /// print("Generation in-progress, try again in 10 seconds.")
+ /// elif response.status_code == 200:
+ /// print("Generation complete!")
+ /// with open("result.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task GetResultsByIdAsBytesAsStreamAsync( + string id, + global::StabilityAI.GetResultsAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + PrepareArguments( + client: HttpClient); + PrepareGetResultsByIdAsBytesArguments( + httpClient: HttpClient, + id: ref id, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_GetResultsByIdAsBytesSecurityRequirements, + operationName: "GetResultsByIdAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: true); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: $"/v2beta/results/{id}", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Get, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/jpeg"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareGetResultsByIdAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + id: id!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "getResultsByIdAsBytes", + methodName: "GetResultsByIdAsBytesAsync", + pathTemplate: "$\"/v2beta/results/{id}\"", + httpMethod: "GET", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseHeadersRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "getResultsByIdAsBytes", + methodName: "GetResultsByIdAsBytesAsync", + pathTemplate: "$\"/v2beta/results/{id}\"", + httpMethod: "GET", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "getResultsByIdAsBytes", + methodName: "GetResultsByIdAsBytesAsync", + pathTemplate: "$\"/v2beta/results/{id}\"", + httpMethod: "GET", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + try + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessGetResultsByIdAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "getResultsByIdAsBytes", + methodName: "GetResultsByIdAsBytesAsync", + pathTemplate: "$\"/v2beta/results/{id}\"", + httpMethod: "GET", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "getResultsByIdAsBytes", + methodName: "GetResultsByIdAsBytesAsync", + pathTemplate: "$\"/v2beta/results/{id}\"", + httpMethod: "GET", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.GetResultsResponse5? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.GetResultsResponse5.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.GetResultsResponse5.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // id: the generation either does not exist or has expired. + if ((int)__response.StatusCode == 404) + { + string? __content_404 = null; + global::System.Exception? __exception_404 = null; + global::StabilityAI.GetResultsResponse6? __value_404 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_404 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_404 = global::StabilityAI.GetResultsResponse6.FromJson(__content_404, JsonSerializerContext); + } + else + { + __content_404 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_404 = global::StabilityAI.GetResultsResponse6.FromJson(__content_404, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_404 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_404 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_404, + responseBody: __content_404, + responseObject: __value_404, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.GetResultsResponse7? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.GetResultsResponse7.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.GetResultsResponse7.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + try + { + __response.EnsureSuccessStatusCode(); + + var __content = await __response.Content.ReadAsStreamAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.ResponseStream(__response, __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + } + catch + { + __response.Dispose(); + throw; + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Fetch async generation result
+ /// Fetch the result of a generation by ID.
+ /// Make sure to use the same API key to fetch the generation result that you used to create the generation,
+ /// otherwise you will receive a `404` response.
+ /// ### How to use
+ /// Please invoke this endpoint with a `GET` request.
+ /// The headers of the request must include an API key in the `authorization` field and the ID
+ /// of your generation must be in the path.
+ /// ### How is progress reported?
+ /// Your generation is either `in-progress` (i.e. status code `202`) or it is complete (i.e. status code `200`).
+ /// We may add more fine-grained progress reporting in the future (e.g. a numerical progress).
+ /// ### How long are results stored?
+ /// Results are stored for 24 hours after generation. After that, the results are deleted. + ///
+ /// + /// The `id` of a generation, typically used for async generations, that can be used to check the status of the generation or retrieve the result.
+ /// Example: a6dc6c6e20acda010fe14d71f180658f2896ed9b4ec25aa99a6ff06c796987c4 + /// + /// + /// Specify `*/*` to receive the bytes of the result directly. Otherwise specify `application/json` to receive the result as base64 encoded JSON.
+ /// Default Value: */* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// generation_id = "e52772ac75b..."
+ /// response = requests.request(
+ /// "GET",
+ /// f"https://api.stability.ai/v2beta/results/{generation_id}",
+ /// headers={
+ /// 'accept': "image/*", # Use 'application/json' to receive base64 encoded JSON
+ /// 'authorization': f"Bearer sk-MYAPIKEY"
+ /// },
+ /// )
+ /// if response.status_code == 202:
+ /// print("Generation in-progress, try again in 10 seconds.")
+ /// elif response.status_code == 200:
+ /// print("Generation complete!")
+ /// with open("result.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task> GetResultsByIdAsBytesAsResponseAsync( + string id, + global::StabilityAI.GetResultsAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + PrepareArguments( + client: HttpClient); + PrepareGetResultsByIdAsBytesArguments( + httpClient: HttpClient, + id: ref id, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_GetResultsByIdAsBytesSecurityRequirements, + operationName: "GetResultsByIdAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: true); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: $"/v2beta/results/{id}", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Get, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/jpeg"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareGetResultsByIdAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + id: id!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "getResultsByIdAsBytes", + methodName: "GetResultsByIdAsBytesAsync", + pathTemplate: "$\"/v2beta/results/{id}\"", + httpMethod: "GET", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "getResultsByIdAsBytes", + methodName: "GetResultsByIdAsBytesAsync", + pathTemplate: "$\"/v2beta/results/{id}\"", + httpMethod: "GET", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "getResultsByIdAsBytes", + methodName: "GetResultsByIdAsBytesAsync", + pathTemplate: "$\"/v2beta/results/{id}\"", + httpMethod: "GET", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessGetResultsByIdAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "getResultsByIdAsBytes", + methodName: "GetResultsByIdAsBytesAsync", + pathTemplate: "$\"/v2beta/results/{id}\"", + httpMethod: "GET", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "getResultsByIdAsBytes", + methodName: "GetResultsByIdAsBytesAsync", + pathTemplate: "$\"/v2beta/results/{id}\"", + httpMethod: "GET", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.GetResultsResponse5? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.GetResultsResponse5.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.GetResultsResponse5.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // id: the generation either does not exist or has expired. + if ((int)__response.StatusCode == 404) + { + string? __content_404 = null; + global::System.Exception? __exception_404 = null; + global::StabilityAI.GetResultsResponse6? __value_404 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_404 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_404 = global::StabilityAI.GetResultsResponse6.FromJson(__content_404, JsonSerializerContext); + } + else + { + __content_404 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_404 = global::StabilityAI.GetResultsResponse6.FromJson(__content_404, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_404 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_404 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_404, + responseBody: __content_404, + responseObject: __value_404, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.GetResultsResponse7? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.GetResultsResponse7.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.GetResultsResponse7.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessGetResultsByIdAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + } +} \ No newline at end of file diff --git a/src/libs/StabilityAI/Generated/StabilityAI.StabilityAIClient.GetStableImageUpscaleCreativeResultById.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.StabilityAIClient.GetStableImageUpscaleCreativeResultById.g.cs index d42372e..64aaeed 100644 --- a/src/libs/StabilityAI/Generated/StabilityAI.StabilityAIClient.GetStableImageUpscaleCreativeResultById.g.cs +++ b/src/libs/StabilityAI/Generated/StabilityAI.StabilityAIClient.GetStableImageUpscaleCreativeResultById.g.cs @@ -244,6 +244,10 @@ partial void ProcessGetStableImageUpscaleCreativeResultByIdResponseContent( __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || diff --git a/src/libs/StabilityAI/Generated/StabilityAI.StabilityAIClient.GetStableImageUpscaleCreativeResultByIdAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.StabilityAIClient.GetStableImageUpscaleCreativeResultByIdAsBytes.g.cs new file mode 100644 index 0000000..1b35195 --- /dev/null +++ b/src/libs/StabilityAI/Generated/StabilityAI.StabilityAIClient.GetStableImageUpscaleCreativeResultByIdAsBytes.g.cs @@ -0,0 +1,1189 @@ + +#nullable enable + +namespace StabilityAI +{ + public partial class StabilityAIClient + { + + + private static readonly global::StabilityAI.EndPointSecurityRequirement s_GetStableImageUpscaleCreativeResultByIdAsBytesSecurityRequirement0 = + new global::StabilityAI.EndPointSecurityRequirement + { + Authorizations = new global::StabilityAI.EndPointAuthorizationRequirement[] + { new global::StabilityAI.EndPointAuthorizationRequirement + { + Type = "Http", + SchemeId = "HttpBearer", + Location = "Header", + Name = "Bearer", + FriendlyName = "Bearer", + }, + }, + }; + private static readonly global::StabilityAI.EndPointSecurityRequirement[] s_GetStableImageUpscaleCreativeResultByIdAsBytesSecurityRequirements = + new global::StabilityAI.EndPointSecurityRequirement[] + { s_GetStableImageUpscaleCreativeResultByIdAsBytesSecurityRequirement0, + }; + partial void PrepareGetStableImageUpscaleCreativeResultByIdAsBytesArguments( + global::System.Net.Http.HttpClient httpClient, + ref string id, + ref global::StabilityAI.GetStableImageUpscaleCreativeResultAccept? accept, + ref string? stabilityClientId, + ref string? stabilityClientUserId, + ref string? stabilityClientVersion); + partial void PrepareGetStableImageUpscaleCreativeResultByIdAsBytesRequest( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpRequestMessage httpRequestMessage, + string id, + global::StabilityAI.GetStableImageUpscaleCreativeResultAccept? accept, + string? stabilityClientId, + string? stabilityClientUserId, + string? stabilityClientVersion); + partial void ProcessGetStableImageUpscaleCreativeResultByIdAsBytesResponse( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpResponseMessage httpResponseMessage); + + partial void ProcessGetStableImageUpscaleCreativeResultByIdAsBytesResponseContent( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpResponseMessage httpResponseMessage, + ref byte[] content); + + /// + /// Fetch Creative Upscale result
+ /// Fetch the result of an upscale generation by ID.
+ /// Make sure to use the same API key to fetch the generation result that you used to create the generation,
+ /// otherwise you will receive a `404` response.
+ /// ### How to use
+ /// Please invoke this endpoint with a `GET` request.
+ /// The headers of the request must include an API key in the `authorization` field and the ID
+ /// of your generation must be in the path.
+ /// ### How is progress reported?
+ /// Your generation is either `in-progress` (i.e. status code `202`) or it is complete (i.e. status code `200`).
+ /// We may add more fine-grained progress reporting in the future (e.g. a numerical progress).
+ /// ### How long are results stored?
+ /// Results are stored for 24 hours after generation. After that, the results are deleted. + ///
+ /// + /// The `id` of a generation, typically used for async generations, that can be used to check the status of the generation or retrieve the result.
+ /// Example: a6dc6c6e20acda010fe14d71f180658f2896ed9b4ec25aa99a6ff06c796987c4 + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// generation_id = "e52772ac75b..."
+ /// response = requests.request(
+ /// "GET",
+ /// f"https://api.stability.ai/v2beta/stable-image/upscale/creative/result/{generation_id}",
+ /// headers={
+ /// 'accept': "image/*", # Use 'application/json' to receive base64 encoded JSON
+ /// 'authorization': f"Bearer sk-MYAPIKEY"
+ /// },
+ /// )
+ /// if response.status_code == 202:
+ /// print("Generation in-progress, try again in 10 seconds.")
+ /// elif response.status_code == 200:
+ /// print("Generation complete!")
+ /// with open("upscaled.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task GetStableImageUpscaleCreativeResultByIdAsBytesAsync( + string id, + global::StabilityAI.GetStableImageUpscaleCreativeResultAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + var __response = await GetStableImageUpscaleCreativeResultByIdAsBytesAsResponseAsync( + id: id, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + requestOptions: requestOptions, + cancellationToken: cancellationToken + ).ConfigureAwait(false); + + return __response.Body; + } + /// + /// Fetch Creative Upscale result
+ /// Fetch the result of an upscale generation by ID.
+ /// Make sure to use the same API key to fetch the generation result that you used to create the generation,
+ /// otherwise you will receive a `404` response.
+ /// ### How to use
+ /// Please invoke this endpoint with a `GET` request.
+ /// The headers of the request must include an API key in the `authorization` field and the ID
+ /// of your generation must be in the path.
+ /// ### How is progress reported?
+ /// Your generation is either `in-progress` (i.e. status code `202`) or it is complete (i.e. status code `200`).
+ /// We may add more fine-grained progress reporting in the future (e.g. a numerical progress).
+ /// ### How long are results stored?
+ /// Results are stored for 24 hours after generation. After that, the results are deleted. + ///
+ /// + /// The `id` of a generation, typically used for async generations, that can be used to check the status of the generation or retrieve the result.
+ /// Example: a6dc6c6e20acda010fe14d71f180658f2896ed9b4ec25aa99a6ff06c796987c4 + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// generation_id = "e52772ac75b..."
+ /// response = requests.request(
+ /// "GET",
+ /// f"https://api.stability.ai/v2beta/stable-image/upscale/creative/result/{generation_id}",
+ /// headers={
+ /// 'accept': "image/*", # Use 'application/json' to receive base64 encoded JSON
+ /// 'authorization': f"Bearer sk-MYAPIKEY"
+ /// },
+ /// )
+ /// if response.status_code == 202:
+ /// print("Generation in-progress, try again in 10 seconds.")
+ /// elif response.status_code == 200:
+ /// print("Generation complete!")
+ /// with open("upscaled.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task GetStableImageUpscaleCreativeResultByIdAsBytesAsStreamAsync( + string id, + global::StabilityAI.GetStableImageUpscaleCreativeResultAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + PrepareArguments( + client: HttpClient); + PrepareGetStableImageUpscaleCreativeResultByIdAsBytesArguments( + httpClient: HttpClient, + id: ref id, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_GetStableImageUpscaleCreativeResultByIdAsBytesSecurityRequirements, + operationName: "GetStableImageUpscaleCreativeResultByIdAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: true); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: $"/v2beta/stable-image/upscale/creative/result/{id}", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Get, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/jpeg"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareGetStableImageUpscaleCreativeResultByIdAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + id: id!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "getStableImageUpscaleCreativeResultByIdAsBytes", + methodName: "GetStableImageUpscaleCreativeResultByIdAsBytesAsync", + pathTemplate: "$\"/v2beta/stable-image/upscale/creative/result/{id}\"", + httpMethod: "GET", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseHeadersRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "getStableImageUpscaleCreativeResultByIdAsBytes", + methodName: "GetStableImageUpscaleCreativeResultByIdAsBytesAsync", + pathTemplate: "$\"/v2beta/stable-image/upscale/creative/result/{id}\"", + httpMethod: "GET", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "getStableImageUpscaleCreativeResultByIdAsBytes", + methodName: "GetStableImageUpscaleCreativeResultByIdAsBytesAsync", + pathTemplate: "$\"/v2beta/stable-image/upscale/creative/result/{id}\"", + httpMethod: "GET", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + try + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessGetStableImageUpscaleCreativeResultByIdAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "getStableImageUpscaleCreativeResultByIdAsBytes", + methodName: "GetStableImageUpscaleCreativeResultByIdAsBytesAsync", + pathTemplate: "$\"/v2beta/stable-image/upscale/creative/result/{id}\"", + httpMethod: "GET", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "getStableImageUpscaleCreativeResultByIdAsBytes", + methodName: "GetStableImageUpscaleCreativeResultByIdAsBytesAsync", + pathTemplate: "$\"/v2beta/stable-image/upscale/creative/result/{id}\"", + httpMethod: "GET", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.GetStableImageUpscaleCreativeResultResponse5? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.GetStableImageUpscaleCreativeResultResponse5.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.GetStableImageUpscaleCreativeResultResponse5.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // id: the generation either does not exist or has expired. + if ((int)__response.StatusCode == 404) + { + string? __content_404 = null; + global::System.Exception? __exception_404 = null; + global::StabilityAI.GetStableImageUpscaleCreativeResultResponse6? __value_404 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_404 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_404 = global::StabilityAI.GetStableImageUpscaleCreativeResultResponse6.FromJson(__content_404, JsonSerializerContext); + } + else + { + __content_404 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_404 = global::StabilityAI.GetStableImageUpscaleCreativeResultResponse6.FromJson(__content_404, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_404 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_404 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_404, + responseBody: __content_404, + responseObject: __value_404, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.GetStableImageUpscaleCreativeResultResponse7? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.GetStableImageUpscaleCreativeResultResponse7.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.GetStableImageUpscaleCreativeResultResponse7.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + try + { + __response.EnsureSuccessStatusCode(); + + var __content = await __response.Content.ReadAsStreamAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.ResponseStream(__response, __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + } + catch + { + __response.Dispose(); + throw; + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Fetch Creative Upscale result
+ /// Fetch the result of an upscale generation by ID.
+ /// Make sure to use the same API key to fetch the generation result that you used to create the generation,
+ /// otherwise you will receive a `404` response.
+ /// ### How to use
+ /// Please invoke this endpoint with a `GET` request.
+ /// The headers of the request must include an API key in the `authorization` field and the ID
+ /// of your generation must be in the path.
+ /// ### How is progress reported?
+ /// Your generation is either `in-progress` (i.e. status code `202`) or it is complete (i.e. status code `200`).
+ /// We may add more fine-grained progress reporting in the future (e.g. a numerical progress).
+ /// ### How long are results stored?
+ /// Results are stored for 24 hours after generation. After that, the results are deleted. + ///
+ /// + /// The `id` of a generation, typically used for async generations, that can be used to check the status of the generation or retrieve the result.
+ /// Example: a6dc6c6e20acda010fe14d71f180658f2896ed9b4ec25aa99a6ff06c796987c4 + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// generation_id = "e52772ac75b..."
+ /// response = requests.request(
+ /// "GET",
+ /// f"https://api.stability.ai/v2beta/stable-image/upscale/creative/result/{generation_id}",
+ /// headers={
+ /// 'accept': "image/*", # Use 'application/json' to receive base64 encoded JSON
+ /// 'authorization': f"Bearer sk-MYAPIKEY"
+ /// },
+ /// )
+ /// if response.status_code == 202:
+ /// print("Generation in-progress, try again in 10 seconds.")
+ /// elif response.status_code == 200:
+ /// print("Generation complete!")
+ /// with open("upscaled.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task> GetStableImageUpscaleCreativeResultByIdAsBytesAsResponseAsync( + string id, + global::StabilityAI.GetStableImageUpscaleCreativeResultAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + PrepareArguments( + client: HttpClient); + PrepareGetStableImageUpscaleCreativeResultByIdAsBytesArguments( + httpClient: HttpClient, + id: ref id, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_GetStableImageUpscaleCreativeResultByIdAsBytesSecurityRequirements, + operationName: "GetStableImageUpscaleCreativeResultByIdAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: true); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: $"/v2beta/stable-image/upscale/creative/result/{id}", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Get, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/jpeg"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareGetStableImageUpscaleCreativeResultByIdAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + id: id!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "getStableImageUpscaleCreativeResultByIdAsBytes", + methodName: "GetStableImageUpscaleCreativeResultByIdAsBytesAsync", + pathTemplate: "$\"/v2beta/stable-image/upscale/creative/result/{id}\"", + httpMethod: "GET", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "getStableImageUpscaleCreativeResultByIdAsBytes", + methodName: "GetStableImageUpscaleCreativeResultByIdAsBytesAsync", + pathTemplate: "$\"/v2beta/stable-image/upscale/creative/result/{id}\"", + httpMethod: "GET", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "getStableImageUpscaleCreativeResultByIdAsBytes", + methodName: "GetStableImageUpscaleCreativeResultByIdAsBytesAsync", + pathTemplate: "$\"/v2beta/stable-image/upscale/creative/result/{id}\"", + httpMethod: "GET", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessGetStableImageUpscaleCreativeResultByIdAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "getStableImageUpscaleCreativeResultByIdAsBytes", + methodName: "GetStableImageUpscaleCreativeResultByIdAsBytesAsync", + pathTemplate: "$\"/v2beta/stable-image/upscale/creative/result/{id}\"", + httpMethod: "GET", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "getStableImageUpscaleCreativeResultByIdAsBytes", + methodName: "GetStableImageUpscaleCreativeResultByIdAsBytesAsync", + pathTemplate: "$\"/v2beta/stable-image/upscale/creative/result/{id}\"", + httpMethod: "GET", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.GetStableImageUpscaleCreativeResultResponse5? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.GetStableImageUpscaleCreativeResultResponse5.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.GetStableImageUpscaleCreativeResultResponse5.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // id: the generation either does not exist or has expired. + if ((int)__response.StatusCode == 404) + { + string? __content_404 = null; + global::System.Exception? __exception_404 = null; + global::StabilityAI.GetStableImageUpscaleCreativeResultResponse6? __value_404 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_404 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_404 = global::StabilityAI.GetStableImageUpscaleCreativeResultResponse6.FromJson(__content_404, JsonSerializerContext); + } + else + { + __content_404 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_404 = global::StabilityAI.GetStableImageUpscaleCreativeResultResponse6.FromJson(__content_404, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_404 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_404 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_404, + responseBody: __content_404, + responseObject: __value_404, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.GetStableImageUpscaleCreativeResultResponse7? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.GetStableImageUpscaleCreativeResultResponse7.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.GetStableImageUpscaleCreativeResultResponse7.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessGetStableImageUpscaleCreativeResultByIdAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + } +} \ No newline at end of file diff --git a/src/libs/StabilityAI/Generated/StabilityAI.StableAudio2Client.CreateAudioStableAudio2AudioToAudio.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.StableAudio2Client.CreateAudioStableAudio2AudioToAudio.g.cs index ac092fe..198a9e1 100644 --- a/src/libs/StabilityAI/Generated/StabilityAI.StableAudio2Client.CreateAudioStableAudio2AudioToAudio.g.cs +++ b/src/libs/StabilityAI/Generated/StabilityAI.StableAudio2Client.CreateAudioStableAudio2AudioToAudio.g.cs @@ -317,6 +317,10 @@ partial void ProcessCreateAudioStableAudio2AudioToAudioResponseContent( __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || @@ -354,42 +358,6 @@ partial void ProcessCreateAudioStableAudio2AudioToAudioResponseContent( var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"accept\""); - - } - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } __httpRequestContent.Add( content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), name: "\"prompt\""); @@ -1372,6 +1340,10 @@ request.Audioname is null __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || @@ -1409,42 +1381,6 @@ request.Audioname is null var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"accept\""); - - } - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } __httpRequestContent.Add( content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), name: "\"prompt\""); @@ -2247,6 +2183,10 @@ request.Audioname is null __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || @@ -2284,42 +2224,6 @@ request.Audioname is null var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"accept\""); - - } - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } __httpRequestContent.Add( content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), name: "\"prompt\""); diff --git a/src/libs/StabilityAI/Generated/StabilityAI.StableAudio2Client.CreateAudioStableAudio2AudioToAudioAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.StableAudio2Client.CreateAudioStableAudio2AudioToAudioAsBytes.g.cs new file mode 100644 index 0000000..1871209 --- /dev/null +++ b/src/libs/StabilityAI/Generated/StabilityAI.StableAudio2Client.CreateAudioStableAudio2AudioToAudioAsBytes.g.cs @@ -0,0 +1,4312 @@ + +#nullable enable + +namespace StabilityAI +{ + public partial class StableAudio2Client + { + + + private static readonly global::StabilityAI.EndPointSecurityRequirement s_CreateAudioStableAudio2AudioToAudioAsBytesSecurityRequirement0 = + new global::StabilityAI.EndPointSecurityRequirement + { + Authorizations = new global::StabilityAI.EndPointAuthorizationRequirement[] + { new global::StabilityAI.EndPointAuthorizationRequirement + { + Type = "Http", + SchemeId = "HttpBearer", + Location = "Header", + Name = "Bearer", + FriendlyName = "Bearer", + }, + }, + }; + private static readonly global::StabilityAI.EndPointSecurityRequirement[] s_CreateAudioStableAudio2AudioToAudioAsBytesSecurityRequirements = + new global::StabilityAI.EndPointSecurityRequirement[] + { s_CreateAudioStableAudio2AudioToAudioAsBytesSecurityRequirement0, + }; + partial void PrepareCreateAudioStableAudio2AudioToAudioAsBytesArguments( + global::System.Net.Http.HttpClient httpClient, + ref string contentType, + ref global::StabilityAI.CreateAudioStableAudio2AudioToAudioAccept? accept, + ref string? stabilityClientId, + ref string? stabilityClientUserId, + ref string? stabilityClientVersion, + global::StabilityAI.CreateAudioStableAudio2AudioToAudioRequest request); + partial void PrepareCreateAudioStableAudio2AudioToAudioAsBytesRequest( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpRequestMessage httpRequestMessage, + string contentType, + global::StabilityAI.CreateAudioStableAudio2AudioToAudioAccept? accept, + string? stabilityClientId, + string? stabilityClientUserId, + string? stabilityClientVersion, + global::StabilityAI.CreateAudioStableAudio2AudioToAudioRequest request); + partial void ProcessCreateAudioStableAudio2AudioToAudioAsBytesResponse( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpResponseMessage httpResponseMessage); + + partial void ProcessCreateAudioStableAudio2AudioToAudioAsBytesResponseContent( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpResponseMessage httpResponseMessage, + ref byte[] content); + + /// + /// Audio-to-Audio
+ /// Stable Audio transforms existing audio samples into new high-quality compositions up to three minutes
+ /// long at 44.1kHz stereo using text instructions. Discover techniques for sample transformation in our
+ /// [Audio to Audio Guide](https://www.stableaudio.com/user-guide/audio-to-audio) to maximize creative control.
+ /// Read more about the model capabilities [here](https://stability.ai/news/stable-audio-2-0).
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to
+ /// [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Audio_API.ipynb)
+ /// or try Stable Audio 2.0 for free at [stableaudio.com](https://stableaudio.com).
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`. The `accept` header should be set to one of the following:
+ /// - `audio/*` to receive the audio in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the audio encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `prompt` - text to generate the audio from. Check our
+ /// [prompt guide](https://www.stableaudio.com/user-guide/audio-to-audio) for tips
+ /// - `audio` - the audio to use as the starting point for the generation
+ /// > **Notes:**
+ /// > - We do not allow copyrighted content to be uploaded to our platform.
+ /// > - Maximum request size is 50Mb.
+ /// #### **Optional Parameters:**
+ /// The body may optionally include:
+ /// - `output_format` - the format of the output audio
+ /// - `seed` - the randomness seed to use for the generation
+ /// - `steps` - the number of sampling steps
+ /// - `duration` - the number of seconds of the generated audio
+ /// - `cfg_scale` - controls how strictly the diffusion process adheres to the prompt text (only for `stable-audio-2`)
+ /// - `model` - the model to use [`stable-audio-2`, `stable-audio-2.5`]
+ /// - `strength` - controls how much influence the `audio` parameter has on the output audio
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// **Stable Audio 2.0**
+ /// By default, 20 credits per successful generation. The number of credits is determined
+ /// by the following formula: `credits = 17 + 0.06 * steps`.
+ /// Examples:
+ /// - 50 steps = 20 credits [default]
+ /// - 100 steps = 23 credits
+ /// **Stable Audio 2.5**
+ /// Requests made using the Stable Audio 2.5 model have a flat rate of 20 credits per successful result.
+ /// As always, you will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `audio/*` to receive the bytes of the audio directly. Otherwise specify `application/json` to receive the audio as base64 encoded JSON.
+ /// Default Value: audio/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/audio/stable-audio-2/audio-to-audio",
+ /// headers={"authorization": f"Bearer sk-MYAPIKEY", "accept": "audio/*"},
+ /// files={
+ /// "audio": open("./uk-bass-base.mp3", "rb"),
+ /// },
+ /// data={
+ /// "prompt": "A song in the 3/4 time signature that features cheerful acoustic guitar, live recorded drums, and rhythmic claps, The mood is happy and up-lifting.",
+ /// "output_format": "mp3",
+ /// "duration": 20,
+ /// "model": "stable-audio-2.5",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./output.mp3", "wb") as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateAudioStableAudio2AudioToAudioAsBytesAsync( + string contentType, + + global::StabilityAI.CreateAudioStableAudio2AudioToAudioRequest request, + global::StabilityAI.CreateAudioStableAudio2AudioToAudioAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + var __response = await CreateAudioStableAudio2AudioToAudioAsBytesAsResponseAsync( + contentType: contentType, + + request: request, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + requestOptions: requestOptions, + cancellationToken: cancellationToken + ).ConfigureAwait(false); + + return __response.Body; + } + /// + /// Audio-to-Audio
+ /// Stable Audio transforms existing audio samples into new high-quality compositions up to three minutes
+ /// long at 44.1kHz stereo using text instructions. Discover techniques for sample transformation in our
+ /// [Audio to Audio Guide](https://www.stableaudio.com/user-guide/audio-to-audio) to maximize creative control.
+ /// Read more about the model capabilities [here](https://stability.ai/news/stable-audio-2-0).
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to
+ /// [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Audio_API.ipynb)
+ /// or try Stable Audio 2.0 for free at [stableaudio.com](https://stableaudio.com).
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`. The `accept` header should be set to one of the following:
+ /// - `audio/*` to receive the audio in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the audio encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `prompt` - text to generate the audio from. Check our
+ /// [prompt guide](https://www.stableaudio.com/user-guide/audio-to-audio) for tips
+ /// - `audio` - the audio to use as the starting point for the generation
+ /// > **Notes:**
+ /// > - We do not allow copyrighted content to be uploaded to our platform.
+ /// > - Maximum request size is 50Mb.
+ /// #### **Optional Parameters:**
+ /// The body may optionally include:
+ /// - `output_format` - the format of the output audio
+ /// - `seed` - the randomness seed to use for the generation
+ /// - `steps` - the number of sampling steps
+ /// - `duration` - the number of seconds of the generated audio
+ /// - `cfg_scale` - controls how strictly the diffusion process adheres to the prompt text (only for `stable-audio-2`)
+ /// - `model` - the model to use [`stable-audio-2`, `stable-audio-2.5`]
+ /// - `strength` - controls how much influence the `audio` parameter has on the output audio
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// **Stable Audio 2.0**
+ /// By default, 20 credits per successful generation. The number of credits is determined
+ /// by the following formula: `credits = 17 + 0.06 * steps`.
+ /// Examples:
+ /// - 50 steps = 20 credits [default]
+ /// - 100 steps = 23 credits
+ /// **Stable Audio 2.5**
+ /// Requests made using the Stable Audio 2.5 model have a flat rate of 20 credits per successful result.
+ /// As always, you will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `audio/*` to receive the bytes of the audio directly. Otherwise specify `application/json` to receive the audio as base64 encoded JSON.
+ /// Default Value: audio/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/audio/stable-audio-2/audio-to-audio",
+ /// headers={"authorization": f"Bearer sk-MYAPIKEY", "accept": "audio/*"},
+ /// files={
+ /// "audio": open("./uk-bass-base.mp3", "rb"),
+ /// },
+ /// data={
+ /// "prompt": "A song in the 3/4 time signature that features cheerful acoustic guitar, live recorded drums, and rhythmic claps, The mood is happy and up-lifting.",
+ /// "output_format": "mp3",
+ /// "duration": 20,
+ /// "model": "stable-audio-2.5",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./output.mp3", "wb") as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateAudioStableAudio2AudioToAudioAsBytesAsStreamAsync( + string contentType, + + global::StabilityAI.CreateAudioStableAudio2AudioToAudioRequest request, + global::StabilityAI.CreateAudioStableAudio2AudioToAudioAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + request = request ?? throw new global::System.ArgumentNullException(nameof(request)); + + PrepareArguments( + client: HttpClient); + PrepareCreateAudioStableAudio2AudioToAudioAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateAudioStableAudio2AudioToAudioAsBytesSecurityRequirements, + operationName: "CreateAudioStableAudio2AudioToAudioAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/audio/stable-audio-2/audio-to-audio", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "audio/mpeg"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + if (request.Duration != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Duration, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"duration\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.Steps != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Steps, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"steps\""); + + } + if (request.CfgScale != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.CfgScale, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"cfg_scale\""); + + } + if (request.Model != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.Model).HasValue ? (request.Model).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"model\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + var __contentAudio = new global::System.Net.Http.ByteArrayContent(request.Audio ?? global::System.Array.Empty()); + __contentAudio.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Audioname is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Audioname) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentAudio, + name: "\"audio\"", + fileName: request.Audioname != null ? $"\"{request.Audioname}\"" : string.Empty); + if (__contentAudio.Headers.ContentDisposition != null) + { + __contentAudio.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.Strength != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Strength, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"strength\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateAudioStableAudio2AudioToAudioAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2AudioToAudioAsBytes", + methodName: "CreateAudioStableAudio2AudioToAudioAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/audio-to-audio\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseHeadersRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2AudioToAudioAsBytes", + methodName: "CreateAudioStableAudio2AudioToAudioAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/audio-to-audio\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2AudioToAudioAsBytes", + methodName: "CreateAudioStableAudio2AudioToAudioAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/audio-to-audio\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + try + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateAudioStableAudio2AudioToAudioAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2AudioToAudioAsBytes", + methodName: "CreateAudioStableAudio2AudioToAudioAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/audio-to-audio\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2AudioToAudioAsBytes", + methodName: "CreateAudioStableAudio2AudioToAudioAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/audio-to-audio\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse3? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse3.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse3.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse4? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse4.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse4.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse5? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse5.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse5.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse6? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse6.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse6.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + try + { + __response.EnsureSuccessStatusCode(); + + var __content = await __response.Content.ReadAsStreamAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.ResponseStream(__response, __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + } + catch + { + __response.Dispose(); + throw; + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Audio-to-Audio
+ /// Stable Audio transforms existing audio samples into new high-quality compositions up to three minutes
+ /// long at 44.1kHz stereo using text instructions. Discover techniques for sample transformation in our
+ /// [Audio to Audio Guide](https://www.stableaudio.com/user-guide/audio-to-audio) to maximize creative control.
+ /// Read more about the model capabilities [here](https://stability.ai/news/stable-audio-2-0).
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to
+ /// [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Audio_API.ipynb)
+ /// or try Stable Audio 2.0 for free at [stableaudio.com](https://stableaudio.com).
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`. The `accept` header should be set to one of the following:
+ /// - `audio/*` to receive the audio in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the audio encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `prompt` - text to generate the audio from. Check our
+ /// [prompt guide](https://www.stableaudio.com/user-guide/audio-to-audio) for tips
+ /// - `audio` - the audio to use as the starting point for the generation
+ /// > **Notes:**
+ /// > - We do not allow copyrighted content to be uploaded to our platform.
+ /// > - Maximum request size is 50Mb.
+ /// #### **Optional Parameters:**
+ /// The body may optionally include:
+ /// - `output_format` - the format of the output audio
+ /// - `seed` - the randomness seed to use for the generation
+ /// - `steps` - the number of sampling steps
+ /// - `duration` - the number of seconds of the generated audio
+ /// - `cfg_scale` - controls how strictly the diffusion process adheres to the prompt text (only for `stable-audio-2`)
+ /// - `model` - the model to use [`stable-audio-2`, `stable-audio-2.5`]
+ /// - `strength` - controls how much influence the `audio` parameter has on the output audio
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// **Stable Audio 2.0**
+ /// By default, 20 credits per successful generation. The number of credits is determined
+ /// by the following formula: `credits = 17 + 0.06 * steps`.
+ /// Examples:
+ /// - 50 steps = 20 credits [default]
+ /// - 100 steps = 23 credits
+ /// **Stable Audio 2.5**
+ /// Requests made using the Stable Audio 2.5 model have a flat rate of 20 credits per successful result.
+ /// As always, you will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `audio/*` to receive the bytes of the audio directly. Otherwise specify `application/json` to receive the audio as base64 encoded JSON.
+ /// Default Value: audio/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/audio/stable-audio-2/audio-to-audio",
+ /// headers={"authorization": f"Bearer sk-MYAPIKEY", "accept": "audio/*"},
+ /// files={
+ /// "audio": open("./uk-bass-base.mp3", "rb"),
+ /// },
+ /// data={
+ /// "prompt": "A song in the 3/4 time signature that features cheerful acoustic guitar, live recorded drums, and rhythmic claps, The mood is happy and up-lifting.",
+ /// "output_format": "mp3",
+ /// "duration": 20,
+ /// "model": "stable-audio-2.5",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./output.mp3", "wb") as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task> CreateAudioStableAudio2AudioToAudioAsBytesAsResponseAsync( + string contentType, + + global::StabilityAI.CreateAudioStableAudio2AudioToAudioRequest request, + global::StabilityAI.CreateAudioStableAudio2AudioToAudioAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + request = request ?? throw new global::System.ArgumentNullException(nameof(request)); + + PrepareArguments( + client: HttpClient); + PrepareCreateAudioStableAudio2AudioToAudioAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateAudioStableAudio2AudioToAudioAsBytesSecurityRequirements, + operationName: "CreateAudioStableAudio2AudioToAudioAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/audio/stable-audio-2/audio-to-audio", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "audio/mpeg"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + if (request.Duration != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Duration, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"duration\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.Steps != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Steps, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"steps\""); + + } + if (request.CfgScale != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.CfgScale, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"cfg_scale\""); + + } + if (request.Model != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.Model).HasValue ? (request.Model).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"model\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + var __contentAudio = new global::System.Net.Http.ByteArrayContent(request.Audio ?? global::System.Array.Empty()); + __contentAudio.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Audioname is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Audioname) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentAudio, + name: "\"audio\"", + fileName: request.Audioname != null ? $"\"{request.Audioname}\"" : string.Empty); + if (__contentAudio.Headers.ContentDisposition != null) + { + __contentAudio.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.Strength != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Strength, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"strength\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateAudioStableAudio2AudioToAudioAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2AudioToAudioAsBytes", + methodName: "CreateAudioStableAudio2AudioToAudioAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/audio-to-audio\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2AudioToAudioAsBytes", + methodName: "CreateAudioStableAudio2AudioToAudioAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/audio-to-audio\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2AudioToAudioAsBytes", + methodName: "CreateAudioStableAudio2AudioToAudioAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/audio-to-audio\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateAudioStableAudio2AudioToAudioAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2AudioToAudioAsBytes", + methodName: "CreateAudioStableAudio2AudioToAudioAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/audio-to-audio\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2AudioToAudioAsBytes", + methodName: "CreateAudioStableAudio2AudioToAudioAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/audio-to-audio\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse3? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse3.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse3.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse4? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse4.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse4.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse5? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse5.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse5.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse6? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse6.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse6.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessCreateAudioStableAudio2AudioToAudioAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Audio-to-Audio
+ /// Stable Audio transforms existing audio samples into new high-quality compositions up to three minutes
+ /// long at 44.1kHz stereo using text instructions. Discover techniques for sample transformation in our
+ /// [Audio to Audio Guide](https://www.stableaudio.com/user-guide/audio-to-audio) to maximize creative control.
+ /// Read more about the model capabilities [here](https://stability.ai/news/stable-audio-2-0).
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to
+ /// [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Audio_API.ipynb)
+ /// or try Stable Audio 2.0 for free at [stableaudio.com](https://stableaudio.com).
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`. The `accept` header should be set to one of the following:
+ /// - `audio/*` to receive the audio in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the audio encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `prompt` - text to generate the audio from. Check our
+ /// [prompt guide](https://www.stableaudio.com/user-guide/audio-to-audio) for tips
+ /// - `audio` - the audio to use as the starting point for the generation
+ /// > **Notes:**
+ /// > - We do not allow copyrighted content to be uploaded to our platform.
+ /// > - Maximum request size is 50Mb.
+ /// #### **Optional Parameters:**
+ /// The body may optionally include:
+ /// - `output_format` - the format of the output audio
+ /// - `seed` - the randomness seed to use for the generation
+ /// - `steps` - the number of sampling steps
+ /// - `duration` - the number of seconds of the generated audio
+ /// - `cfg_scale` - controls how strictly the diffusion process adheres to the prompt text (only for `stable-audio-2`)
+ /// - `model` - the model to use [`stable-audio-2`, `stable-audio-2.5`]
+ /// - `strength` - controls how much influence the `audio` parameter has on the output audio
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// **Stable Audio 2.0**
+ /// By default, 20 credits per successful generation. The number of credits is determined
+ /// by the following formula: `credits = 17 + 0.06 * steps`.
+ /// Examples:
+ /// - 50 steps = 20 credits [default]
+ /// - 100 steps = 23 credits
+ /// **Stable Audio 2.5**
+ /// Requests made using the Stable Audio 2.5 model have a flat rate of 20 credits per successful result.
+ /// As always, you will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `audio/*` to receive the bytes of the audio directly. Otherwise specify `application/json` to receive the audio as base64 encoded JSON.
+ /// Default Value: audio/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// What you wish the output audio to be. A strong, descriptive prompt that clearly defines
+ /// instruments, moods, styles, and genre will lead to better results.
+ /// You can make a prompt as simple or complex as you like. Simple prompts are good for clean
+ /// output audio. Complex prompts are good for adding texture and depth to the output audio.
+ /// Check our [prompt guide](https://www.stableaudio.com/user-guide/audio-to-audio) for tips. + /// + /// + /// Controls the duration in seconds of the generated audio.
+ /// Default Value: 190 + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Controls the number of sampling steps.
+ /// - For `stable-audio-2`: accepts steps between `30` and `100` (defaults to `50`).
+ /// - For `stable-audio-2.5`: accepts steps between `4` and `8` (defaults to `8`). + /// + /// + /// How strictly the diffusion process adheres to the prompt text (higher values make your
+ /// audio closer to your prompt).
+ /// Defaults to 7 for `stable-audio-2` and 1 for `stable-audio-2.5` if not specified. + /// + /// + /// The model to use for generation.
+ /// - `stable-audio-2.5` requires 20 credits per generation
+ /// - `stable-audio-2` requires 20 credits per generation
+ /// Default Value: stable-audio-2 + /// + /// + /// Dictates the `content-type` of the generated audio.
+ /// Default Value: mp3 + /// + /// + /// The audio to be use as the starting point for the generation.
+ /// Supported Formats:
+ /// - mp3
+ /// - wav
+ /// Validation Rule:
+ /// - Audio must be between 6 and 190 seconds long
+ /// Example: ./some/audio.mp3 + /// + /// + /// The audio to be use as the starting point for the generation.
+ /// Supported Formats:
+ /// - mp3
+ /// - wav
+ /// Validation Rule:
+ /// - Audio must be between 6 and 190 seconds long
+ /// Example: ./some/audio.mp3 + /// + /// + /// Sometimes referred to as _denoising_, this parameter controls how much influence the
+ /// `audio` parameter has on the generated audio.
+ /// A value of 0 would yield audio that is identical to the input.
+ /// A value of 1 would be as if you passed in no audio at all.
+ /// Minimum value for `stable-audio-2.5` is 0.01.
+ /// Default Value: 1 + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + public async global::System.Threading.Tasks.Task CreateAudioStableAudio2AudioToAudioAsBytesAsync( + string contentType, + string prompt, + byte[] audio, + string audioname, + global::StabilityAI.CreateAudioStableAudio2AudioToAudioAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + double? duration = default, + double? seed = default, + int? steps = default, + double? cfgScale = default, + global::StabilityAI.CreateAudioStableAudio2AudioToAudioRequestModel? model = default, + global::StabilityAI.CreateAudioStableAudio2AudioToAudioRequestOutputFormat? outputFormat = default, + double? strength = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + var __request = new global::StabilityAI.CreateAudioStableAudio2AudioToAudioRequest + { + Prompt = prompt, + Duration = duration, + Seed = seed, + Steps = steps, + CfgScale = cfgScale, + Model = model, + OutputFormat = outputFormat, + Audio = audio, + Audioname = audioname, + Strength = strength, + }; + + return await CreateAudioStableAudio2AudioToAudioAsBytesAsync( + contentType: contentType, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: __request, + requestOptions: requestOptions, + cancellationToken: cancellationToken).ConfigureAwait(false); + } + + /// + /// Audio-to-Audio
+ /// Stable Audio transforms existing audio samples into new high-quality compositions up to three minutes
+ /// long at 44.1kHz stereo using text instructions. Discover techniques for sample transformation in our
+ /// [Audio to Audio Guide](https://www.stableaudio.com/user-guide/audio-to-audio) to maximize creative control.
+ /// Read more about the model capabilities [here](https://stability.ai/news/stable-audio-2-0).
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to
+ /// [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Audio_API.ipynb)
+ /// or try Stable Audio 2.0 for free at [stableaudio.com](https://stableaudio.com).
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`. The `accept` header should be set to one of the following:
+ /// - `audio/*` to receive the audio in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the audio encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `prompt` - text to generate the audio from. Check our
+ /// [prompt guide](https://www.stableaudio.com/user-guide/audio-to-audio) for tips
+ /// - `audio` - the audio to use as the starting point for the generation
+ /// > **Notes:**
+ /// > - We do not allow copyrighted content to be uploaded to our platform.
+ /// > - Maximum request size is 50Mb.
+ /// #### **Optional Parameters:**
+ /// The body may optionally include:
+ /// - `output_format` - the format of the output audio
+ /// - `seed` - the randomness seed to use for the generation
+ /// - `steps` - the number of sampling steps
+ /// - `duration` - the number of seconds of the generated audio
+ /// - `cfg_scale` - controls how strictly the diffusion process adheres to the prompt text (only for `stable-audio-2`)
+ /// - `model` - the model to use [`stable-audio-2`, `stable-audio-2.5`]
+ /// - `strength` - controls how much influence the `audio` parameter has on the output audio
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// **Stable Audio 2.0**
+ /// By default, 20 credits per successful generation. The number of credits is determined
+ /// by the following formula: `credits = 17 + 0.06 * steps`.
+ /// Examples:
+ /// - 50 steps = 20 credits [default]
+ /// - 100 steps = 23 credits
+ /// **Stable Audio 2.5**
+ /// Requests made using the Stable Audio 2.5 model have a flat rate of 20 credits per successful result.
+ /// As always, you will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `audio/*` to receive the bytes of the audio directly. Otherwise specify `application/json` to receive the audio as base64 encoded JSON.
+ /// Default Value: audio/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// What you wish the output audio to be. A strong, descriptive prompt that clearly defines
+ /// instruments, moods, styles, and genre will lead to better results.
+ /// You can make a prompt as simple or complex as you like. Simple prompts are good for clean
+ /// output audio. Complex prompts are good for adding texture and depth to the output audio.
+ /// Check our [prompt guide](https://www.stableaudio.com/user-guide/audio-to-audio) for tips. + /// + /// + /// Controls the duration in seconds of the generated audio.
+ /// Default Value: 190 + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Controls the number of sampling steps.
+ /// - For `stable-audio-2`: accepts steps between `30` and `100` (defaults to `50`).
+ /// - For `stable-audio-2.5`: accepts steps between `4` and `8` (defaults to `8`). + /// + /// + /// How strictly the diffusion process adheres to the prompt text (higher values make your
+ /// audio closer to your prompt).
+ /// Defaults to 7 for `stable-audio-2` and 1 for `stable-audio-2.5` if not specified. + /// + /// + /// The model to use for generation.
+ /// - `stable-audio-2.5` requires 20 credits per generation
+ /// - `stable-audio-2` requires 20 credits per generation
+ /// Default Value: stable-audio-2 + /// + /// + /// Dictates the `content-type` of the generated audio.
+ /// Default Value: mp3 + /// + /// + /// The audio to be use as the starting point for the generation.
+ /// Supported Formats:
+ /// - mp3
+ /// - wav
+ /// Validation Rule:
+ /// - Audio must be between 6 and 190 seconds long
+ /// Example: ./some/audio.mp3 + /// + /// + /// The audio to be use as the starting point for the generation.
+ /// Supported Formats:
+ /// - mp3
+ /// - wav
+ /// Validation Rule:
+ /// - Audio must be between 6 and 190 seconds long
+ /// Example: ./some/audio.mp3 + /// + /// + /// Sometimes referred to as _denoising_, this parameter controls how much influence the
+ /// `audio` parameter has on the generated audio.
+ /// A value of 0 would yield audio that is identical to the input.
+ /// A value of 1 would be as if you passed in no audio at all.
+ /// Minimum value for `stable-audio-2.5` is 0.01.
+ /// Default Value: 1 + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/audio/stable-audio-2/audio-to-audio",
+ /// headers={"authorization": f"Bearer sk-MYAPIKEY", "accept": "audio/*"},
+ /// files={
+ /// "audio": open("./uk-bass-base.mp3", "rb"),
+ /// },
+ /// data={
+ /// "prompt": "A song in the 3/4 time signature that features cheerful acoustic guitar, live recorded drums, and rhythmic claps, The mood is happy and up-lifting.",
+ /// "output_format": "mp3",
+ /// "duration": 20,
+ /// "model": "stable-audio-2.5",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./output.mp3", "wb") as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateAudioStableAudio2AudioToAudioAsBytesAsync( + string contentType, + string prompt, + global::System.IO.Stream audio, + string audioname, + global::StabilityAI.CreateAudioStableAudio2AudioToAudioAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + double? duration = default, + double? seed = default, + int? steps = default, + double? cfgScale = default, + global::StabilityAI.CreateAudioStableAudio2AudioToAudioRequestModel? model = default, + global::StabilityAI.CreateAudioStableAudio2AudioToAudioRequestOutputFormat? outputFormat = default, + double? strength = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + + audio = audio ?? throw new global::System.ArgumentNullException(nameof(audio)); + var request = new global::StabilityAI.CreateAudioStableAudio2AudioToAudioRequest + { + Prompt = prompt, + Duration = duration, + Seed = seed, + Steps = steps, + CfgScale = cfgScale, + Model = model, + OutputFormat = outputFormat, + Audio = global::System.Array.Empty(), + Audioname = audioname, + Strength = strength, + }; + PrepareArguments( + client: HttpClient); + PrepareCreateAudioStableAudio2AudioToAudioAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateAudioStableAudio2AudioToAudioAsBytesSecurityRequirements, + operationName: "CreateAudioStableAudio2AudioToAudioAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/audio/stable-audio-2/audio-to-audio", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "audio/mpeg"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + if (request.Duration != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Duration, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"duration\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.Steps != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Steps, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"steps\""); + + } + if (request.CfgScale != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.CfgScale, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"cfg_scale\""); + + } + if (request.Model != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.Model).HasValue ? (request.Model).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"model\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + var __contentAudio = new global::System.Net.Http.StreamContent(audio); + __contentAudio.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Audioname is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Audioname) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentAudio, + name: "\"audio\"", + fileName: request.Audioname != null ? $"\"{request.Audioname}\"" : string.Empty); + if (__contentAudio.Headers.ContentDisposition != null) + { + __contentAudio.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.Strength != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Strength, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"strength\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateAudioStableAudio2AudioToAudioAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2AudioToAudioAsBytes", + methodName: "CreateAudioStableAudio2AudioToAudioAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/audio-to-audio\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2AudioToAudioAsBytes", + methodName: "CreateAudioStableAudio2AudioToAudioAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/audio-to-audio\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2AudioToAudioAsBytes", + methodName: "CreateAudioStableAudio2AudioToAudioAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/audio-to-audio\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateAudioStableAudio2AudioToAudioAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2AudioToAudioAsBytes", + methodName: "CreateAudioStableAudio2AudioToAudioAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/audio-to-audio\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2AudioToAudioAsBytes", + methodName: "CreateAudioStableAudio2AudioToAudioAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/audio-to-audio\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse3? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse3.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse3.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse4? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse4.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse4.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse5? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse5.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse5.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse6? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse6.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse6.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessCreateAudioStableAudio2AudioToAudioAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return __content; + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return __content; + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Audio-to-Audio
+ /// Stable Audio transforms existing audio samples into new high-quality compositions up to three minutes
+ /// long at 44.1kHz stereo using text instructions. Discover techniques for sample transformation in our
+ /// [Audio to Audio Guide](https://www.stableaudio.com/user-guide/audio-to-audio) to maximize creative control.
+ /// Read more about the model capabilities [here](https://stability.ai/news/stable-audio-2-0).
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to
+ /// [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Audio_API.ipynb)
+ /// or try Stable Audio 2.0 for free at [stableaudio.com](https://stableaudio.com).
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`. The `accept` header should be set to one of the following:
+ /// - `audio/*` to receive the audio in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the audio encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `prompt` - text to generate the audio from. Check our
+ /// [prompt guide](https://www.stableaudio.com/user-guide/audio-to-audio) for tips
+ /// - `audio` - the audio to use as the starting point for the generation
+ /// > **Notes:**
+ /// > - We do not allow copyrighted content to be uploaded to our platform.
+ /// > - Maximum request size is 50Mb.
+ /// #### **Optional Parameters:**
+ /// The body may optionally include:
+ /// - `output_format` - the format of the output audio
+ /// - `seed` - the randomness seed to use for the generation
+ /// - `steps` - the number of sampling steps
+ /// - `duration` - the number of seconds of the generated audio
+ /// - `cfg_scale` - controls how strictly the diffusion process adheres to the prompt text (only for `stable-audio-2`)
+ /// - `model` - the model to use [`stable-audio-2`, `stable-audio-2.5`]
+ /// - `strength` - controls how much influence the `audio` parameter has on the output audio
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// **Stable Audio 2.0**
+ /// By default, 20 credits per successful generation. The number of credits is determined
+ /// by the following formula: `credits = 17 + 0.06 * steps`.
+ /// Examples:
+ /// - 50 steps = 20 credits [default]
+ /// - 100 steps = 23 credits
+ /// **Stable Audio 2.5**
+ /// Requests made using the Stable Audio 2.5 model have a flat rate of 20 credits per successful result.
+ /// As always, you will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `audio/*` to receive the bytes of the audio directly. Otherwise specify `application/json` to receive the audio as base64 encoded JSON.
+ /// Default Value: audio/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// What you wish the output audio to be. A strong, descriptive prompt that clearly defines
+ /// instruments, moods, styles, and genre will lead to better results.
+ /// You can make a prompt as simple or complex as you like. Simple prompts are good for clean
+ /// output audio. Complex prompts are good for adding texture and depth to the output audio.
+ /// Check our [prompt guide](https://www.stableaudio.com/user-guide/audio-to-audio) for tips. + /// + /// + /// Controls the duration in seconds of the generated audio.
+ /// Default Value: 190 + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Controls the number of sampling steps.
+ /// - For `stable-audio-2`: accepts steps between `30` and `100` (defaults to `50`).
+ /// - For `stable-audio-2.5`: accepts steps between `4` and `8` (defaults to `8`). + /// + /// + /// How strictly the diffusion process adheres to the prompt text (higher values make your
+ /// audio closer to your prompt).
+ /// Defaults to 7 for `stable-audio-2` and 1 for `stable-audio-2.5` if not specified. + /// + /// + /// The model to use for generation.
+ /// - `stable-audio-2.5` requires 20 credits per generation
+ /// - `stable-audio-2` requires 20 credits per generation
+ /// Default Value: stable-audio-2 + /// + /// + /// Dictates the `content-type` of the generated audio.
+ /// Default Value: mp3 + /// + /// + /// The audio to be use as the starting point for the generation.
+ /// Supported Formats:
+ /// - mp3
+ /// - wav
+ /// Validation Rule:
+ /// - Audio must be between 6 and 190 seconds long
+ /// Example: ./some/audio.mp3 + /// + /// + /// The audio to be use as the starting point for the generation.
+ /// Supported Formats:
+ /// - mp3
+ /// - wav
+ /// Validation Rule:
+ /// - Audio must be between 6 and 190 seconds long
+ /// Example: ./some/audio.mp3 + /// + /// + /// Sometimes referred to as _denoising_, this parameter controls how much influence the
+ /// `audio` parameter has on the generated audio.
+ /// A value of 0 would yield audio that is identical to the input.
+ /// A value of 1 would be as if you passed in no audio at all.
+ /// Minimum value for `stable-audio-2.5` is 0.01.
+ /// Default Value: 1 + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/audio/stable-audio-2/audio-to-audio",
+ /// headers={"authorization": f"Bearer sk-MYAPIKEY", "accept": "audio/*"},
+ /// files={
+ /// "audio": open("./uk-bass-base.mp3", "rb"),
+ /// },
+ /// data={
+ /// "prompt": "A song in the 3/4 time signature that features cheerful acoustic guitar, live recorded drums, and rhythmic claps, The mood is happy and up-lifting.",
+ /// "output_format": "mp3",
+ /// "duration": 20,
+ /// "model": "stable-audio-2.5",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./output.mp3", "wb") as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateAudioStableAudio2AudioToAudioAsBytesAsStreamAsync( + string contentType, + string prompt, + global::System.IO.Stream audio, + string audioname, + global::StabilityAI.CreateAudioStableAudio2AudioToAudioAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + double? duration = default, + double? seed = default, + int? steps = default, + double? cfgScale = default, + global::StabilityAI.CreateAudioStableAudio2AudioToAudioRequestModel? model = default, + global::StabilityAI.CreateAudioStableAudio2AudioToAudioRequestOutputFormat? outputFormat = default, + double? strength = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + + audio = audio ?? throw new global::System.ArgumentNullException(nameof(audio)); + var request = new global::StabilityAI.CreateAudioStableAudio2AudioToAudioRequest + { + Prompt = prompt, + Duration = duration, + Seed = seed, + Steps = steps, + CfgScale = cfgScale, + Model = model, + OutputFormat = outputFormat, + Audio = global::System.Array.Empty(), + Audioname = audioname, + Strength = strength, + }; + PrepareArguments( + client: HttpClient); + PrepareCreateAudioStableAudio2AudioToAudioAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateAudioStableAudio2AudioToAudioAsBytesSecurityRequirements, + operationName: "CreateAudioStableAudio2AudioToAudioAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/audio/stable-audio-2/audio-to-audio", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "audio/mpeg"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + if (request.Duration != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Duration, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"duration\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.Steps != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Steps, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"steps\""); + + } + if (request.CfgScale != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.CfgScale, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"cfg_scale\""); + + } + if (request.Model != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.Model).HasValue ? (request.Model).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"model\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + var __contentAudio = new global::System.Net.Http.StreamContent(audio); + __contentAudio.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Audioname is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Audioname) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentAudio, + name: "\"audio\"", + fileName: request.Audioname != null ? $"\"{request.Audioname}\"" : string.Empty); + if (__contentAudio.Headers.ContentDisposition != null) + { + __contentAudio.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.Strength != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Strength, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"strength\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateAudioStableAudio2AudioToAudioAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2AudioToAudioAsBytes", + methodName: "CreateAudioStableAudio2AudioToAudioAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/audio-to-audio\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseHeadersRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2AudioToAudioAsBytes", + methodName: "CreateAudioStableAudio2AudioToAudioAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/audio-to-audio\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2AudioToAudioAsBytes", + methodName: "CreateAudioStableAudio2AudioToAudioAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/audio-to-audio\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + try + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateAudioStableAudio2AudioToAudioAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2AudioToAudioAsBytes", + methodName: "CreateAudioStableAudio2AudioToAudioAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/audio-to-audio\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2AudioToAudioAsBytes", + methodName: "CreateAudioStableAudio2AudioToAudioAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/audio-to-audio\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse3? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse3.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse3.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse4? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse4.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse4.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse5? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse5.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse5.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse6? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse6.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse6.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + try + { + __response.EnsureSuccessStatusCode(); + + var __content = await __response.Content.ReadAsStreamAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.ResponseStream(__response, __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + } + catch + { + __response.Dispose(); + throw; + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Audio-to-Audio
+ /// Stable Audio transforms existing audio samples into new high-quality compositions up to three minutes
+ /// long at 44.1kHz stereo using text instructions. Discover techniques for sample transformation in our
+ /// [Audio to Audio Guide](https://www.stableaudio.com/user-guide/audio-to-audio) to maximize creative control.
+ /// Read more about the model capabilities [here](https://stability.ai/news/stable-audio-2-0).
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to
+ /// [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Audio_API.ipynb)
+ /// or try Stable Audio 2.0 for free at [stableaudio.com](https://stableaudio.com).
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`. The `accept` header should be set to one of the following:
+ /// - `audio/*` to receive the audio in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the audio encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `prompt` - text to generate the audio from. Check our
+ /// [prompt guide](https://www.stableaudio.com/user-guide/audio-to-audio) for tips
+ /// - `audio` - the audio to use as the starting point for the generation
+ /// > **Notes:**
+ /// > - We do not allow copyrighted content to be uploaded to our platform.
+ /// > - Maximum request size is 50Mb.
+ /// #### **Optional Parameters:**
+ /// The body may optionally include:
+ /// - `output_format` - the format of the output audio
+ /// - `seed` - the randomness seed to use for the generation
+ /// - `steps` - the number of sampling steps
+ /// - `duration` - the number of seconds of the generated audio
+ /// - `cfg_scale` - controls how strictly the diffusion process adheres to the prompt text (only for `stable-audio-2`)
+ /// - `model` - the model to use [`stable-audio-2`, `stable-audio-2.5`]
+ /// - `strength` - controls how much influence the `audio` parameter has on the output audio
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// **Stable Audio 2.0**
+ /// By default, 20 credits per successful generation. The number of credits is determined
+ /// by the following formula: `credits = 17 + 0.06 * steps`.
+ /// Examples:
+ /// - 50 steps = 20 credits [default]
+ /// - 100 steps = 23 credits
+ /// **Stable Audio 2.5**
+ /// Requests made using the Stable Audio 2.5 model have a flat rate of 20 credits per successful result.
+ /// As always, you will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `audio/*` to receive the bytes of the audio directly. Otherwise specify `application/json` to receive the audio as base64 encoded JSON.
+ /// Default Value: audio/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// What you wish the output audio to be. A strong, descriptive prompt that clearly defines
+ /// instruments, moods, styles, and genre will lead to better results.
+ /// You can make a prompt as simple or complex as you like. Simple prompts are good for clean
+ /// output audio. Complex prompts are good for adding texture and depth to the output audio.
+ /// Check our [prompt guide](https://www.stableaudio.com/user-guide/audio-to-audio) for tips. + /// + /// + /// Controls the duration in seconds of the generated audio.
+ /// Default Value: 190 + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Controls the number of sampling steps.
+ /// - For `stable-audio-2`: accepts steps between `30` and `100` (defaults to `50`).
+ /// - For `stable-audio-2.5`: accepts steps between `4` and `8` (defaults to `8`). + /// + /// + /// How strictly the diffusion process adheres to the prompt text (higher values make your
+ /// audio closer to your prompt).
+ /// Defaults to 7 for `stable-audio-2` and 1 for `stable-audio-2.5` if not specified. + /// + /// + /// The model to use for generation.
+ /// - `stable-audio-2.5` requires 20 credits per generation
+ /// - `stable-audio-2` requires 20 credits per generation
+ /// Default Value: stable-audio-2 + /// + /// + /// Dictates the `content-type` of the generated audio.
+ /// Default Value: mp3 + /// + /// + /// The audio to be use as the starting point for the generation.
+ /// Supported Formats:
+ /// - mp3
+ /// - wav
+ /// Validation Rule:
+ /// - Audio must be between 6 and 190 seconds long
+ /// Example: ./some/audio.mp3 + /// + /// + /// The audio to be use as the starting point for the generation.
+ /// Supported Formats:
+ /// - mp3
+ /// - wav
+ /// Validation Rule:
+ /// - Audio must be between 6 and 190 seconds long
+ /// Example: ./some/audio.mp3 + /// + /// + /// Sometimes referred to as _denoising_, this parameter controls how much influence the
+ /// `audio` parameter has on the generated audio.
+ /// A value of 0 would yield audio that is identical to the input.
+ /// A value of 1 would be as if you passed in no audio at all.
+ /// Minimum value for `stable-audio-2.5` is 0.01.
+ /// Default Value: 1 + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/audio/stable-audio-2/audio-to-audio",
+ /// headers={"authorization": f"Bearer sk-MYAPIKEY", "accept": "audio/*"},
+ /// files={
+ /// "audio": open("./uk-bass-base.mp3", "rb"),
+ /// },
+ /// data={
+ /// "prompt": "A song in the 3/4 time signature that features cheerful acoustic guitar, live recorded drums, and rhythmic claps, The mood is happy and up-lifting.",
+ /// "output_format": "mp3",
+ /// "duration": 20,
+ /// "model": "stable-audio-2.5",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./output.mp3", "wb") as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task> CreateAudioStableAudio2AudioToAudioAsBytesAsResponseAsync( + string contentType, + string prompt, + global::System.IO.Stream audio, + string audioname, + global::StabilityAI.CreateAudioStableAudio2AudioToAudioAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + double? duration = default, + double? seed = default, + int? steps = default, + double? cfgScale = default, + global::StabilityAI.CreateAudioStableAudio2AudioToAudioRequestModel? model = default, + global::StabilityAI.CreateAudioStableAudio2AudioToAudioRequestOutputFormat? outputFormat = default, + double? strength = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + + audio = audio ?? throw new global::System.ArgumentNullException(nameof(audio)); + var request = new global::StabilityAI.CreateAudioStableAudio2AudioToAudioRequest + { + Prompt = prompt, + Duration = duration, + Seed = seed, + Steps = steps, + CfgScale = cfgScale, + Model = model, + OutputFormat = outputFormat, + Audio = global::System.Array.Empty(), + Audioname = audioname, + Strength = strength, + }; + PrepareArguments( + client: HttpClient); + PrepareCreateAudioStableAudio2AudioToAudioAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateAudioStableAudio2AudioToAudioAsBytesSecurityRequirements, + operationName: "CreateAudioStableAudio2AudioToAudioAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/audio/stable-audio-2/audio-to-audio", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "audio/mpeg"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + if (request.Duration != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Duration, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"duration\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.Steps != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Steps, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"steps\""); + + } + if (request.CfgScale != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.CfgScale, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"cfg_scale\""); + + } + if (request.Model != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.Model).HasValue ? (request.Model).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"model\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + var __contentAudio = new global::System.Net.Http.StreamContent(audio); + __contentAudio.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Audioname is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Audioname) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentAudio, + name: "\"audio\"", + fileName: request.Audioname != null ? $"\"{request.Audioname}\"" : string.Empty); + if (__contentAudio.Headers.ContentDisposition != null) + { + __contentAudio.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.Strength != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Strength, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"strength\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateAudioStableAudio2AudioToAudioAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2AudioToAudioAsBytes", + methodName: "CreateAudioStableAudio2AudioToAudioAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/audio-to-audio\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2AudioToAudioAsBytes", + methodName: "CreateAudioStableAudio2AudioToAudioAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/audio-to-audio\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2AudioToAudioAsBytes", + methodName: "CreateAudioStableAudio2AudioToAudioAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/audio-to-audio\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateAudioStableAudio2AudioToAudioAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2AudioToAudioAsBytes", + methodName: "CreateAudioStableAudio2AudioToAudioAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/audio-to-audio\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2AudioToAudioAsBytes", + methodName: "CreateAudioStableAudio2AudioToAudioAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/audio-to-audio\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse3? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse3.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse3.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse4? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse4.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse4.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse5? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse5.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse5.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse6? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse6.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateAudioStableAudio2AudioToAudioResponse6.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessCreateAudioStableAudio2AudioToAudioAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + } +} \ No newline at end of file diff --git a/src/libs/StabilityAI/Generated/StabilityAI.StableAudio2Client.CreateAudioStableAudio2Inpaint.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.StableAudio2Client.CreateAudioStableAudio2Inpaint.g.cs index 0efd0f0..280faef 100644 --- a/src/libs/StabilityAI/Generated/StabilityAI.StableAudio2Client.CreateAudioStableAudio2Inpaint.g.cs +++ b/src/libs/StabilityAI/Generated/StabilityAI.StableAudio2Client.CreateAudioStableAudio2Inpaint.g.cs @@ -293,6 +293,10 @@ partial void ProcessCreateAudioStableAudio2InpaintResponseContent( __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || @@ -330,42 +334,6 @@ partial void ProcessCreateAudioStableAudio2InpaintResponseContent( var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"accept\""); - - } - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } __httpRequestContent.Add( content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), name: "\"prompt\""); @@ -1283,6 +1251,10 @@ request.Audioname is null __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || @@ -1320,42 +1292,6 @@ request.Audioname is null var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"accept\""); - - } - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } __httpRequestContent.Add( content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), name: "\"prompt\""); @@ -2121,6 +2057,10 @@ request.Audioname is null __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || @@ -2158,42 +2098,6 @@ request.Audioname is null var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"accept\""); - - } - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } __httpRequestContent.Add( content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), name: "\"prompt\""); diff --git a/src/libs/StabilityAI/Generated/StabilityAI.StableAudio2Client.CreateAudioStableAudio2InpaintAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.StableAudio2Client.CreateAudioStableAudio2InpaintAsBytes.g.cs new file mode 100644 index 0000000..25dcfa2 --- /dev/null +++ b/src/libs/StabilityAI/Generated/StabilityAI.StableAudio2Client.CreateAudioStableAudio2InpaintAsBytes.g.cs @@ -0,0 +1,4121 @@ + +#nullable enable + +namespace StabilityAI +{ + public partial class StableAudio2Client + { + + + private static readonly global::StabilityAI.EndPointSecurityRequirement s_CreateAudioStableAudio2InpaintAsBytesSecurityRequirement0 = + new global::StabilityAI.EndPointSecurityRequirement + { + Authorizations = new global::StabilityAI.EndPointAuthorizationRequirement[] + { new global::StabilityAI.EndPointAuthorizationRequirement + { + Type = "Http", + SchemeId = "HttpBearer", + Location = "Header", + Name = "Bearer", + FriendlyName = "Bearer", + }, + }, + }; + private static readonly global::StabilityAI.EndPointSecurityRequirement[] s_CreateAudioStableAudio2InpaintAsBytesSecurityRequirements = + new global::StabilityAI.EndPointSecurityRequirement[] + { s_CreateAudioStableAudio2InpaintAsBytesSecurityRequirement0, + }; + partial void PrepareCreateAudioStableAudio2InpaintAsBytesArguments( + global::System.Net.Http.HttpClient httpClient, + ref string contentType, + ref global::StabilityAI.CreateAudioStableAudio2InpaintAccept? accept, + ref string? stabilityClientId, + ref string? stabilityClientUserId, + ref string? stabilityClientVersion, + global::StabilityAI.CreateAudioStableAudio2InpaintRequest request); + partial void PrepareCreateAudioStableAudio2InpaintAsBytesRequest( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpRequestMessage httpRequestMessage, + string contentType, + global::StabilityAI.CreateAudioStableAudio2InpaintAccept? accept, + string? stabilityClientId, + string? stabilityClientUserId, + string? stabilityClientVersion, + global::StabilityAI.CreateAudioStableAudio2InpaintRequest request); + partial void ProcessCreateAudioStableAudio2InpaintAsBytesResponse( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpResponseMessage httpResponseMessage); + + partial void ProcessCreateAudioStableAudio2InpaintAsBytesResponseContent( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpResponseMessage httpResponseMessage, + ref byte[] content); + + /// + /// Inpaint
+ /// Stable Audio 2.5 transforms existing audio samples into new high-quality compositions up to three minutes
+ /// long at 44.1kHz stereo using text instructions.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to
+ /// [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Audio_API.ipynb).
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`. The `accept` header should be set to one of the following:
+ /// - `audio/*` to receive the audio in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the audio encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `prompt` - text to generate the audio from
+ /// - `audio` - the audio to use as the starting point for the generation
+ /// > **Notes:**
+ /// > - We do not allow copyrighted content to be uploaded to our platform.
+ /// > - Maximum request size is 50Mb.
+ /// #### **Optional Parameters:**
+ /// The body may optionally include:
+ /// - `output_format` - the format of the output audio
+ /// - `seed` - the randomness seed to use for the generation
+ /// - `duration` - the number of seconds of the generated audio
+ /// - `steps` - the number of sampling steps
+ /// - `mask_start` - start time in seconds for the audio segment to be inpainted (e.g., 30.0 for 30.0 seconds)
+ /// - `mask_end` - end time in seconds for the audio segment to be inpainted (e.g., 190.0 for 190.0 seconds)
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// **Stable Audio 2.5**
+ /// Flat rate of 20 credits per successful generation.
+ /// As always, you will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `audio/*` to receive the bytes of the audio directly. Otherwise specify `application/json` to receive the audio as base64 encoded JSON.
+ /// Default Value: audio/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/audio/stable-audio-2/inpaint",
+ /// headers={"authorization": f"Bearer sk-MYAPIKEY", "accept": "audio/*"},
+ /// files={
+ /// "audio": open("./uk-bass-base.mp3", "rb"),
+ /// },
+ /// data={
+ /// "prompt": "A song in the 3/4 time signature that features cheerful acoustic guitar, live recorded drums, and rhythmic claps, The mood is happy and up-lifting.",
+ /// "output_format": "mp3",
+ /// "duration": 20,
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./output.mp3", "wb") as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateAudioStableAudio2InpaintAsBytesAsync( + string contentType, + + global::StabilityAI.CreateAudioStableAudio2InpaintRequest request, + global::StabilityAI.CreateAudioStableAudio2InpaintAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + var __response = await CreateAudioStableAudio2InpaintAsBytesAsResponseAsync( + contentType: contentType, + + request: request, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + requestOptions: requestOptions, + cancellationToken: cancellationToken + ).ConfigureAwait(false); + + return __response.Body; + } + /// + /// Inpaint
+ /// Stable Audio 2.5 transforms existing audio samples into new high-quality compositions up to three minutes
+ /// long at 44.1kHz stereo using text instructions.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to
+ /// [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Audio_API.ipynb).
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`. The `accept` header should be set to one of the following:
+ /// - `audio/*` to receive the audio in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the audio encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `prompt` - text to generate the audio from
+ /// - `audio` - the audio to use as the starting point for the generation
+ /// > **Notes:**
+ /// > - We do not allow copyrighted content to be uploaded to our platform.
+ /// > - Maximum request size is 50Mb.
+ /// #### **Optional Parameters:**
+ /// The body may optionally include:
+ /// - `output_format` - the format of the output audio
+ /// - `seed` - the randomness seed to use for the generation
+ /// - `duration` - the number of seconds of the generated audio
+ /// - `steps` - the number of sampling steps
+ /// - `mask_start` - start time in seconds for the audio segment to be inpainted (e.g., 30.0 for 30.0 seconds)
+ /// - `mask_end` - end time in seconds for the audio segment to be inpainted (e.g., 190.0 for 190.0 seconds)
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// **Stable Audio 2.5**
+ /// Flat rate of 20 credits per successful generation.
+ /// As always, you will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `audio/*` to receive the bytes of the audio directly. Otherwise specify `application/json` to receive the audio as base64 encoded JSON.
+ /// Default Value: audio/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/audio/stable-audio-2/inpaint",
+ /// headers={"authorization": f"Bearer sk-MYAPIKEY", "accept": "audio/*"},
+ /// files={
+ /// "audio": open("./uk-bass-base.mp3", "rb"),
+ /// },
+ /// data={
+ /// "prompt": "A song in the 3/4 time signature that features cheerful acoustic guitar, live recorded drums, and rhythmic claps, The mood is happy and up-lifting.",
+ /// "output_format": "mp3",
+ /// "duration": 20,
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./output.mp3", "wb") as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateAudioStableAudio2InpaintAsBytesAsStreamAsync( + string contentType, + + global::StabilityAI.CreateAudioStableAudio2InpaintRequest request, + global::StabilityAI.CreateAudioStableAudio2InpaintAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + request = request ?? throw new global::System.ArgumentNullException(nameof(request)); + + PrepareArguments( + client: HttpClient); + PrepareCreateAudioStableAudio2InpaintAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateAudioStableAudio2InpaintAsBytesSecurityRequirements, + operationName: "CreateAudioStableAudio2InpaintAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/audio/stable-audio-2/inpaint", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "audio/mpeg"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + if (request.Duration != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Duration, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"duration\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.Steps != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Steps, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"steps\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + var __contentAudio = new global::System.Net.Http.ByteArrayContent(request.Audio ?? global::System.Array.Empty()); + __contentAudio.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Audioname is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Audioname) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentAudio, + name: "\"audio\"", + fileName: request.Audioname != null ? $"\"{request.Audioname}\"" : string.Empty); + if (__contentAudio.Headers.ContentDisposition != null) + { + __contentAudio.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.MaskStart != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.MaskStart, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"mask_start\""); + + } + if (request.MaskEnd != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.MaskEnd, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"mask_end\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateAudioStableAudio2InpaintAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2InpaintAsBytes", + methodName: "CreateAudioStableAudio2InpaintAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseHeadersRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2InpaintAsBytes", + methodName: "CreateAudioStableAudio2InpaintAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2InpaintAsBytes", + methodName: "CreateAudioStableAudio2InpaintAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + try + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateAudioStableAudio2InpaintAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2InpaintAsBytes", + methodName: "CreateAudioStableAudio2InpaintAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2InpaintAsBytes", + methodName: "CreateAudioStableAudio2InpaintAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateAudioStableAudio2InpaintResponse3? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateAudioStableAudio2InpaintResponse3.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateAudioStableAudio2InpaintResponse3.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateAudioStableAudio2InpaintResponse4? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateAudioStableAudio2InpaintResponse4.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateAudioStableAudio2InpaintResponse4.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateAudioStableAudio2InpaintResponse5? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateAudioStableAudio2InpaintResponse5.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateAudioStableAudio2InpaintResponse5.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateAudioStableAudio2InpaintResponse6? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateAudioStableAudio2InpaintResponse6.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateAudioStableAudio2InpaintResponse6.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + try + { + __response.EnsureSuccessStatusCode(); + + var __content = await __response.Content.ReadAsStreamAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.ResponseStream(__response, __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + } + catch + { + __response.Dispose(); + throw; + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Inpaint
+ /// Stable Audio 2.5 transforms existing audio samples into new high-quality compositions up to three minutes
+ /// long at 44.1kHz stereo using text instructions.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to
+ /// [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Audio_API.ipynb).
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`. The `accept` header should be set to one of the following:
+ /// - `audio/*` to receive the audio in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the audio encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `prompt` - text to generate the audio from
+ /// - `audio` - the audio to use as the starting point for the generation
+ /// > **Notes:**
+ /// > - We do not allow copyrighted content to be uploaded to our platform.
+ /// > - Maximum request size is 50Mb.
+ /// #### **Optional Parameters:**
+ /// The body may optionally include:
+ /// - `output_format` - the format of the output audio
+ /// - `seed` - the randomness seed to use for the generation
+ /// - `duration` - the number of seconds of the generated audio
+ /// - `steps` - the number of sampling steps
+ /// - `mask_start` - start time in seconds for the audio segment to be inpainted (e.g., 30.0 for 30.0 seconds)
+ /// - `mask_end` - end time in seconds for the audio segment to be inpainted (e.g., 190.0 for 190.0 seconds)
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// **Stable Audio 2.5**
+ /// Flat rate of 20 credits per successful generation.
+ /// As always, you will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `audio/*` to receive the bytes of the audio directly. Otherwise specify `application/json` to receive the audio as base64 encoded JSON.
+ /// Default Value: audio/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/audio/stable-audio-2/inpaint",
+ /// headers={"authorization": f"Bearer sk-MYAPIKEY", "accept": "audio/*"},
+ /// files={
+ /// "audio": open("./uk-bass-base.mp3", "rb"),
+ /// },
+ /// data={
+ /// "prompt": "A song in the 3/4 time signature that features cheerful acoustic guitar, live recorded drums, and rhythmic claps, The mood is happy and up-lifting.",
+ /// "output_format": "mp3",
+ /// "duration": 20,
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./output.mp3", "wb") as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task> CreateAudioStableAudio2InpaintAsBytesAsResponseAsync( + string contentType, + + global::StabilityAI.CreateAudioStableAudio2InpaintRequest request, + global::StabilityAI.CreateAudioStableAudio2InpaintAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + request = request ?? throw new global::System.ArgumentNullException(nameof(request)); + + PrepareArguments( + client: HttpClient); + PrepareCreateAudioStableAudio2InpaintAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateAudioStableAudio2InpaintAsBytesSecurityRequirements, + operationName: "CreateAudioStableAudio2InpaintAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/audio/stable-audio-2/inpaint", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "audio/mpeg"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + if (request.Duration != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Duration, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"duration\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.Steps != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Steps, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"steps\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + var __contentAudio = new global::System.Net.Http.ByteArrayContent(request.Audio ?? global::System.Array.Empty()); + __contentAudio.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Audioname is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Audioname) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentAudio, + name: "\"audio\"", + fileName: request.Audioname != null ? $"\"{request.Audioname}\"" : string.Empty); + if (__contentAudio.Headers.ContentDisposition != null) + { + __contentAudio.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.MaskStart != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.MaskStart, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"mask_start\""); + + } + if (request.MaskEnd != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.MaskEnd, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"mask_end\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateAudioStableAudio2InpaintAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2InpaintAsBytes", + methodName: "CreateAudioStableAudio2InpaintAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2InpaintAsBytes", + methodName: "CreateAudioStableAudio2InpaintAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2InpaintAsBytes", + methodName: "CreateAudioStableAudio2InpaintAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateAudioStableAudio2InpaintAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2InpaintAsBytes", + methodName: "CreateAudioStableAudio2InpaintAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2InpaintAsBytes", + methodName: "CreateAudioStableAudio2InpaintAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateAudioStableAudio2InpaintResponse3? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateAudioStableAudio2InpaintResponse3.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateAudioStableAudio2InpaintResponse3.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateAudioStableAudio2InpaintResponse4? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateAudioStableAudio2InpaintResponse4.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateAudioStableAudio2InpaintResponse4.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateAudioStableAudio2InpaintResponse5? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateAudioStableAudio2InpaintResponse5.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateAudioStableAudio2InpaintResponse5.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateAudioStableAudio2InpaintResponse6? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateAudioStableAudio2InpaintResponse6.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateAudioStableAudio2InpaintResponse6.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessCreateAudioStableAudio2InpaintAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Inpaint
+ /// Stable Audio 2.5 transforms existing audio samples into new high-quality compositions up to three minutes
+ /// long at 44.1kHz stereo using text instructions.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to
+ /// [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Audio_API.ipynb).
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`. The `accept` header should be set to one of the following:
+ /// - `audio/*` to receive the audio in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the audio encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `prompt` - text to generate the audio from
+ /// - `audio` - the audio to use as the starting point for the generation
+ /// > **Notes:**
+ /// > - We do not allow copyrighted content to be uploaded to our platform.
+ /// > - Maximum request size is 50Mb.
+ /// #### **Optional Parameters:**
+ /// The body may optionally include:
+ /// - `output_format` - the format of the output audio
+ /// - `seed` - the randomness seed to use for the generation
+ /// - `duration` - the number of seconds of the generated audio
+ /// - `steps` - the number of sampling steps
+ /// - `mask_start` - start time in seconds for the audio segment to be inpainted (e.g., 30.0 for 30.0 seconds)
+ /// - `mask_end` - end time in seconds for the audio segment to be inpainted (e.g., 190.0 for 190.0 seconds)
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// **Stable Audio 2.5**
+ /// Flat rate of 20 credits per successful generation.
+ /// As always, you will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `audio/*` to receive the bytes of the audio directly. Otherwise specify `application/json` to receive the audio as base64 encoded JSON.
+ /// Default Value: audio/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// What you wish the output audio to be. A strong, descriptive prompt that clearly defines
+ /// instruments, moods, styles, and genre will lead to better results.
+ /// You can make a prompt as simple or complex as you like. Simple prompts are good for clean
+ /// output audio. Complex prompts are good for adding texture and depth to the output audio. + /// + /// + /// Controls the duration in seconds of the generated audio.
+ /// Default Value: 190 + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Controls the number of sampling steps.
+ /// Default Value: 8 + /// + /// + /// Dictates the `content-type` of the generated audio.
+ /// Default Value: mp3 + /// + /// + /// The audio to be use as the starting point for the generation.
+ /// Supported Formats:
+ /// - mp3
+ /// - wav
+ /// Validation Rule:
+ /// - Audio must be between 6 and 190 seconds long
+ /// Example: ./some/audio.mp3 + /// + /// + /// The audio to be use as the starting point for the generation.
+ /// Supported Formats:
+ /// - mp3
+ /// - wav
+ /// Validation Rule:
+ /// - Audio must be between 6 and 190 seconds long
+ /// Example: ./some/audio.mp3 + /// + /// + /// Default Value: 30 + /// + /// + /// Default Value: 190 + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + public async global::System.Threading.Tasks.Task CreateAudioStableAudio2InpaintAsBytesAsync( + string contentType, + string prompt, + byte[] audio, + string audioname, + global::StabilityAI.CreateAudioStableAudio2InpaintAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + double? duration = default, + double? seed = default, + int? steps = default, + global::StabilityAI.CreateAudioStableAudio2InpaintRequestOutputFormat? outputFormat = default, + double? maskStart = default, + double? maskEnd = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + var __request = new global::StabilityAI.CreateAudioStableAudio2InpaintRequest + { + Prompt = prompt, + Duration = duration, + Seed = seed, + Steps = steps, + OutputFormat = outputFormat, + Audio = audio, + Audioname = audioname, + MaskStart = maskStart, + MaskEnd = maskEnd, + }; + + return await CreateAudioStableAudio2InpaintAsBytesAsync( + contentType: contentType, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: __request, + requestOptions: requestOptions, + cancellationToken: cancellationToken).ConfigureAwait(false); + } + + /// + /// Inpaint
+ /// Stable Audio 2.5 transforms existing audio samples into new high-quality compositions up to three minutes
+ /// long at 44.1kHz stereo using text instructions.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to
+ /// [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Audio_API.ipynb).
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`. The `accept` header should be set to one of the following:
+ /// - `audio/*` to receive the audio in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the audio encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `prompt` - text to generate the audio from
+ /// - `audio` - the audio to use as the starting point for the generation
+ /// > **Notes:**
+ /// > - We do not allow copyrighted content to be uploaded to our platform.
+ /// > - Maximum request size is 50Mb.
+ /// #### **Optional Parameters:**
+ /// The body may optionally include:
+ /// - `output_format` - the format of the output audio
+ /// - `seed` - the randomness seed to use for the generation
+ /// - `duration` - the number of seconds of the generated audio
+ /// - `steps` - the number of sampling steps
+ /// - `mask_start` - start time in seconds for the audio segment to be inpainted (e.g., 30.0 for 30.0 seconds)
+ /// - `mask_end` - end time in seconds for the audio segment to be inpainted (e.g., 190.0 for 190.0 seconds)
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// **Stable Audio 2.5**
+ /// Flat rate of 20 credits per successful generation.
+ /// As always, you will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `audio/*` to receive the bytes of the audio directly. Otherwise specify `application/json` to receive the audio as base64 encoded JSON.
+ /// Default Value: audio/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// What you wish the output audio to be. A strong, descriptive prompt that clearly defines
+ /// instruments, moods, styles, and genre will lead to better results.
+ /// You can make a prompt as simple or complex as you like. Simple prompts are good for clean
+ /// output audio. Complex prompts are good for adding texture and depth to the output audio. + /// + /// + /// Controls the duration in seconds of the generated audio.
+ /// Default Value: 190 + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Controls the number of sampling steps.
+ /// Default Value: 8 + /// + /// + /// Dictates the `content-type` of the generated audio.
+ /// Default Value: mp3 + /// + /// + /// The audio to be use as the starting point for the generation.
+ /// Supported Formats:
+ /// - mp3
+ /// - wav
+ /// Validation Rule:
+ /// - Audio must be between 6 and 190 seconds long
+ /// Example: ./some/audio.mp3 + /// + /// + /// The audio to be use as the starting point for the generation.
+ /// Supported Formats:
+ /// - mp3
+ /// - wav
+ /// Validation Rule:
+ /// - Audio must be between 6 and 190 seconds long
+ /// Example: ./some/audio.mp3 + /// + /// + /// Default Value: 30 + /// + /// + /// Default Value: 190 + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/audio/stable-audio-2/inpaint",
+ /// headers={"authorization": f"Bearer sk-MYAPIKEY", "accept": "audio/*"},
+ /// files={
+ /// "audio": open("./uk-bass-base.mp3", "rb"),
+ /// },
+ /// data={
+ /// "prompt": "A song in the 3/4 time signature that features cheerful acoustic guitar, live recorded drums, and rhythmic claps, The mood is happy and up-lifting.",
+ /// "output_format": "mp3",
+ /// "duration": 20,
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./output.mp3", "wb") as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateAudioStableAudio2InpaintAsBytesAsync( + string contentType, + string prompt, + global::System.IO.Stream audio, + string audioname, + global::StabilityAI.CreateAudioStableAudio2InpaintAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + double? duration = default, + double? seed = default, + int? steps = default, + global::StabilityAI.CreateAudioStableAudio2InpaintRequestOutputFormat? outputFormat = default, + double? maskStart = default, + double? maskEnd = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + + audio = audio ?? throw new global::System.ArgumentNullException(nameof(audio)); + var request = new global::StabilityAI.CreateAudioStableAudio2InpaintRequest + { + Prompt = prompt, + Duration = duration, + Seed = seed, + Steps = steps, + OutputFormat = outputFormat, + Audio = global::System.Array.Empty(), + Audioname = audioname, + MaskStart = maskStart, + MaskEnd = maskEnd, + }; + PrepareArguments( + client: HttpClient); + PrepareCreateAudioStableAudio2InpaintAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateAudioStableAudio2InpaintAsBytesSecurityRequirements, + operationName: "CreateAudioStableAudio2InpaintAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/audio/stable-audio-2/inpaint", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "audio/mpeg"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + if (request.Duration != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Duration, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"duration\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.Steps != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Steps, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"steps\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + var __contentAudio = new global::System.Net.Http.StreamContent(audio); + __contentAudio.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Audioname is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Audioname) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentAudio, + name: "\"audio\"", + fileName: request.Audioname != null ? $"\"{request.Audioname}\"" : string.Empty); + if (__contentAudio.Headers.ContentDisposition != null) + { + __contentAudio.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.MaskStart != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.MaskStart, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"mask_start\""); + + } + if (request.MaskEnd != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.MaskEnd, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"mask_end\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateAudioStableAudio2InpaintAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2InpaintAsBytes", + methodName: "CreateAudioStableAudio2InpaintAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2InpaintAsBytes", + methodName: "CreateAudioStableAudio2InpaintAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2InpaintAsBytes", + methodName: "CreateAudioStableAudio2InpaintAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateAudioStableAudio2InpaintAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2InpaintAsBytes", + methodName: "CreateAudioStableAudio2InpaintAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2InpaintAsBytes", + methodName: "CreateAudioStableAudio2InpaintAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateAudioStableAudio2InpaintResponse3? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateAudioStableAudio2InpaintResponse3.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateAudioStableAudio2InpaintResponse3.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateAudioStableAudio2InpaintResponse4? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateAudioStableAudio2InpaintResponse4.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateAudioStableAudio2InpaintResponse4.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateAudioStableAudio2InpaintResponse5? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateAudioStableAudio2InpaintResponse5.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateAudioStableAudio2InpaintResponse5.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateAudioStableAudio2InpaintResponse6? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateAudioStableAudio2InpaintResponse6.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateAudioStableAudio2InpaintResponse6.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessCreateAudioStableAudio2InpaintAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return __content; + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return __content; + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Inpaint
+ /// Stable Audio 2.5 transforms existing audio samples into new high-quality compositions up to three minutes
+ /// long at 44.1kHz stereo using text instructions.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to
+ /// [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Audio_API.ipynb).
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`. The `accept` header should be set to one of the following:
+ /// - `audio/*` to receive the audio in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the audio encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `prompt` - text to generate the audio from
+ /// - `audio` - the audio to use as the starting point for the generation
+ /// > **Notes:**
+ /// > - We do not allow copyrighted content to be uploaded to our platform.
+ /// > - Maximum request size is 50Mb.
+ /// #### **Optional Parameters:**
+ /// The body may optionally include:
+ /// - `output_format` - the format of the output audio
+ /// - `seed` - the randomness seed to use for the generation
+ /// - `duration` - the number of seconds of the generated audio
+ /// - `steps` - the number of sampling steps
+ /// - `mask_start` - start time in seconds for the audio segment to be inpainted (e.g., 30.0 for 30.0 seconds)
+ /// - `mask_end` - end time in seconds for the audio segment to be inpainted (e.g., 190.0 for 190.0 seconds)
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// **Stable Audio 2.5**
+ /// Flat rate of 20 credits per successful generation.
+ /// As always, you will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `audio/*` to receive the bytes of the audio directly. Otherwise specify `application/json` to receive the audio as base64 encoded JSON.
+ /// Default Value: audio/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// What you wish the output audio to be. A strong, descriptive prompt that clearly defines
+ /// instruments, moods, styles, and genre will lead to better results.
+ /// You can make a prompt as simple or complex as you like. Simple prompts are good for clean
+ /// output audio. Complex prompts are good for adding texture and depth to the output audio. + /// + /// + /// Controls the duration in seconds of the generated audio.
+ /// Default Value: 190 + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Controls the number of sampling steps.
+ /// Default Value: 8 + /// + /// + /// Dictates the `content-type` of the generated audio.
+ /// Default Value: mp3 + /// + /// + /// The audio to be use as the starting point for the generation.
+ /// Supported Formats:
+ /// - mp3
+ /// - wav
+ /// Validation Rule:
+ /// - Audio must be between 6 and 190 seconds long
+ /// Example: ./some/audio.mp3 + /// + /// + /// The audio to be use as the starting point for the generation.
+ /// Supported Formats:
+ /// - mp3
+ /// - wav
+ /// Validation Rule:
+ /// - Audio must be between 6 and 190 seconds long
+ /// Example: ./some/audio.mp3 + /// + /// + /// Default Value: 30 + /// + /// + /// Default Value: 190 + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/audio/stable-audio-2/inpaint",
+ /// headers={"authorization": f"Bearer sk-MYAPIKEY", "accept": "audio/*"},
+ /// files={
+ /// "audio": open("./uk-bass-base.mp3", "rb"),
+ /// },
+ /// data={
+ /// "prompt": "A song in the 3/4 time signature that features cheerful acoustic guitar, live recorded drums, and rhythmic claps, The mood is happy and up-lifting.",
+ /// "output_format": "mp3",
+ /// "duration": 20,
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./output.mp3", "wb") as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateAudioStableAudio2InpaintAsBytesAsStreamAsync( + string contentType, + string prompt, + global::System.IO.Stream audio, + string audioname, + global::StabilityAI.CreateAudioStableAudio2InpaintAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + double? duration = default, + double? seed = default, + int? steps = default, + global::StabilityAI.CreateAudioStableAudio2InpaintRequestOutputFormat? outputFormat = default, + double? maskStart = default, + double? maskEnd = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + + audio = audio ?? throw new global::System.ArgumentNullException(nameof(audio)); + var request = new global::StabilityAI.CreateAudioStableAudio2InpaintRequest + { + Prompt = prompt, + Duration = duration, + Seed = seed, + Steps = steps, + OutputFormat = outputFormat, + Audio = global::System.Array.Empty(), + Audioname = audioname, + MaskStart = maskStart, + MaskEnd = maskEnd, + }; + PrepareArguments( + client: HttpClient); + PrepareCreateAudioStableAudio2InpaintAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateAudioStableAudio2InpaintAsBytesSecurityRequirements, + operationName: "CreateAudioStableAudio2InpaintAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/audio/stable-audio-2/inpaint", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "audio/mpeg"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + if (request.Duration != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Duration, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"duration\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.Steps != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Steps, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"steps\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + var __contentAudio = new global::System.Net.Http.StreamContent(audio); + __contentAudio.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Audioname is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Audioname) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentAudio, + name: "\"audio\"", + fileName: request.Audioname != null ? $"\"{request.Audioname}\"" : string.Empty); + if (__contentAudio.Headers.ContentDisposition != null) + { + __contentAudio.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.MaskStart != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.MaskStart, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"mask_start\""); + + } + if (request.MaskEnd != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.MaskEnd, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"mask_end\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateAudioStableAudio2InpaintAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2InpaintAsBytes", + methodName: "CreateAudioStableAudio2InpaintAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseHeadersRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2InpaintAsBytes", + methodName: "CreateAudioStableAudio2InpaintAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2InpaintAsBytes", + methodName: "CreateAudioStableAudio2InpaintAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + try + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateAudioStableAudio2InpaintAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2InpaintAsBytes", + methodName: "CreateAudioStableAudio2InpaintAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2InpaintAsBytes", + methodName: "CreateAudioStableAudio2InpaintAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateAudioStableAudio2InpaintResponse3? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateAudioStableAudio2InpaintResponse3.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateAudioStableAudio2InpaintResponse3.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateAudioStableAudio2InpaintResponse4? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateAudioStableAudio2InpaintResponse4.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateAudioStableAudio2InpaintResponse4.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateAudioStableAudio2InpaintResponse5? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateAudioStableAudio2InpaintResponse5.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateAudioStableAudio2InpaintResponse5.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateAudioStableAudio2InpaintResponse6? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateAudioStableAudio2InpaintResponse6.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateAudioStableAudio2InpaintResponse6.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + try + { + __response.EnsureSuccessStatusCode(); + + var __content = await __response.Content.ReadAsStreamAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.ResponseStream(__response, __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + } + catch + { + __response.Dispose(); + throw; + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Inpaint
+ /// Stable Audio 2.5 transforms existing audio samples into new high-quality compositions up to three minutes
+ /// long at 44.1kHz stereo using text instructions.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to
+ /// [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Audio_API.ipynb).
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`. The `accept` header should be set to one of the following:
+ /// - `audio/*` to receive the audio in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the audio encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `prompt` - text to generate the audio from
+ /// - `audio` - the audio to use as the starting point for the generation
+ /// > **Notes:**
+ /// > - We do not allow copyrighted content to be uploaded to our platform.
+ /// > - Maximum request size is 50Mb.
+ /// #### **Optional Parameters:**
+ /// The body may optionally include:
+ /// - `output_format` - the format of the output audio
+ /// - `seed` - the randomness seed to use for the generation
+ /// - `duration` - the number of seconds of the generated audio
+ /// - `steps` - the number of sampling steps
+ /// - `mask_start` - start time in seconds for the audio segment to be inpainted (e.g., 30.0 for 30.0 seconds)
+ /// - `mask_end` - end time in seconds for the audio segment to be inpainted (e.g., 190.0 for 190.0 seconds)
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// **Stable Audio 2.5**
+ /// Flat rate of 20 credits per successful generation.
+ /// As always, you will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `audio/*` to receive the bytes of the audio directly. Otherwise specify `application/json` to receive the audio as base64 encoded JSON.
+ /// Default Value: audio/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// What you wish the output audio to be. A strong, descriptive prompt that clearly defines
+ /// instruments, moods, styles, and genre will lead to better results.
+ /// You can make a prompt as simple or complex as you like. Simple prompts are good for clean
+ /// output audio. Complex prompts are good for adding texture and depth to the output audio. + /// + /// + /// Controls the duration in seconds of the generated audio.
+ /// Default Value: 190 + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Controls the number of sampling steps.
+ /// Default Value: 8 + /// + /// + /// Dictates the `content-type` of the generated audio.
+ /// Default Value: mp3 + /// + /// + /// The audio to be use as the starting point for the generation.
+ /// Supported Formats:
+ /// - mp3
+ /// - wav
+ /// Validation Rule:
+ /// - Audio must be between 6 and 190 seconds long
+ /// Example: ./some/audio.mp3 + /// + /// + /// The audio to be use as the starting point for the generation.
+ /// Supported Formats:
+ /// - mp3
+ /// - wav
+ /// Validation Rule:
+ /// - Audio must be between 6 and 190 seconds long
+ /// Example: ./some/audio.mp3 + /// + /// + /// Default Value: 30 + /// + /// + /// Default Value: 190 + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/audio/stable-audio-2/inpaint",
+ /// headers={"authorization": f"Bearer sk-MYAPIKEY", "accept": "audio/*"},
+ /// files={
+ /// "audio": open("./uk-bass-base.mp3", "rb"),
+ /// },
+ /// data={
+ /// "prompt": "A song in the 3/4 time signature that features cheerful acoustic guitar, live recorded drums, and rhythmic claps, The mood is happy and up-lifting.",
+ /// "output_format": "mp3",
+ /// "duration": 20,
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./output.mp3", "wb") as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task> CreateAudioStableAudio2InpaintAsBytesAsResponseAsync( + string contentType, + string prompt, + global::System.IO.Stream audio, + string audioname, + global::StabilityAI.CreateAudioStableAudio2InpaintAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + double? duration = default, + double? seed = default, + int? steps = default, + global::StabilityAI.CreateAudioStableAudio2InpaintRequestOutputFormat? outputFormat = default, + double? maskStart = default, + double? maskEnd = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + + audio = audio ?? throw new global::System.ArgumentNullException(nameof(audio)); + var request = new global::StabilityAI.CreateAudioStableAudio2InpaintRequest + { + Prompt = prompt, + Duration = duration, + Seed = seed, + Steps = steps, + OutputFormat = outputFormat, + Audio = global::System.Array.Empty(), + Audioname = audioname, + MaskStart = maskStart, + MaskEnd = maskEnd, + }; + PrepareArguments( + client: HttpClient); + PrepareCreateAudioStableAudio2InpaintAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateAudioStableAudio2InpaintAsBytesSecurityRequirements, + operationName: "CreateAudioStableAudio2InpaintAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/audio/stable-audio-2/inpaint", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "audio/mpeg"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + if (request.Duration != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Duration, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"duration\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.Steps != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Steps, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"steps\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + var __contentAudio = new global::System.Net.Http.StreamContent(audio); + __contentAudio.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Audioname is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Audioname) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentAudio, + name: "\"audio\"", + fileName: request.Audioname != null ? $"\"{request.Audioname}\"" : string.Empty); + if (__contentAudio.Headers.ContentDisposition != null) + { + __contentAudio.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.MaskStart != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.MaskStart, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"mask_start\""); + + } + if (request.MaskEnd != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.MaskEnd, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"mask_end\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateAudioStableAudio2InpaintAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2InpaintAsBytes", + methodName: "CreateAudioStableAudio2InpaintAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2InpaintAsBytes", + methodName: "CreateAudioStableAudio2InpaintAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2InpaintAsBytes", + methodName: "CreateAudioStableAudio2InpaintAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateAudioStableAudio2InpaintAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2InpaintAsBytes", + methodName: "CreateAudioStableAudio2InpaintAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2InpaintAsBytes", + methodName: "CreateAudioStableAudio2InpaintAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateAudioStableAudio2InpaintResponse3? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateAudioStableAudio2InpaintResponse3.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateAudioStableAudio2InpaintResponse3.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateAudioStableAudio2InpaintResponse4? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateAudioStableAudio2InpaintResponse4.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateAudioStableAudio2InpaintResponse4.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateAudioStableAudio2InpaintResponse5? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateAudioStableAudio2InpaintResponse5.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateAudioStableAudio2InpaintResponse5.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateAudioStableAudio2InpaintResponse6? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateAudioStableAudio2InpaintResponse6.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateAudioStableAudio2InpaintResponse6.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessCreateAudioStableAudio2InpaintAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + } +} \ No newline at end of file diff --git a/src/libs/StabilityAI/Generated/StabilityAI.StableAudio2Client.CreateAudioStableAudio2TextToAudio.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.StableAudio2Client.CreateAudioStableAudio2TextToAudio.g.cs index 19d5b1a..72c2c69 100644 --- a/src/libs/StabilityAI/Generated/StabilityAI.StableAudio2Client.CreateAudioStableAudio2TextToAudio.g.cs +++ b/src/libs/StabilityAI/Generated/StabilityAI.StableAudio2Client.CreateAudioStableAudio2TextToAudio.g.cs @@ -303,6 +303,10 @@ partial void ProcessCreateAudioStableAudio2TextToAudioResponseContent( __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || @@ -340,42 +344,6 @@ partial void ProcessCreateAudioStableAudio2TextToAudioResponseContent( var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"accept\""); - - } - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } __httpRequestContent.Add( content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), name: "\"prompt\""); diff --git a/src/libs/StabilityAI/Generated/StabilityAI.StableAudio2Client.CreateAudioStableAudio2TextToAudioAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.StableAudio2Client.CreateAudioStableAudio2TextToAudioAsBytes.g.cs new file mode 100644 index 0000000..d127685 --- /dev/null +++ b/src/libs/StabilityAI/Generated/StabilityAI.StableAudio2Client.CreateAudioStableAudio2TextToAudioAsBytes.g.cs @@ -0,0 +1,1677 @@ + +#nullable enable + +namespace StabilityAI +{ + public partial class StableAudio2Client + { + + + private static readonly global::StabilityAI.EndPointSecurityRequirement s_CreateAudioStableAudio2TextToAudioAsBytesSecurityRequirement0 = + new global::StabilityAI.EndPointSecurityRequirement + { + Authorizations = new global::StabilityAI.EndPointAuthorizationRequirement[] + { new global::StabilityAI.EndPointAuthorizationRequirement + { + Type = "Http", + SchemeId = "HttpBearer", + Location = "Header", + Name = "Bearer", + FriendlyName = "Bearer", + }, + }, + }; + private static readonly global::StabilityAI.EndPointSecurityRequirement[] s_CreateAudioStableAudio2TextToAudioAsBytesSecurityRequirements = + new global::StabilityAI.EndPointSecurityRequirement[] + { s_CreateAudioStableAudio2TextToAudioAsBytesSecurityRequirement0, + }; + partial void PrepareCreateAudioStableAudio2TextToAudioAsBytesArguments( + global::System.Net.Http.HttpClient httpClient, + ref string contentType, + ref global::StabilityAI.CreateAudioStableAudio2TextToAudioAccept? accept, + ref string? stabilityClientId, + ref string? stabilityClientUserId, + ref string? stabilityClientVersion, + global::StabilityAI.CreateAudioStableAudio2TextToAudioRequest request); + partial void PrepareCreateAudioStableAudio2TextToAudioAsBytesRequest( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpRequestMessage httpRequestMessage, + string contentType, + global::StabilityAI.CreateAudioStableAudio2TextToAudioAccept? accept, + string? stabilityClientId, + string? stabilityClientUserId, + string? stabilityClientVersion, + global::StabilityAI.CreateAudioStableAudio2TextToAudioRequest request); + partial void ProcessCreateAudioStableAudio2TextToAudioAsBytesResponse( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpResponseMessage httpResponseMessage); + + partial void ProcessCreateAudioStableAudio2TextToAudioAsBytesResponseContent( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpResponseMessage httpResponseMessage, + ref byte[] content); + + /// + /// Text-to-Audio
+ /// Stable Audio generates high-quality music and sound effects up to three minutes long at
+ /// 44.1kHz stereo from text descriptions. Learn how to craft effective prompts in our
+ /// [Prompt Guide](https://www.stableaudio.com/user-guide/text-to-audio) to get the best results
+ /// from your generations.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to
+ /// [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Audio_API.ipynb)
+ /// or try Stable Audio 2.0 for free at [stableaudio.com](https://stableaudio.com).
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`. The `accept` header should be set to one of the following:
+ /// - `audio/*` to receive the audio in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the audio encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `prompt` - text to generate the audio from. Check our
+ /// [prompt guide](https://www.stableaudio.com/user-guide/text-to-audio) for tips
+ /// #### **Optional Parameters:**
+ /// The body may optionally include:
+ /// - `output_format` - the format of the output audio
+ /// - `seed` - the randomness seed to use for the generation
+ /// - `steps` - the number of sampling steps
+ /// - `duration` - the number of seconds of the generated audio
+ /// - `cfg_scale` - controls how strictly the diffusion process adheres to the prompt text (only for `stable-audio-2`)
+ /// - `model` - the model to use [`stable-audio-2`, `stable-audio-2.5`]
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// **Stable Audio 2.0**
+ /// By default, 20 credits per successful generation. The number of credits is determined
+ /// by the following formula: `credits = 17 + 0.06 * steps`.
+ /// Examples:
+ /// - 50 steps = 20 credits [default]
+ /// - 100 steps = 23 credits
+ /// **Stable Audio 2.5**
+ /// Requests made using the Stable Audio 2.5 model have a flat rate of 20 credits per successful result.
+ /// As always, you will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `audio/*` to receive the bytes of the audio directly. Otherwise specify `application/json` to receive the audio as base64 encoded JSON.
+ /// Default Value: audio/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/audio/stable-audio-2/text-to-audio",
+ /// headers={"authorization": f"Bearer sk-MYAPIKEY", "accept": "audio/*"},
+ /// files={"none": ""},
+ /// data={
+ /// "prompt": "A song in the 3/4 time signature that features cheerful acoustic guitar, live recorded drums, and rhythmic claps, The mood is happy and up-lifting.",
+ /// "output_format": "mp3",
+ /// "duration": 20,
+ /// "model": "stable-audio-2.5",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./output.mp3", "wb") as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateAudioStableAudio2TextToAudioAsBytesAsync( + string contentType, + + global::StabilityAI.CreateAudioStableAudio2TextToAudioRequest request, + global::StabilityAI.CreateAudioStableAudio2TextToAudioAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + var __response = await CreateAudioStableAudio2TextToAudioAsBytesAsResponseAsync( + contentType: contentType, + + request: request, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + requestOptions: requestOptions, + cancellationToken: cancellationToken + ).ConfigureAwait(false); + + return __response.Body; + } + /// + /// Text-to-Audio
+ /// Stable Audio generates high-quality music and sound effects up to three minutes long at
+ /// 44.1kHz stereo from text descriptions. Learn how to craft effective prompts in our
+ /// [Prompt Guide](https://www.stableaudio.com/user-guide/text-to-audio) to get the best results
+ /// from your generations.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to
+ /// [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Audio_API.ipynb)
+ /// or try Stable Audio 2.0 for free at [stableaudio.com](https://stableaudio.com).
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`. The `accept` header should be set to one of the following:
+ /// - `audio/*` to receive the audio in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the audio encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `prompt` - text to generate the audio from. Check our
+ /// [prompt guide](https://www.stableaudio.com/user-guide/text-to-audio) for tips
+ /// #### **Optional Parameters:**
+ /// The body may optionally include:
+ /// - `output_format` - the format of the output audio
+ /// - `seed` - the randomness seed to use for the generation
+ /// - `steps` - the number of sampling steps
+ /// - `duration` - the number of seconds of the generated audio
+ /// - `cfg_scale` - controls how strictly the diffusion process adheres to the prompt text (only for `stable-audio-2`)
+ /// - `model` - the model to use [`stable-audio-2`, `stable-audio-2.5`]
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// **Stable Audio 2.0**
+ /// By default, 20 credits per successful generation. The number of credits is determined
+ /// by the following formula: `credits = 17 + 0.06 * steps`.
+ /// Examples:
+ /// - 50 steps = 20 credits [default]
+ /// - 100 steps = 23 credits
+ /// **Stable Audio 2.5**
+ /// Requests made using the Stable Audio 2.5 model have a flat rate of 20 credits per successful result.
+ /// As always, you will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `audio/*` to receive the bytes of the audio directly. Otherwise specify `application/json` to receive the audio as base64 encoded JSON.
+ /// Default Value: audio/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/audio/stable-audio-2/text-to-audio",
+ /// headers={"authorization": f"Bearer sk-MYAPIKEY", "accept": "audio/*"},
+ /// files={"none": ""},
+ /// data={
+ /// "prompt": "A song in the 3/4 time signature that features cheerful acoustic guitar, live recorded drums, and rhythmic claps, The mood is happy and up-lifting.",
+ /// "output_format": "mp3",
+ /// "duration": 20,
+ /// "model": "stable-audio-2.5",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./output.mp3", "wb") as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateAudioStableAudio2TextToAudioAsBytesAsStreamAsync( + string contentType, + + global::StabilityAI.CreateAudioStableAudio2TextToAudioRequest request, + global::StabilityAI.CreateAudioStableAudio2TextToAudioAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + request = request ?? throw new global::System.ArgumentNullException(nameof(request)); + + PrepareArguments( + client: HttpClient); + PrepareCreateAudioStableAudio2TextToAudioAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateAudioStableAudio2TextToAudioAsBytesSecurityRequirements, + operationName: "CreateAudioStableAudio2TextToAudioAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/audio/stable-audio-2/text-to-audio", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "audio/mpeg"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + if (request.Duration != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Duration, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"duration\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.Steps != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Steps, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"steps\""); + + } + if (request.CfgScale != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.CfgScale, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"cfg_scale\""); + + } + if (request.Model != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.Model).HasValue ? (request.Model).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"model\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateAudioStableAudio2TextToAudioAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2TextToAudioAsBytes", + methodName: "CreateAudioStableAudio2TextToAudioAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/text-to-audio\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseHeadersRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2TextToAudioAsBytes", + methodName: "CreateAudioStableAudio2TextToAudioAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/text-to-audio\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2TextToAudioAsBytes", + methodName: "CreateAudioStableAudio2TextToAudioAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/text-to-audio\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + try + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateAudioStableAudio2TextToAudioAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2TextToAudioAsBytes", + methodName: "CreateAudioStableAudio2TextToAudioAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/text-to-audio\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2TextToAudioAsBytes", + methodName: "CreateAudioStableAudio2TextToAudioAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/text-to-audio\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateAudioStableAudio2TextToAudioResponse3? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateAudioStableAudio2TextToAudioResponse3.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateAudioStableAudio2TextToAudioResponse3.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateAudioStableAudio2TextToAudioResponse4? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateAudioStableAudio2TextToAudioResponse4.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateAudioStableAudio2TextToAudioResponse4.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateAudioStableAudio2TextToAudioResponse5? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateAudioStableAudio2TextToAudioResponse5.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateAudioStableAudio2TextToAudioResponse5.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateAudioStableAudio2TextToAudioResponse6? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateAudioStableAudio2TextToAudioResponse6.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateAudioStableAudio2TextToAudioResponse6.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + try + { + __response.EnsureSuccessStatusCode(); + + var __content = await __response.Content.ReadAsStreamAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.ResponseStream(__response, __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + } + catch + { + __response.Dispose(); + throw; + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Text-to-Audio
+ /// Stable Audio generates high-quality music and sound effects up to three minutes long at
+ /// 44.1kHz stereo from text descriptions. Learn how to craft effective prompts in our
+ /// [Prompt Guide](https://www.stableaudio.com/user-guide/text-to-audio) to get the best results
+ /// from your generations.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to
+ /// [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Audio_API.ipynb)
+ /// or try Stable Audio 2.0 for free at [stableaudio.com](https://stableaudio.com).
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`. The `accept` header should be set to one of the following:
+ /// - `audio/*` to receive the audio in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the audio encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `prompt` - text to generate the audio from. Check our
+ /// [prompt guide](https://www.stableaudio.com/user-guide/text-to-audio) for tips
+ /// #### **Optional Parameters:**
+ /// The body may optionally include:
+ /// - `output_format` - the format of the output audio
+ /// - `seed` - the randomness seed to use for the generation
+ /// - `steps` - the number of sampling steps
+ /// - `duration` - the number of seconds of the generated audio
+ /// - `cfg_scale` - controls how strictly the diffusion process adheres to the prompt text (only for `stable-audio-2`)
+ /// - `model` - the model to use [`stable-audio-2`, `stable-audio-2.5`]
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// **Stable Audio 2.0**
+ /// By default, 20 credits per successful generation. The number of credits is determined
+ /// by the following formula: `credits = 17 + 0.06 * steps`.
+ /// Examples:
+ /// - 50 steps = 20 credits [default]
+ /// - 100 steps = 23 credits
+ /// **Stable Audio 2.5**
+ /// Requests made using the Stable Audio 2.5 model have a flat rate of 20 credits per successful result.
+ /// As always, you will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `audio/*` to receive the bytes of the audio directly. Otherwise specify `application/json` to receive the audio as base64 encoded JSON.
+ /// Default Value: audio/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/audio/stable-audio-2/text-to-audio",
+ /// headers={"authorization": f"Bearer sk-MYAPIKEY", "accept": "audio/*"},
+ /// files={"none": ""},
+ /// data={
+ /// "prompt": "A song in the 3/4 time signature that features cheerful acoustic guitar, live recorded drums, and rhythmic claps, The mood is happy and up-lifting.",
+ /// "output_format": "mp3",
+ /// "duration": 20,
+ /// "model": "stable-audio-2.5",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./output.mp3", "wb") as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task> CreateAudioStableAudio2TextToAudioAsBytesAsResponseAsync( + string contentType, + + global::StabilityAI.CreateAudioStableAudio2TextToAudioRequest request, + global::StabilityAI.CreateAudioStableAudio2TextToAudioAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + request = request ?? throw new global::System.ArgumentNullException(nameof(request)); + + PrepareArguments( + client: HttpClient); + PrepareCreateAudioStableAudio2TextToAudioAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateAudioStableAudio2TextToAudioAsBytesSecurityRequirements, + operationName: "CreateAudioStableAudio2TextToAudioAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/audio/stable-audio-2/text-to-audio", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "audio/mpeg"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + if (request.Duration != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Duration, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"duration\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.Steps != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Steps, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"steps\""); + + } + if (request.CfgScale != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.CfgScale, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"cfg_scale\""); + + } + if (request.Model != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.Model).HasValue ? (request.Model).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"model\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateAudioStableAudio2TextToAudioAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2TextToAudioAsBytes", + methodName: "CreateAudioStableAudio2TextToAudioAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/text-to-audio\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2TextToAudioAsBytes", + methodName: "CreateAudioStableAudio2TextToAudioAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/text-to-audio\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2TextToAudioAsBytes", + methodName: "CreateAudioStableAudio2TextToAudioAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/text-to-audio\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateAudioStableAudio2TextToAudioAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2TextToAudioAsBytes", + methodName: "CreateAudioStableAudio2TextToAudioAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/text-to-audio\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createAudioStableAudio2TextToAudioAsBytes", + methodName: "CreateAudioStableAudio2TextToAudioAsBytesAsync", + pathTemplate: "\"/v2beta/audio/stable-audio-2/text-to-audio\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateAudioStableAudio2TextToAudioResponse3? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateAudioStableAudio2TextToAudioResponse3.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateAudioStableAudio2TextToAudioResponse3.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateAudioStableAudio2TextToAudioResponse4? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateAudioStableAudio2TextToAudioResponse4.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateAudioStableAudio2TextToAudioResponse4.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateAudioStableAudio2TextToAudioResponse5? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateAudioStableAudio2TextToAudioResponse5.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateAudioStableAudio2TextToAudioResponse5.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateAudioStableAudio2TextToAudioResponse6? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateAudioStableAudio2TextToAudioResponse6.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateAudioStableAudio2TextToAudioResponse6.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessCreateAudioStableAudio2TextToAudioAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Text-to-Audio
+ /// Stable Audio generates high-quality music and sound effects up to three minutes long at
+ /// 44.1kHz stereo from text descriptions. Learn how to craft effective prompts in our
+ /// [Prompt Guide](https://www.stableaudio.com/user-guide/text-to-audio) to get the best results
+ /// from your generations.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to
+ /// [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Audio_API.ipynb)
+ /// or try Stable Audio 2.0 for free at [stableaudio.com](https://stableaudio.com).
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`. The `accept` header should be set to one of the following:
+ /// - `audio/*` to receive the audio in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the audio encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `prompt` - text to generate the audio from. Check our
+ /// [prompt guide](https://www.stableaudio.com/user-guide/text-to-audio) for tips
+ /// #### **Optional Parameters:**
+ /// The body may optionally include:
+ /// - `output_format` - the format of the output audio
+ /// - `seed` - the randomness seed to use for the generation
+ /// - `steps` - the number of sampling steps
+ /// - `duration` - the number of seconds of the generated audio
+ /// - `cfg_scale` - controls how strictly the diffusion process adheres to the prompt text (only for `stable-audio-2`)
+ /// - `model` - the model to use [`stable-audio-2`, `stable-audio-2.5`]
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Credits
+ /// **Stable Audio 2.0**
+ /// By default, 20 credits per successful generation. The number of credits is determined
+ /// by the following formula: `credits = 17 + 0.06 * steps`.
+ /// Examples:
+ /// - 50 steps = 20 credits [default]
+ /// - 100 steps = 23 credits
+ /// **Stable Audio 2.5**
+ /// Requests made using the Stable Audio 2.5 model have a flat rate of 20 credits per successful result.
+ /// As always, you will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `audio/*` to receive the bytes of the audio directly. Otherwise specify `application/json` to receive the audio as base64 encoded JSON.
+ /// Default Value: audio/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// What you wish the output audio to be. A strong, descriptive prompt that clearly defines
+ /// instruments, moods, styles, and genre will lead to better results.
+ /// You can make a prompt as simple or complex as you like. Simple prompts are good for clean
+ /// output audio. Complex prompts are good for adding texture and depth to the output audio.
+ /// Check our [prompt guide](https://www.stableaudio.com/user-guide/text-to-audio) for tips. + /// + /// + /// Controls the duration in seconds of the generated audio.
+ /// Default Value: 190 + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Controls the number of sampling steps.
+ /// - For `stable-audio-2`: accepts steps between `30` and `100` (defaults to `50`).
+ /// - For `stable-audio-2.5`: accepts steps between `4` and `8` (defaults to `8`). + /// + /// + /// How strictly the diffusion process adheres to the prompt text (higher values make your
+ /// audio closer to your prompt).
+ /// Defaults to 7 for `stable-audio-2` and 1 for `stable-audio-2.5` if not specified. + /// + /// + /// The model to use for generation.
+ /// - `stable-audio-2.5` requires 20 credits per generation
+ /// - `stable-audio-2` requires 20 credits per generation
+ /// Default Value: stable-audio-2 + /// + /// + /// Dictates the `content-type` of the generated audio.
+ /// Default Value: mp3 + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + public async global::System.Threading.Tasks.Task CreateAudioStableAudio2TextToAudioAsBytesAsync( + string contentType, + string prompt, + global::StabilityAI.CreateAudioStableAudio2TextToAudioAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + double? duration = default, + double? seed = default, + int? steps = default, + double? cfgScale = default, + global::StabilityAI.CreateAudioStableAudio2TextToAudioRequestModel? model = default, + global::StabilityAI.CreateAudioStableAudio2TextToAudioRequestOutputFormat? outputFormat = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + var __request = new global::StabilityAI.CreateAudioStableAudio2TextToAudioRequest + { + Prompt = prompt, + Duration = duration, + Seed = seed, + Steps = steps, + CfgScale = cfgScale, + Model = model, + OutputFormat = outputFormat, + }; + + return await CreateAudioStableAudio2TextToAudioAsBytesAsync( + contentType: contentType, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: __request, + requestOptions: requestOptions, + cancellationToken: cancellationToken).ConfigureAwait(false); + } + } +} \ No newline at end of file diff --git a/src/libs/StabilityAI/Generated/StabilityAI.StableAudioClient.CreateAudioStableAudioAudioToAudio.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.StableAudioClient.CreateAudioStableAudioAudioToAudio.g.cs index 2a6112e..db666b6 100644 --- a/src/libs/StabilityAI/Generated/StabilityAI.StableAudioClient.CreateAudioStableAudioAudioToAudio.g.cs +++ b/src/libs/StabilityAI/Generated/StabilityAI.StableAudioClient.CreateAudioStableAudioAudioToAudio.g.cs @@ -326,42 +326,6 @@ partial void ProcessCreateAudioStableAudioAudioToAudioResponseContent( var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"accept\""); - - } - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } __httpRequestContent.Add( content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), name: "\"prompt\""); @@ -1332,42 +1296,6 @@ request.Audioname is null var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"accept\""); - - } - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } __httpRequestContent.Add( content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), name: "\"prompt\""); @@ -2187,42 +2115,6 @@ request.Audioname is null var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"accept\""); - - } - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } __httpRequestContent.Add( content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), name: "\"prompt\""); diff --git a/src/libs/StabilityAI/Generated/StabilityAI.StableAudioClient.CreateAudioStableAudioInpaint.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.StableAudioClient.CreateAudioStableAudioInpaint.g.cs index fabee85..583a5ea 100644 --- a/src/libs/StabilityAI/Generated/StabilityAI.StableAudioClient.CreateAudioStableAudioInpaint.g.cs +++ b/src/libs/StabilityAI/Generated/StabilityAI.StableAudioClient.CreateAudioStableAudioInpaint.g.cs @@ -324,42 +324,6 @@ partial void ProcessCreateAudioStableAudioInpaintResponseContent( var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"accept\""); - - } - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } __httpRequestContent.Add( content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), name: "\"prompt\""); @@ -1337,42 +1301,6 @@ request.Audioname is null var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"accept\""); - - } - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } __httpRequestContent.Add( content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), name: "\"prompt\""); @@ -2200,42 +2128,6 @@ request.Audioname is null var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"accept\""); - - } - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } __httpRequestContent.Add( content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), name: "\"prompt\""); diff --git a/src/libs/StabilityAI/Generated/StabilityAI.StableAudioClient.CreateAudioStableAudioTextToAudio.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.StableAudioClient.CreateAudioStableAudioTextToAudio.g.cs index 48ed873..3b45f02 100644 --- a/src/libs/StabilityAI/Generated/StabilityAI.StableAudioClient.CreateAudioStableAudioTextToAudio.g.cs +++ b/src/libs/StabilityAI/Generated/StabilityAI.StableAudioClient.CreateAudioStableAudioTextToAudio.g.cs @@ -314,42 +314,6 @@ partial void ProcessCreateAudioStableAudioTextToAudioResponseContent( var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"accept\""); - - } - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } __httpRequestContent.Add( content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), name: "\"prompt\""); diff --git a/src/libs/StabilityAI/Generated/StabilityAI.UpscaleClient.CreateStableImageUpscaleConservative.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.UpscaleClient.CreateStableImageUpscaleConservative.g.cs index 9e366ce..606bcdc 100644 --- a/src/libs/StabilityAI/Generated/StabilityAI.UpscaleClient.CreateStableImageUpscaleConservative.g.cs +++ b/src/libs/StabilityAI/Generated/StabilityAI.UpscaleClient.CreateStableImageUpscaleConservative.g.cs @@ -281,6 +281,10 @@ partial void ProcessCreateStableImageUpscaleConservativeResponseContent( __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || @@ -318,42 +322,6 @@ partial void ProcessCreateStableImageUpscaleConservativeResponseContent( var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"accept\""); - - } - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } var __contentImage = new global::System.Net.Http.ByteArrayContent(request.Image ?? global::System.Array.Empty()); __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( request.Imagename is null @@ -1274,6 +1242,10 @@ request.Imagename is null __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || @@ -1311,42 +1283,6 @@ request.Imagename is null var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"accept\""); - - } - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } var __contentImage = new global::System.Net.Http.StreamContent(image); __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( request.Imagename is null @@ -2125,6 +2061,10 @@ request.Imagename is null __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || @@ -2162,42 +2102,6 @@ request.Imagename is null var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"accept\""); - - } - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } var __contentImage = new global::System.Net.Http.StreamContent(image); __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( request.Imagename is null diff --git a/src/libs/StabilityAI/Generated/StabilityAI.UpscaleClient.CreateStableImageUpscaleConservativeAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.UpscaleClient.CreateStableImageUpscaleConservativeAsBytes.g.cs new file mode 100644 index 0000000..b2f9f95 --- /dev/null +++ b/src/libs/StabilityAI/Generated/StabilityAI.UpscaleClient.CreateStableImageUpscaleConservativeAsBytes.g.cs @@ -0,0 +1,4174 @@ + +#nullable enable + +namespace StabilityAI +{ + public partial class UpscaleClient + { + + + private static readonly global::StabilityAI.EndPointSecurityRequirement s_CreateStableImageUpscaleConservativeAsBytesSecurityRequirement0 = + new global::StabilityAI.EndPointSecurityRequirement + { + Authorizations = new global::StabilityAI.EndPointAuthorizationRequirement[] + { new global::StabilityAI.EndPointAuthorizationRequirement + { + Type = "Http", + SchemeId = "HttpBearer", + Location = "Header", + Name = "Bearer", + FriendlyName = "Bearer", + }, + }, + }; + private static readonly global::StabilityAI.EndPointSecurityRequirement[] s_CreateStableImageUpscaleConservativeAsBytesSecurityRequirements = + new global::StabilityAI.EndPointSecurityRequirement[] + { s_CreateStableImageUpscaleConservativeAsBytesSecurityRequirement0, + }; + partial void PrepareCreateStableImageUpscaleConservativeAsBytesArguments( + global::System.Net.Http.HttpClient httpClient, + ref string contentType, + ref global::StabilityAI.CreateStableImageUpscaleConservativeAccept? accept, + ref string? stabilityClientId, + ref string? stabilityClientUserId, + ref string? stabilityClientVersion, + global::StabilityAI.CreateStableImageUpscaleConservativeRequest request); + partial void PrepareCreateStableImageUpscaleConservativeAsBytesRequest( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpRequestMessage httpRequestMessage, + string contentType, + global::StabilityAI.CreateStableImageUpscaleConservativeAccept? accept, + string? stabilityClientId, + string? stabilityClientUserId, + string? stabilityClientVersion, + global::StabilityAI.CreateStableImageUpscaleConservativeRequest request); + partial void ProcessCreateStableImageUpscaleConservativeAsBytesResponse( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpResponseMessage httpResponseMessage); + + partial void ProcessCreateStableImageUpscaleConservativeAsBytesResponseContent( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpResponseMessage httpResponseMessage, + ref byte[] content); + + /// + /// Conservative
+ /// Takes images between 64x64 and 1 megapixel and upscales them all the way to 4K resolution. Put more generally, it can upscale images ~20-40x times while preserving all aspects. Conservative Upscale minimizes alterations to the image and should not be used to reimagine an image.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// - `prompt`
+ /// Optionally, the body of the request may also include:
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `creativity`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 40 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/upscale/conservative",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./low-res-flower.jpg", "rb"),
+ /// },
+ /// data={
+ /// "prompt": "a flower",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./flower.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateStableImageUpscaleConservativeAsBytesAsync( + string contentType, + + global::StabilityAI.CreateStableImageUpscaleConservativeRequest request, + global::StabilityAI.CreateStableImageUpscaleConservativeAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + var __response = await CreateStableImageUpscaleConservativeAsBytesAsResponseAsync( + contentType: contentType, + + request: request, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + requestOptions: requestOptions, + cancellationToken: cancellationToken + ).ConfigureAwait(false); + + return __response.Body; + } + /// + /// Conservative
+ /// Takes images between 64x64 and 1 megapixel and upscales them all the way to 4K resolution. Put more generally, it can upscale images ~20-40x times while preserving all aspects. Conservative Upscale minimizes alterations to the image and should not be used to reimagine an image.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// - `prompt`
+ /// Optionally, the body of the request may also include:
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `creativity`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 40 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/upscale/conservative",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./low-res-flower.jpg", "rb"),
+ /// },
+ /// data={
+ /// "prompt": "a flower",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./flower.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateStableImageUpscaleConservativeAsBytesAsStreamAsync( + string contentType, + + global::StabilityAI.CreateStableImageUpscaleConservativeRequest request, + global::StabilityAI.CreateStableImageUpscaleConservativeAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + request = request ?? throw new global::System.ArgumentNullException(nameof(request)); + + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageUpscaleConservativeAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageUpscaleConservativeAsBytesSecurityRequirements, + operationName: "CreateStableImageUpscaleConservativeAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/upscale/conservative", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/jpeg"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + var __contentImage = new global::System.Net.Http.ByteArrayContent(request.Image ?? global::System.Array.Empty()); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + if (request.NegativePrompt != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty), + name: "\"negative_prompt\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + if (request.Creativity != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Creativity, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"creativity\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageUpscaleConservativeAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageUpscaleConservativeAsBytes", + methodName: "CreateStableImageUpscaleConservativeAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/upscale/conservative\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseHeadersRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageUpscaleConservativeAsBytes", + methodName: "CreateStableImageUpscaleConservativeAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/upscale/conservative\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageUpscaleConservativeAsBytes", + methodName: "CreateStableImageUpscaleConservativeAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/upscale/conservative\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + try + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageUpscaleConservativeAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageUpscaleConservativeAsBytes", + methodName: "CreateStableImageUpscaleConservativeAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/upscale/conservative\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageUpscaleConservativeAsBytes", + methodName: "CreateStableImageUpscaleConservativeAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/upscale/conservative\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageUpscaleConservativeResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageUpscaleConservativeResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageUpscaleConservativeResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageUpscaleConservativeResponse5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageUpscaleConservativeResponse5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageUpscaleConservativeResponse5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateStableImageUpscaleConservativeResponse6? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateStableImageUpscaleConservativeResponse6.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateStableImageUpscaleConservativeResponse6.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageUpscaleConservativeResponse7? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageUpscaleConservativeResponse7.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageUpscaleConservativeResponse7.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageUpscaleConservativeResponse8? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageUpscaleConservativeResponse8.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageUpscaleConservativeResponse8.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + try + { + __response.EnsureSuccessStatusCode(); + + var __content = await __response.Content.ReadAsStreamAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.ResponseStream(__response, __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + } + catch + { + __response.Dispose(); + throw; + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Conservative
+ /// Takes images between 64x64 and 1 megapixel and upscales them all the way to 4K resolution. Put more generally, it can upscale images ~20-40x times while preserving all aspects. Conservative Upscale minimizes alterations to the image and should not be used to reimagine an image.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// - `prompt`
+ /// Optionally, the body of the request may also include:
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `creativity`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 40 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/upscale/conservative",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./low-res-flower.jpg", "rb"),
+ /// },
+ /// data={
+ /// "prompt": "a flower",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./flower.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task> CreateStableImageUpscaleConservativeAsBytesAsResponseAsync( + string contentType, + + global::StabilityAI.CreateStableImageUpscaleConservativeRequest request, + global::StabilityAI.CreateStableImageUpscaleConservativeAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + request = request ?? throw new global::System.ArgumentNullException(nameof(request)); + + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageUpscaleConservativeAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageUpscaleConservativeAsBytesSecurityRequirements, + operationName: "CreateStableImageUpscaleConservativeAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/upscale/conservative", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/jpeg"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + var __contentImage = new global::System.Net.Http.ByteArrayContent(request.Image ?? global::System.Array.Empty()); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + if (request.NegativePrompt != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty), + name: "\"negative_prompt\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + if (request.Creativity != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Creativity, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"creativity\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageUpscaleConservativeAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageUpscaleConservativeAsBytes", + methodName: "CreateStableImageUpscaleConservativeAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/upscale/conservative\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageUpscaleConservativeAsBytes", + methodName: "CreateStableImageUpscaleConservativeAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/upscale/conservative\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageUpscaleConservativeAsBytes", + methodName: "CreateStableImageUpscaleConservativeAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/upscale/conservative\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageUpscaleConservativeAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageUpscaleConservativeAsBytes", + methodName: "CreateStableImageUpscaleConservativeAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/upscale/conservative\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageUpscaleConservativeAsBytes", + methodName: "CreateStableImageUpscaleConservativeAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/upscale/conservative\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageUpscaleConservativeResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageUpscaleConservativeResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageUpscaleConservativeResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageUpscaleConservativeResponse5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageUpscaleConservativeResponse5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageUpscaleConservativeResponse5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateStableImageUpscaleConservativeResponse6? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateStableImageUpscaleConservativeResponse6.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateStableImageUpscaleConservativeResponse6.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageUpscaleConservativeResponse7? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageUpscaleConservativeResponse7.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageUpscaleConservativeResponse7.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageUpscaleConservativeResponse8? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageUpscaleConservativeResponse8.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageUpscaleConservativeResponse8.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessCreateStableImageUpscaleConservativeAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Conservative
+ /// Takes images between 64x64 and 1 megapixel and upscales them all the way to 4K resolution. Put more generally, it can upscale images ~20-40x times while preserving all aspects. Conservative Upscale minimizes alterations to the image and should not be used to reimagine an image.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// - `prompt`
+ /// Optionally, the body of the request may also include:
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `creativity`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 40 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// The image you wish to upscale.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// The image you wish to upscale.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Controls the likelihood of creating additional details not heavily conditioned by the init image.
+ /// Default Value: 0.35F + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + public async global::System.Threading.Tasks.Task CreateStableImageUpscaleConservativeAsBytesAsync( + string contentType, + byte[] image, + string imagename, + string prompt, + global::StabilityAI.CreateStableImageUpscaleConservativeAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + string? negativePrompt = default, + double? seed = default, + global::StabilityAI.CreateStableImageUpscaleConservativeRequestOutputFormat? outputFormat = default, + double? creativity = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + var __request = new global::StabilityAI.CreateStableImageUpscaleConservativeRequest + { + Image = image, + Imagename = imagename, + Prompt = prompt, + NegativePrompt = negativePrompt, + Seed = seed, + OutputFormat = outputFormat, + Creativity = creativity, + }; + + return await CreateStableImageUpscaleConservativeAsBytesAsync( + contentType: contentType, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: __request, + requestOptions: requestOptions, + cancellationToken: cancellationToken).ConfigureAwait(false); + } + + /// + /// Conservative
+ /// Takes images between 64x64 and 1 megapixel and upscales them all the way to 4K resolution. Put more generally, it can upscale images ~20-40x times while preserving all aspects. Conservative Upscale minimizes alterations to the image and should not be used to reimagine an image.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// - `prompt`
+ /// Optionally, the body of the request may also include:
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `creativity`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 40 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// The image you wish to upscale.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// The image you wish to upscale.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Controls the likelihood of creating additional details not heavily conditioned by the init image.
+ /// Default Value: 0.35F + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/upscale/conservative",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./low-res-flower.jpg", "rb"),
+ /// },
+ /// data={
+ /// "prompt": "a flower",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./flower.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateStableImageUpscaleConservativeAsBytesAsync( + string contentType, + global::System.IO.Stream image, + string imagename, + string prompt, + global::StabilityAI.CreateStableImageUpscaleConservativeAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + string? negativePrompt = default, + double? seed = default, + global::StabilityAI.CreateStableImageUpscaleConservativeRequestOutputFormat? outputFormat = default, + double? creativity = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + + image = image ?? throw new global::System.ArgumentNullException(nameof(image)); + var request = new global::StabilityAI.CreateStableImageUpscaleConservativeRequest + { + Image = global::System.Array.Empty(), + Imagename = imagename, + Prompt = prompt, + NegativePrompt = negativePrompt, + Seed = seed, + OutputFormat = outputFormat, + Creativity = creativity, + }; + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageUpscaleConservativeAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageUpscaleConservativeAsBytesSecurityRequirements, + operationName: "CreateStableImageUpscaleConservativeAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/upscale/conservative", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/jpeg"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + var __contentImage = new global::System.Net.Http.StreamContent(image); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + if (request.NegativePrompt != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty), + name: "\"negative_prompt\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + if (request.Creativity != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Creativity, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"creativity\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageUpscaleConservativeAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageUpscaleConservativeAsBytes", + methodName: "CreateStableImageUpscaleConservativeAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/upscale/conservative\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageUpscaleConservativeAsBytes", + methodName: "CreateStableImageUpscaleConservativeAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/upscale/conservative\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageUpscaleConservativeAsBytes", + methodName: "CreateStableImageUpscaleConservativeAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/upscale/conservative\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageUpscaleConservativeAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageUpscaleConservativeAsBytes", + methodName: "CreateStableImageUpscaleConservativeAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/upscale/conservative\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageUpscaleConservativeAsBytes", + methodName: "CreateStableImageUpscaleConservativeAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/upscale/conservative\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageUpscaleConservativeResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageUpscaleConservativeResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageUpscaleConservativeResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageUpscaleConservativeResponse5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageUpscaleConservativeResponse5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageUpscaleConservativeResponse5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateStableImageUpscaleConservativeResponse6? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateStableImageUpscaleConservativeResponse6.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateStableImageUpscaleConservativeResponse6.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageUpscaleConservativeResponse7? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageUpscaleConservativeResponse7.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageUpscaleConservativeResponse7.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageUpscaleConservativeResponse8? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageUpscaleConservativeResponse8.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageUpscaleConservativeResponse8.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessCreateStableImageUpscaleConservativeAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return __content; + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return __content; + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Conservative
+ /// Takes images between 64x64 and 1 megapixel and upscales them all the way to 4K resolution. Put more generally, it can upscale images ~20-40x times while preserving all aspects. Conservative Upscale minimizes alterations to the image and should not be used to reimagine an image.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// - `prompt`
+ /// Optionally, the body of the request may also include:
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `creativity`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 40 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// The image you wish to upscale.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// The image you wish to upscale.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Controls the likelihood of creating additional details not heavily conditioned by the init image.
+ /// Default Value: 0.35F + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/upscale/conservative",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./low-res-flower.jpg", "rb"),
+ /// },
+ /// data={
+ /// "prompt": "a flower",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./flower.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateStableImageUpscaleConservativeAsBytesAsStreamAsync( + string contentType, + global::System.IO.Stream image, + string imagename, + string prompt, + global::StabilityAI.CreateStableImageUpscaleConservativeAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + string? negativePrompt = default, + double? seed = default, + global::StabilityAI.CreateStableImageUpscaleConservativeRequestOutputFormat? outputFormat = default, + double? creativity = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + + image = image ?? throw new global::System.ArgumentNullException(nameof(image)); + var request = new global::StabilityAI.CreateStableImageUpscaleConservativeRequest + { + Image = global::System.Array.Empty(), + Imagename = imagename, + Prompt = prompt, + NegativePrompt = negativePrompt, + Seed = seed, + OutputFormat = outputFormat, + Creativity = creativity, + }; + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageUpscaleConservativeAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageUpscaleConservativeAsBytesSecurityRequirements, + operationName: "CreateStableImageUpscaleConservativeAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/upscale/conservative", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/jpeg"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + var __contentImage = new global::System.Net.Http.StreamContent(image); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + if (request.NegativePrompt != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty), + name: "\"negative_prompt\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + if (request.Creativity != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Creativity, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"creativity\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageUpscaleConservativeAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageUpscaleConservativeAsBytes", + methodName: "CreateStableImageUpscaleConservativeAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/upscale/conservative\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseHeadersRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageUpscaleConservativeAsBytes", + methodName: "CreateStableImageUpscaleConservativeAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/upscale/conservative\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageUpscaleConservativeAsBytes", + methodName: "CreateStableImageUpscaleConservativeAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/upscale/conservative\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + try + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageUpscaleConservativeAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageUpscaleConservativeAsBytes", + methodName: "CreateStableImageUpscaleConservativeAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/upscale/conservative\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageUpscaleConservativeAsBytes", + methodName: "CreateStableImageUpscaleConservativeAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/upscale/conservative\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageUpscaleConservativeResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageUpscaleConservativeResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageUpscaleConservativeResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageUpscaleConservativeResponse5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageUpscaleConservativeResponse5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageUpscaleConservativeResponse5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateStableImageUpscaleConservativeResponse6? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateStableImageUpscaleConservativeResponse6.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateStableImageUpscaleConservativeResponse6.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageUpscaleConservativeResponse7? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageUpscaleConservativeResponse7.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageUpscaleConservativeResponse7.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageUpscaleConservativeResponse8? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageUpscaleConservativeResponse8.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageUpscaleConservativeResponse8.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + try + { + __response.EnsureSuccessStatusCode(); + + var __content = await __response.Content.ReadAsStreamAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.ResponseStream(__response, __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + } + catch + { + __response.Dispose(); + throw; + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Conservative
+ /// Takes images between 64x64 and 1 megapixel and upscales them all the way to 4K resolution. Put more generally, it can upscale images ~20-40x times while preserving all aspects. Conservative Upscale minimizes alterations to the image and should not be used to reimagine an image.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// - `prompt`
+ /// Optionally, the body of the request may also include:
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `creativity`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 40 credits per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// The image you wish to upscale.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// The image you wish to upscale.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png + /// + /// + /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue. + /// + /// + /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature. + /// + /// + /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0 + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// + /// Controls the likelihood of creating additional details not heavily conditioned by the init image.
+ /// Default Value: 0.35F + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/upscale/conservative",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./low-res-flower.jpg", "rb"),
+ /// },
+ /// data={
+ /// "prompt": "a flower",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./flower.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task> CreateStableImageUpscaleConservativeAsBytesAsResponseAsync( + string contentType, + global::System.IO.Stream image, + string imagename, + string prompt, + global::StabilityAI.CreateStableImageUpscaleConservativeAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + string? negativePrompt = default, + double? seed = default, + global::StabilityAI.CreateStableImageUpscaleConservativeRequestOutputFormat? outputFormat = default, + double? creativity = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + + image = image ?? throw new global::System.ArgumentNullException(nameof(image)); + var request = new global::StabilityAI.CreateStableImageUpscaleConservativeRequest + { + Image = global::System.Array.Empty(), + Imagename = imagename, + Prompt = prompt, + NegativePrompt = negativePrompt, + Seed = seed, + OutputFormat = outputFormat, + Creativity = creativity, + }; + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageUpscaleConservativeAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageUpscaleConservativeAsBytesSecurityRequirements, + operationName: "CreateStableImageUpscaleConservativeAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/upscale/conservative", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/jpeg"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + var __contentImage = new global::System.Net.Http.StreamContent(image); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty), + name: "\"prompt\""); + + if (request.NegativePrompt != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty), + name: "\"negative_prompt\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + if (request.Creativity != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Creativity, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"creativity\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageUpscaleConservativeAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageUpscaleConservativeAsBytes", + methodName: "CreateStableImageUpscaleConservativeAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/upscale/conservative\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageUpscaleConservativeAsBytes", + methodName: "CreateStableImageUpscaleConservativeAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/upscale/conservative\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageUpscaleConservativeAsBytes", + methodName: "CreateStableImageUpscaleConservativeAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/upscale/conservative\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageUpscaleConservativeAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageUpscaleConservativeAsBytes", + methodName: "CreateStableImageUpscaleConservativeAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/upscale/conservative\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageUpscaleConservativeAsBytes", + methodName: "CreateStableImageUpscaleConservativeAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/upscale/conservative\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageUpscaleConservativeResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageUpscaleConservativeResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageUpscaleConservativeResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageUpscaleConservativeResponse5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageUpscaleConservativeResponse5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageUpscaleConservativeResponse5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateStableImageUpscaleConservativeResponse6? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateStableImageUpscaleConservativeResponse6.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateStableImageUpscaleConservativeResponse6.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageUpscaleConservativeResponse7? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageUpscaleConservativeResponse7.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageUpscaleConservativeResponse7.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageUpscaleConservativeResponse8? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageUpscaleConservativeResponse8.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageUpscaleConservativeResponse8.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessCreateStableImageUpscaleConservativeAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + } +} \ No newline at end of file diff --git a/src/libs/StabilityAI/Generated/StabilityAI.UpscaleClient.CreateStableImageUpscaleCreative.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.UpscaleClient.CreateStableImageUpscaleCreative.g.cs index ece3c1a..fe949ab 100644 --- a/src/libs/StabilityAI/Generated/StabilityAI.UpscaleClient.CreateStableImageUpscaleCreative.g.cs +++ b/src/libs/StabilityAI/Generated/StabilityAI.UpscaleClient.CreateStableImageUpscaleCreative.g.cs @@ -298,34 +298,6 @@ partial void ProcessCreateStableImageUpscaleCreativeResponseContent( var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } var __contentImage = new global::System.Net.Http.ByteArrayContent(request.Image ?? global::System.Array.Empty()); __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( request.Imagename is null @@ -1284,34 +1256,6 @@ request.Imagename is null var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } var __contentImage = new global::System.Net.Http.StreamContent(image); __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( request.Imagename is null @@ -2127,34 +2071,6 @@ request.Imagename is null var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } var __contentImage = new global::System.Net.Http.StreamContent(image); __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( request.Imagename is null diff --git a/src/libs/StabilityAI/Generated/StabilityAI.UpscaleClient.CreateStableImageUpscaleFast.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.UpscaleClient.CreateStableImageUpscaleFast.g.cs index 6329ea3..fb5829d 100644 --- a/src/libs/StabilityAI/Generated/StabilityAI.UpscaleClient.CreateStableImageUpscaleFast.g.cs +++ b/src/libs/StabilityAI/Generated/StabilityAI.UpscaleClient.CreateStableImageUpscaleFast.g.cs @@ -271,6 +271,10 @@ partial void ProcessCreateStableImageUpscaleFastResponseContent( __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || @@ -308,42 +312,6 @@ partial void ProcessCreateStableImageUpscaleFastResponseContent( var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"accept\""); - - } - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } var __contentImage = new global::System.Net.Http.ByteArrayContent(request.Image ?? global::System.Array.Empty()); __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( request.Imagename is null @@ -1171,6 +1139,10 @@ request.Imagename is null __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || @@ -1208,42 +1180,6 @@ request.Imagename is null var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"accept\""); - - } - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } var __contentImage = new global::System.Net.Http.StreamContent(image); __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( request.Imagename is null @@ -1961,6 +1897,10 @@ request.Imagename is null __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || @@ -1998,42 +1938,6 @@ request.Imagename is null var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"accept\""); - - } - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } var __contentImage = new global::System.Net.Http.StreamContent(image); __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( request.Imagename is null diff --git a/src/libs/StabilityAI/Generated/StabilityAI.UpscaleClient.CreateStableImageUpscaleFastAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.UpscaleClient.CreateStableImageUpscaleFastAsBytes.g.cs new file mode 100644 index 0000000..c7c6abd --- /dev/null +++ b/src/libs/StabilityAI/Generated/StabilityAI.UpscaleClient.CreateStableImageUpscaleFastAsBytes.g.cs @@ -0,0 +1,3888 @@ + +#nullable enable + +namespace StabilityAI +{ + public partial class UpscaleClient + { + + + private static readonly global::StabilityAI.EndPointSecurityRequirement s_CreateStableImageUpscaleFastAsBytesSecurityRequirement0 = + new global::StabilityAI.EndPointSecurityRequirement + { + Authorizations = new global::StabilityAI.EndPointAuthorizationRequirement[] + { new global::StabilityAI.EndPointAuthorizationRequirement + { + Type = "Http", + SchemeId = "HttpBearer", + Location = "Header", + Name = "Bearer", + FriendlyName = "Bearer", + }, + }, + }; + private static readonly global::StabilityAI.EndPointSecurityRequirement[] s_CreateStableImageUpscaleFastAsBytesSecurityRequirements = + new global::StabilityAI.EndPointSecurityRequirement[] + { s_CreateStableImageUpscaleFastAsBytesSecurityRequirement0, + }; + partial void PrepareCreateStableImageUpscaleFastAsBytesArguments( + global::System.Net.Http.HttpClient httpClient, + ref string contentType, + ref global::StabilityAI.CreateStableImageUpscaleFastAccept? accept, + ref string? stabilityClientId, + ref string? stabilityClientUserId, + ref string? stabilityClientVersion, + global::StabilityAI.CreateStableImageUpscaleFastRequest request); + partial void PrepareCreateStableImageUpscaleFastAsBytesRequest( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpRequestMessage httpRequestMessage, + string contentType, + global::StabilityAI.CreateStableImageUpscaleFastAccept? accept, + string? stabilityClientId, + string? stabilityClientUserId, + string? stabilityClientVersion, + global::StabilityAI.CreateStableImageUpscaleFastRequest request); + partial void ProcessCreateStableImageUpscaleFastAsBytesResponse( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpResponseMessage httpResponseMessage); + + partial void ProcessCreateStableImageUpscaleFastAsBytesResponseContent( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpResponseMessage httpResponseMessage, + ref byte[] content); + + /// + /// Fast
+ /// Our Fast Upscaler service enhances image resolution by 4x using predictive and generative AI. This lightweight and fast service (processing in ~1 second) is ideal for enhancing the quality of compressed images, making it suitable for social media posts and other applications.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// Optionally, the body of the request may also include:
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image is 4 times that of the input image with a maximum size of 16 megapixels.
+ /// ### Credits
+ /// Flat rate of 2 credit per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/upscale/fast",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./low-res-flower.jpg", "rb"),
+ /// },
+ /// data={
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./flower.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateStableImageUpscaleFastAsBytesAsync( + string contentType, + + global::StabilityAI.CreateStableImageUpscaleFastRequest request, + global::StabilityAI.CreateStableImageUpscaleFastAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + var __response = await CreateStableImageUpscaleFastAsBytesAsResponseAsync( + contentType: contentType, + + request: request, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + requestOptions: requestOptions, + cancellationToken: cancellationToken + ).ConfigureAwait(false); + + return __response.Body; + } + /// + /// Fast
+ /// Our Fast Upscaler service enhances image resolution by 4x using predictive and generative AI. This lightweight and fast service (processing in ~1 second) is ideal for enhancing the quality of compressed images, making it suitable for social media posts and other applications.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// Optionally, the body of the request may also include:
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image is 4 times that of the input image with a maximum size of 16 megapixels.
+ /// ### Credits
+ /// Flat rate of 2 credit per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/upscale/fast",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./low-res-flower.jpg", "rb"),
+ /// },
+ /// data={
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./flower.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateStableImageUpscaleFastAsBytesAsStreamAsync( + string contentType, + + global::StabilityAI.CreateStableImageUpscaleFastRequest request, + global::StabilityAI.CreateStableImageUpscaleFastAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + request = request ?? throw new global::System.ArgumentNullException(nameof(request)); + + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageUpscaleFastAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageUpscaleFastAsBytesSecurityRequirements, + operationName: "CreateStableImageUpscaleFastAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/upscale/fast", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/jpeg"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + var __contentImage = new global::System.Net.Http.ByteArrayContent(request.Image ?? global::System.Array.Empty()); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageUpscaleFastAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageUpscaleFastAsBytes", + methodName: "CreateStableImageUpscaleFastAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/upscale/fast\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseHeadersRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageUpscaleFastAsBytes", + methodName: "CreateStableImageUpscaleFastAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/upscale/fast\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageUpscaleFastAsBytes", + methodName: "CreateStableImageUpscaleFastAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/upscale/fast\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + try + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageUpscaleFastAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageUpscaleFastAsBytes", + methodName: "CreateStableImageUpscaleFastAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/upscale/fast\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageUpscaleFastAsBytes", + methodName: "CreateStableImageUpscaleFastAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/upscale/fast\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageUpscaleFastResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageUpscaleFastResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageUpscaleFastResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageUpscaleFastResponse5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageUpscaleFastResponse5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageUpscaleFastResponse5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateStableImageUpscaleFastResponse6? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateStableImageUpscaleFastResponse6.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateStableImageUpscaleFastResponse6.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageUpscaleFastResponse7? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageUpscaleFastResponse7.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageUpscaleFastResponse7.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageUpscaleFastResponse8? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageUpscaleFastResponse8.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageUpscaleFastResponse8.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + try + { + __response.EnsureSuccessStatusCode(); + + var __content = await __response.Content.ReadAsStreamAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.ResponseStream(__response, __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + } + catch + { + __response.Dispose(); + throw; + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Fast
+ /// Our Fast Upscaler service enhances image resolution by 4x using predictive and generative AI. This lightweight and fast service (processing in ~1 second) is ideal for enhancing the quality of compressed images, making it suitable for social media posts and other applications.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// Optionally, the body of the request may also include:
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image is 4 times that of the input image with a maximum size of 16 megapixels.
+ /// ### Credits
+ /// Flat rate of 2 credit per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/upscale/fast",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./low-res-flower.jpg", "rb"),
+ /// },
+ /// data={
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./flower.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task> CreateStableImageUpscaleFastAsBytesAsResponseAsync( + string contentType, + + global::StabilityAI.CreateStableImageUpscaleFastRequest request, + global::StabilityAI.CreateStableImageUpscaleFastAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + request = request ?? throw new global::System.ArgumentNullException(nameof(request)); + + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageUpscaleFastAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageUpscaleFastAsBytesSecurityRequirements, + operationName: "CreateStableImageUpscaleFastAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/upscale/fast", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/jpeg"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + var __contentImage = new global::System.Net.Http.ByteArrayContent(request.Image ?? global::System.Array.Empty()); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageUpscaleFastAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageUpscaleFastAsBytes", + methodName: "CreateStableImageUpscaleFastAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/upscale/fast\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageUpscaleFastAsBytes", + methodName: "CreateStableImageUpscaleFastAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/upscale/fast\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageUpscaleFastAsBytes", + methodName: "CreateStableImageUpscaleFastAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/upscale/fast\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageUpscaleFastAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageUpscaleFastAsBytes", + methodName: "CreateStableImageUpscaleFastAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/upscale/fast\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageUpscaleFastAsBytes", + methodName: "CreateStableImageUpscaleFastAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/upscale/fast\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageUpscaleFastResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageUpscaleFastResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageUpscaleFastResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageUpscaleFastResponse5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageUpscaleFastResponse5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageUpscaleFastResponse5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateStableImageUpscaleFastResponse6? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateStableImageUpscaleFastResponse6.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateStableImageUpscaleFastResponse6.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageUpscaleFastResponse7? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageUpscaleFastResponse7.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageUpscaleFastResponse7.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageUpscaleFastResponse8? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageUpscaleFastResponse8.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageUpscaleFastResponse8.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessCreateStableImageUpscaleFastAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Fast
+ /// Our Fast Upscaler service enhances image resolution by 4x using predictive and generative AI. This lightweight and fast service (processing in ~1 second) is ideal for enhancing the quality of compressed images, making it suitable for social media posts and other applications.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// Optionally, the body of the request may also include:
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image is 4 times that of the input image with a maximum size of 16 megapixels.
+ /// ### Credits
+ /// Flat rate of 2 credit per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// The image you wish to upscale.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 32 and 1,536 pixels
+ /// - Height must be between 32 and 1,536 pixels
+ /// - Total pixel count must be between 1,024 and 1,048,576 pixels
+ /// Example: ./some/image.png + /// + /// + /// The image you wish to upscale.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 32 and 1,536 pixels
+ /// - Height must be between 32 and 1,536 pixels
+ /// - Total pixel count must be between 1,024 and 1,048,576 pixels
+ /// Example: ./some/image.png + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + public async global::System.Threading.Tasks.Task CreateStableImageUpscaleFastAsBytesAsync( + string contentType, + byte[] image, + string imagename, + global::StabilityAI.CreateStableImageUpscaleFastAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.CreateStableImageUpscaleFastRequestOutputFormat? outputFormat = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + var __request = new global::StabilityAI.CreateStableImageUpscaleFastRequest + { + Image = image, + Imagename = imagename, + OutputFormat = outputFormat, + }; + + return await CreateStableImageUpscaleFastAsBytesAsync( + contentType: contentType, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: __request, + requestOptions: requestOptions, + cancellationToken: cancellationToken).ConfigureAwait(false); + } + + /// + /// Fast
+ /// Our Fast Upscaler service enhances image resolution by 4x using predictive and generative AI. This lightweight and fast service (processing in ~1 second) is ideal for enhancing the quality of compressed images, making it suitable for social media posts and other applications.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// Optionally, the body of the request may also include:
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image is 4 times that of the input image with a maximum size of 16 megapixels.
+ /// ### Credits
+ /// Flat rate of 2 credit per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// The image you wish to upscale.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 32 and 1,536 pixels
+ /// - Height must be between 32 and 1,536 pixels
+ /// - Total pixel count must be between 1,024 and 1,048,576 pixels
+ /// Example: ./some/image.png + /// + /// + /// The image you wish to upscale.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 32 and 1,536 pixels
+ /// - Height must be between 32 and 1,536 pixels
+ /// - Total pixel count must be between 1,024 and 1,048,576 pixels
+ /// Example: ./some/image.png + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/upscale/fast",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./low-res-flower.jpg", "rb"),
+ /// },
+ /// data={
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./flower.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateStableImageUpscaleFastAsBytesAsync( + string contentType, + global::System.IO.Stream image, + string imagename, + global::StabilityAI.CreateStableImageUpscaleFastAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.CreateStableImageUpscaleFastRequestOutputFormat? outputFormat = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + + image = image ?? throw new global::System.ArgumentNullException(nameof(image)); + var request = new global::StabilityAI.CreateStableImageUpscaleFastRequest + { + Image = global::System.Array.Empty(), + Imagename = imagename, + OutputFormat = outputFormat, + }; + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageUpscaleFastAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageUpscaleFastAsBytesSecurityRequirements, + operationName: "CreateStableImageUpscaleFastAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/upscale/fast", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/jpeg"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + var __contentImage = new global::System.Net.Http.StreamContent(image); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageUpscaleFastAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageUpscaleFastAsBytes", + methodName: "CreateStableImageUpscaleFastAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/upscale/fast\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageUpscaleFastAsBytes", + methodName: "CreateStableImageUpscaleFastAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/upscale/fast\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageUpscaleFastAsBytes", + methodName: "CreateStableImageUpscaleFastAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/upscale/fast\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageUpscaleFastAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageUpscaleFastAsBytes", + methodName: "CreateStableImageUpscaleFastAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/upscale/fast\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageUpscaleFastAsBytes", + methodName: "CreateStableImageUpscaleFastAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/upscale/fast\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageUpscaleFastResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageUpscaleFastResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageUpscaleFastResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageUpscaleFastResponse5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageUpscaleFastResponse5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageUpscaleFastResponse5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateStableImageUpscaleFastResponse6? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateStableImageUpscaleFastResponse6.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateStableImageUpscaleFastResponse6.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageUpscaleFastResponse7? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageUpscaleFastResponse7.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageUpscaleFastResponse7.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageUpscaleFastResponse8? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageUpscaleFastResponse8.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageUpscaleFastResponse8.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessCreateStableImageUpscaleFastAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return __content; + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return __content; + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Fast
+ /// Our Fast Upscaler service enhances image resolution by 4x using predictive and generative AI. This lightweight and fast service (processing in ~1 second) is ideal for enhancing the quality of compressed images, making it suitable for social media posts and other applications.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// Optionally, the body of the request may also include:
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image is 4 times that of the input image with a maximum size of 16 megapixels.
+ /// ### Credits
+ /// Flat rate of 2 credit per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// The image you wish to upscale.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 32 and 1,536 pixels
+ /// - Height must be between 32 and 1,536 pixels
+ /// - Total pixel count must be between 1,024 and 1,048,576 pixels
+ /// Example: ./some/image.png + /// + /// + /// The image you wish to upscale.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 32 and 1,536 pixels
+ /// - Height must be between 32 and 1,536 pixels
+ /// - Total pixel count must be between 1,024 and 1,048,576 pixels
+ /// Example: ./some/image.png + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/upscale/fast",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./low-res-flower.jpg", "rb"),
+ /// },
+ /// data={
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./flower.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateStableImageUpscaleFastAsBytesAsStreamAsync( + string contentType, + global::System.IO.Stream image, + string imagename, + global::StabilityAI.CreateStableImageUpscaleFastAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.CreateStableImageUpscaleFastRequestOutputFormat? outputFormat = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + + image = image ?? throw new global::System.ArgumentNullException(nameof(image)); + var request = new global::StabilityAI.CreateStableImageUpscaleFastRequest + { + Image = global::System.Array.Empty(), + Imagename = imagename, + OutputFormat = outputFormat, + }; + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageUpscaleFastAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageUpscaleFastAsBytesSecurityRequirements, + operationName: "CreateStableImageUpscaleFastAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/upscale/fast", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/jpeg"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + var __contentImage = new global::System.Net.Http.StreamContent(image); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageUpscaleFastAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageUpscaleFastAsBytes", + methodName: "CreateStableImageUpscaleFastAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/upscale/fast\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseHeadersRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageUpscaleFastAsBytes", + methodName: "CreateStableImageUpscaleFastAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/upscale/fast\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageUpscaleFastAsBytes", + methodName: "CreateStableImageUpscaleFastAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/upscale/fast\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + try + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageUpscaleFastAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageUpscaleFastAsBytes", + methodName: "CreateStableImageUpscaleFastAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/upscale/fast\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageUpscaleFastAsBytes", + methodName: "CreateStableImageUpscaleFastAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/upscale/fast\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageUpscaleFastResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageUpscaleFastResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageUpscaleFastResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageUpscaleFastResponse5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageUpscaleFastResponse5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageUpscaleFastResponse5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateStableImageUpscaleFastResponse6? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateStableImageUpscaleFastResponse6.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateStableImageUpscaleFastResponse6.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageUpscaleFastResponse7? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageUpscaleFastResponse7.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageUpscaleFastResponse7.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageUpscaleFastResponse8? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageUpscaleFastResponse8.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageUpscaleFastResponse8.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + try + { + __response.EnsureSuccessStatusCode(); + + var __content = await __response.Content.ReadAsStreamAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.ResponseStream(__response, __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + } + catch + { + __response.Dispose(); + throw; + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// Fast
+ /// Our Fast Upscaler service enhances image resolution by 4x using predictive and generative AI. This lightweight and fast service (processing in ~1 second) is ideal for enhancing the quality of compressed images, making it suitable for social media posts and other applications.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// Optionally, the body of the request may also include:
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image is 4 times that of the input image with a maximum size of 16 megapixels.
+ /// ### Credits
+ /// Flat rate of 2 credit per successful generation. You will not be charged for failed generations. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app + /// + /// + /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999 + /// + /// + /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1 + /// + /// + /// The image you wish to upscale.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 32 and 1,536 pixels
+ /// - Height must be between 32 and 1,536 pixels
+ /// - Total pixel count must be between 1,024 and 1,048,576 pixels
+ /// Example: ./some/image.png + /// + /// + /// The image you wish to upscale.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 32 and 1,536 pixels
+ /// - Height must be between 32 and 1,536 pixels
+ /// - Total pixel count must be between 1,024 and 1,048,576 pixels
+ /// Example: ./some/image.png + /// + /// + /// Dictates the `content-type` of the generated image.
+ /// Default Value: png + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/upscale/fast",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./low-res-flower.jpg", "rb"),
+ /// },
+ /// data={
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./flower.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task> CreateStableImageUpscaleFastAsBytesAsResponseAsync( + string contentType, + global::System.IO.Stream image, + string imagename, + global::StabilityAI.CreateStableImageUpscaleFastAccept? accept = default, + string? stabilityClientId = default, + string? stabilityClientUserId = default, + string? stabilityClientVersion = default, + global::StabilityAI.CreateStableImageUpscaleFastRequestOutputFormat? outputFormat = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + + image = image ?? throw new global::System.ArgumentNullException(nameof(image)); + var request = new global::StabilityAI.CreateStableImageUpscaleFastRequest + { + Image = global::System.Array.Empty(), + Imagename = imagename, + OutputFormat = outputFormat, + }; + PrepareArguments( + client: HttpClient); + PrepareCreateStableImageUpscaleFastAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + stabilityClientId: ref stabilityClientId, + stabilityClientUserId: ref stabilityClientUserId, + stabilityClientVersion: ref stabilityClientVersion, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateStableImageUpscaleFastAsBytesSecurityRequirements, + operationName: "CreateStableImageUpscaleFastAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2beta/stable-image/upscale/fast", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/jpeg"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + if (stabilityClientId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString()); + } + if (stabilityClientUserId != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString()); + } + if (stabilityClientVersion != default) + { + __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + var __contentImage = new global::System.Net.Http.StreamContent(image); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.OutputFormat != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"output_format\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateStableImageUpscaleFastAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + stabilityClientId: stabilityClientId, + stabilityClientUserId: stabilityClientUserId, + stabilityClientVersion: stabilityClientVersion, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageUpscaleFastAsBytes", + methodName: "CreateStableImageUpscaleFastAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/upscale/fast\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageUpscaleFastAsBytes", + methodName: "CreateStableImageUpscaleFastAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/upscale/fast\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageUpscaleFastAsBytes", + methodName: "CreateStableImageUpscaleFastAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/upscale/fast\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateStableImageUpscaleFastAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageUpscaleFastAsBytes", + methodName: "CreateStableImageUpscaleFastAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/upscale/fast\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createStableImageUpscaleFastAsBytes", + methodName: "CreateStableImageUpscaleFastAsBytesAsync", + pathTemplate: "\"/v2beta/stable-image/upscale/fast\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateStableImageUpscaleFastResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateStableImageUpscaleFastResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateStableImageUpscaleFastResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was larger than 10MiB. + if ((int)__response.StatusCode == 413) + { + string? __content_413 = null; + global::System.Exception? __exception_413 = null; + global::StabilityAI.CreateStableImageUpscaleFastResponse5? __value_413 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_413 = global::StabilityAI.CreateStableImageUpscaleFastResponse5.FromJson(__content_413, JsonSerializerContext); + } + else + { + __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_413 = global::StabilityAI.CreateStableImageUpscaleFastResponse5.FromJson(__content_413, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_413 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_413 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_413, + responseBody: __content_413, + responseObject: __value_413, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was well-formed, but rejected. See the `errors` field for details. + if ((int)__response.StatusCode == 422) + { + string? __content_422 = null; + global::System.Exception? __exception_422 = null; + global::StabilityAI.CreateStableImageUpscaleFastResponse6? __value_422 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_422 = global::StabilityAI.CreateStableImageUpscaleFastResponse6.FromJson(__content_422, JsonSerializerContext); + } + else + { + __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_422 = global::StabilityAI.CreateStableImageUpscaleFastResponse6.FromJson(__content_422, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_422 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_422 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_422, + responseBody: __content_422, + responseObject: __value_422, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // You have made more than 150 requests in 10 seconds. + if ((int)__response.StatusCode == 429) + { + string? __content_429 = null; + global::System.Exception? __exception_429 = null; + global::StabilityAI.CreateStableImageUpscaleFastResponse7? __value_429 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_429 = global::StabilityAI.CreateStableImageUpscaleFastResponse7.FromJson(__content_429, JsonSerializerContext); + } + else + { + __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_429 = global::StabilityAI.CreateStableImageUpscaleFastResponse7.FromJson(__content_429, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_429 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_429 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_429, + responseBody: __content_429, + responseObject: __value_429, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateStableImageUpscaleFastResponse8? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateStableImageUpscaleFastResponse8.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateStableImageUpscaleFastResponse8.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessCreateStableImageUpscaleFastAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + } +} \ No newline at end of file diff --git a/src/libs/StabilityAI/Generated/StabilityAI.V1GenerationClient.ImageToImage.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.V1GenerationClient.ImageToImage.g.cs index b5a4003..21bbc01 100644 --- a/src/libs/StabilityAI/Generated/StabilityAI.V1GenerationClient.ImageToImage.g.cs +++ b/src/libs/StabilityAI/Generated/StabilityAI.V1GenerationClient.ImageToImage.g.cs @@ -201,6 +201,10 @@ partial void ProcessImageToImageResponseContent( __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || @@ -229,26 +233,6 @@ partial void ProcessImageToImageResponseContent( var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(engineId ?? string.Empty), - name: "\"engine_id\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"Accept\""); - - } - if (organization != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(organization ?? string.Empty), - name: "\"Organization\""); - - } __httpRequestContent.Add( content: new global::System.Net.Http.StringContent($"[{string.Join(",", global::System.Linq.Enumerable.Select(request.TextPrompts, x => x.ToJson(JsonSerializerContext)))}]"), name: "\"text_prompts\""); @@ -1154,6 +1138,10 @@ request.InitImagename is null __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || @@ -1182,26 +1170,6 @@ request.InitImagename is null var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(engineId ?? string.Empty), - name: "\"engine_id\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"Accept\""); - - } - if (organization != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(organization ?? string.Empty), - name: "\"Organization\""); - - } __httpRequestContent.Add( content: new global::System.Net.Http.StringContent($"[{string.Join(",", global::System.Linq.Enumerable.Select(request.TextPrompts, x => x.ToJson(JsonSerializerContext)))}]"), name: "\"text_prompts\""); @@ -1973,6 +1941,10 @@ request.InitImagename is null __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || @@ -2001,26 +1973,6 @@ request.InitImagename is null var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(engineId ?? string.Empty), - name: "\"engine_id\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"Accept\""); - - } - if (organization != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(organization ?? string.Empty), - name: "\"Organization\""); - - } __httpRequestContent.Add( content: new global::System.Net.Http.StringContent($"[{string.Join(",", global::System.Linq.Enumerable.Select(request.TextPrompts, x => x.ToJson(JsonSerializerContext)))}]"), name: "\"text_prompts\""); diff --git a/src/libs/StabilityAI/Generated/StabilityAI.V1GenerationClient.ImageToImageAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.V1GenerationClient.ImageToImageAsBytes.g.cs new file mode 100644 index 0000000..2b550a3 --- /dev/null +++ b/src/libs/StabilityAI/Generated/StabilityAI.V1GenerationClient.ImageToImageAsBytes.g.cs @@ -0,0 +1,3984 @@ + +#nullable enable + +namespace StabilityAI +{ + public partial class V1GenerationClient + { + + + private static readonly global::StabilityAI.EndPointSecurityRequirement s_ImageToImageAsBytesSecurityRequirement0 = + new global::StabilityAI.EndPointSecurityRequirement + { + Authorizations = new global::StabilityAI.EndPointAuthorizationRequirement[] + { new global::StabilityAI.EndPointAuthorizationRequirement + { + Type = "Http", + SchemeId = "HttpBearer", + Location = "Header", + Name = "Bearer", + FriendlyName = "Bearer", + }, + }, + }; + private static readonly global::StabilityAI.EndPointSecurityRequirement[] s_ImageToImageAsBytesSecurityRequirements = + new global::StabilityAI.EndPointSecurityRequirement[] + { s_ImageToImageAsBytesSecurityRequirement0, + }; + partial void PrepareImageToImageAsBytesArguments( + global::System.Net.Http.HttpClient httpClient, + ref string engineId, + ref global::StabilityAI.ImageToImageAccept? accept, + ref string? organization, + global::StabilityAI.ImageToImageRequestBody request); + partial void PrepareImageToImageAsBytesRequest( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpRequestMessage httpRequestMessage, + string engineId, + global::StabilityAI.ImageToImageAccept? accept, + string? organization, + global::StabilityAI.ImageToImageRequestBody request); + partial void ProcessImageToImageAsBytesResponse( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpResponseMessage httpResponseMessage); + + partial void ProcessImageToImageAsBytesResponseContent( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpResponseMessage httpResponseMessage, + ref byte[] content); + + /// + /// image-to-image
+ /// Modify an image based on a text prompt + ///
+ /// + /// Example: stable-diffusion-v1-5 + /// + /// + /// Default Value: application/json + /// + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// if [ -z "$STABILITY_API_KEY" ]; then
+ /// echo "STABILITY_API_KEY environment variable is not set"
+ /// exit 1
+ /// fi
+ /// OUTPUT_FILE=./out/v1_img2img.png
+ /// BASE_URL=${API_HOST:-https://api.stability.ai}
+ /// URL="$BASE_URL/v1/generation/stable-diffusion-v1-5/image-to-image"
+ /// curl -f -sS -X POST "$URL" \
+ /// -H 'Content-Type: multipart/form-data' \
+ /// -H 'Accept: image/png' \
+ /// -H "Authorization: Bearer $STABILITY_API_KEY" \
+ /// -F 'init_image=@"../init_image.png"' \
+ /// -F 'init_image_mode=IMAGE_STRENGTH' \
+ /// -F 'image_strength=0.35' \
+ /// -F 'text_prompts[0][text]=A galactic dog in space' \
+ /// -F 'cfg_scale=7' \
+ /// -F 'clip_guidance_preset=FAST_BLUE' \
+ /// -F 'samples=1' \
+ /// -F 'steps=30' \
+ /// -o "$OUTPUT_FILE" + ///
+ public async global::System.Threading.Tasks.Task ImageToImageAsBytesAsync( + string engineId, + + global::StabilityAI.ImageToImageRequestBody request, + global::StabilityAI.ImageToImageAccept? accept = default, + string? organization = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + var __response = await ImageToImageAsBytesAsResponseAsync( + engineId: engineId, + + request: request, + accept: accept, + organization: organization, + requestOptions: requestOptions, + cancellationToken: cancellationToken + ).ConfigureAwait(false); + + return __response.Body; + } + /// + /// image-to-image
+ /// Modify an image based on a text prompt + ///
+ /// + /// Example: stable-diffusion-v1-5 + /// + /// + /// Default Value: application/json + /// + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// if [ -z "$STABILITY_API_KEY" ]; then
+ /// echo "STABILITY_API_KEY environment variable is not set"
+ /// exit 1
+ /// fi
+ /// OUTPUT_FILE=./out/v1_img2img.png
+ /// BASE_URL=${API_HOST:-https://api.stability.ai}
+ /// URL="$BASE_URL/v1/generation/stable-diffusion-v1-5/image-to-image"
+ /// curl -f -sS -X POST "$URL" \
+ /// -H 'Content-Type: multipart/form-data' \
+ /// -H 'Accept: image/png' \
+ /// -H "Authorization: Bearer $STABILITY_API_KEY" \
+ /// -F 'init_image=@"../init_image.png"' \
+ /// -F 'init_image_mode=IMAGE_STRENGTH' \
+ /// -F 'image_strength=0.35' \
+ /// -F 'text_prompts[0][text]=A galactic dog in space' \
+ /// -F 'cfg_scale=7' \
+ /// -F 'clip_guidance_preset=FAST_BLUE' \
+ /// -F 'samples=1' \
+ /// -F 'steps=30' \
+ /// -o "$OUTPUT_FILE" + ///
+ public async global::System.Threading.Tasks.Task ImageToImageAsBytesAsStreamAsync( + string engineId, + + global::StabilityAI.ImageToImageRequestBody request, + global::StabilityAI.ImageToImageAccept? accept = default, + string? organization = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + request = request ?? throw new global::System.ArgumentNullException(nameof(request)); + + PrepareArguments( + client: HttpClient); + PrepareImageToImageAsBytesArguments( + httpClient: HttpClient, + engineId: ref engineId, + accept: ref accept, + organization: ref organization, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_ImageToImageAsBytesSecurityRequirements, + operationName: "ImageToImageAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: $"/v1/generation/{engineId}/image-to-image", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/png"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("Accept", accept?.ToValueString() ?? string.Empty); + } + if (organization != default) + { + __httpRequest.Headers.TryAddWithoutValidation("Organization", organization.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent($"[{string.Join(",", global::System.Linq.Enumerable.Select(request.TextPrompts, x => x.ToJson(JsonSerializerContext)))}]"), + name: "\"text_prompts\""); + + var __contentInitImage = new global::System.Net.Http.ByteArrayContent(request.InitImage ?? global::System.Array.Empty()); + __contentInitImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.InitImagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.InitImagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentInitImage, + name: "\"init_image\"", + fileName: request.InitImagename != null ? $"\"{request.InitImagename}\"" : string.Empty); + if (__contentInitImage.Headers.ContentDisposition != null) + { + __contentInitImage.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.ImageStrength != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.ImageStrength, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"image_strength\""); + + } + if (request.StepScheduleStart != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.StepScheduleStart, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"step_schedule_start\""); + + } + if (request.StepScheduleEnd != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.StepScheduleEnd, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"step_schedule_end\""); + + } + if (request.CfgScale != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.CfgScale, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"cfg_scale\""); + + } + if (request.ClipGuidancePreset != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.ClipGuidancePreset).HasValue ? (request.ClipGuidancePreset).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"clip_guidance_preset\""); + + } + if (request.Sampler != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.Sampler).HasValue ? (request.Sampler).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"sampler\""); + + } + if (request.Samples != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Samples, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"samples\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.Steps != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Steps, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"steps\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareImageToImageAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + engineId: engineId!, + accept: accept, + organization: organization, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "ImageToImageAsBytes", + methodName: "ImageToImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseHeadersRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "ImageToImageAsBytes", + methodName: "ImageToImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "ImageToImageAsBytes", + methodName: "ImageToImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + try + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessImageToImageAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "ImageToImageAsBytes", + methodName: "ImageToImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "ImageToImageAsBytes", + methodName: "ImageToImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // bad_request: general error for invalid parameters

More specific errors:

- invalid_samples: Sample count may only be greater than 1 when the accept header is set to `application/json` - invalid_height_or_width: Height and width must be specified in increments of 64 - invalid_file_size: The file size of one or more of the provided files is invalid - invalid_mime_type: The mime type of one or more of the provided files is invalid - invalid_image_dimensions: The dimensions of the provided `init_image` and `mask_image` do not match - invalid_mask_image: The parameter `mask_source` was set to `MASK_IMAGE_WHITE` or `MASK_IMAGE_BLACK` but no `mask_image` was provided - invalid_prompts: One or more of the prompts contains filtered words - invalid_pixel_count: Incorrect number of pixels specified. Requirements: - For 768 engines : 589,824 ≤ `height * width` ≤ 1,048,576 - All other engines: 262,144 ≤ `height * width` ≤ 1,048,576 + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.Error? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.Error.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.Error.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // unauthorized: API key missing or invalid + if ((int)__response.StatusCode == 401) + { + string? __content_401 = null; + global::System.Exception? __exception_401 = null; + global::StabilityAI.Error? __value_401 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_401 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_401 = global::StabilityAI.Error.FromJson(__content_401, JsonSerializerContext); + } + else + { + __content_401 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_401 = global::StabilityAI.Error.FromJson(__content_401, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_401 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_401 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_401, + responseBody: __content_401, + responseObject: __value_401, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // permission_denied: You lack the necessary permissions to perform this action + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.Error? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.Error.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.Error.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // not_found: The requested resource was not found (e.g. specifing a model that does not exist) + if ((int)__response.StatusCode == 404) + { + string? __content_404 = null; + global::System.Exception? __exception_404 = null; + global::StabilityAI.Error? __value_404 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_404 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_404 = global::StabilityAI.Error.FromJson(__content_404, JsonSerializerContext); + } + else + { + __content_404 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_404 = global::StabilityAI.Error.FromJson(__content_404, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_404 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_404 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_404, + responseBody: __content_404, + responseObject: __value_404, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // server_error: Some unexpected server error occurred + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.Error? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.Error.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.Error.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + try + { + __response.EnsureSuccessStatusCode(); + + var __content = await __response.Content.ReadAsStreamAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.ResponseStream(__response, __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + } + catch + { + __response.Dispose(); + throw; + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// image-to-image
+ /// Modify an image based on a text prompt + ///
+ /// + /// Example: stable-diffusion-v1-5 + /// + /// + /// Default Value: application/json + /// + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// if [ -z "$STABILITY_API_KEY" ]; then
+ /// echo "STABILITY_API_KEY environment variable is not set"
+ /// exit 1
+ /// fi
+ /// OUTPUT_FILE=./out/v1_img2img.png
+ /// BASE_URL=${API_HOST:-https://api.stability.ai}
+ /// URL="$BASE_URL/v1/generation/stable-diffusion-v1-5/image-to-image"
+ /// curl -f -sS -X POST "$URL" \
+ /// -H 'Content-Type: multipart/form-data' \
+ /// -H 'Accept: image/png' \
+ /// -H "Authorization: Bearer $STABILITY_API_KEY" \
+ /// -F 'init_image=@"../init_image.png"' \
+ /// -F 'init_image_mode=IMAGE_STRENGTH' \
+ /// -F 'image_strength=0.35' \
+ /// -F 'text_prompts[0][text]=A galactic dog in space' \
+ /// -F 'cfg_scale=7' \
+ /// -F 'clip_guidance_preset=FAST_BLUE' \
+ /// -F 'samples=1' \
+ /// -F 'steps=30' \
+ /// -o "$OUTPUT_FILE" + ///
+ public async global::System.Threading.Tasks.Task> ImageToImageAsBytesAsResponseAsync( + string engineId, + + global::StabilityAI.ImageToImageRequestBody request, + global::StabilityAI.ImageToImageAccept? accept = default, + string? organization = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + request = request ?? throw new global::System.ArgumentNullException(nameof(request)); + + PrepareArguments( + client: HttpClient); + PrepareImageToImageAsBytesArguments( + httpClient: HttpClient, + engineId: ref engineId, + accept: ref accept, + organization: ref organization, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_ImageToImageAsBytesSecurityRequirements, + operationName: "ImageToImageAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: $"/v1/generation/{engineId}/image-to-image", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/png"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("Accept", accept?.ToValueString() ?? string.Empty); + } + if (organization != default) + { + __httpRequest.Headers.TryAddWithoutValidation("Organization", organization.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent($"[{string.Join(",", global::System.Linq.Enumerable.Select(request.TextPrompts, x => x.ToJson(JsonSerializerContext)))}]"), + name: "\"text_prompts\""); + + var __contentInitImage = new global::System.Net.Http.ByteArrayContent(request.InitImage ?? global::System.Array.Empty()); + __contentInitImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.InitImagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.InitImagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentInitImage, + name: "\"init_image\"", + fileName: request.InitImagename != null ? $"\"{request.InitImagename}\"" : string.Empty); + if (__contentInitImage.Headers.ContentDisposition != null) + { + __contentInitImage.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.ImageStrength != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.ImageStrength, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"image_strength\""); + + } + if (request.StepScheduleStart != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.StepScheduleStart, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"step_schedule_start\""); + + } + if (request.StepScheduleEnd != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.StepScheduleEnd, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"step_schedule_end\""); + + } + if (request.CfgScale != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.CfgScale, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"cfg_scale\""); + + } + if (request.ClipGuidancePreset != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.ClipGuidancePreset).HasValue ? (request.ClipGuidancePreset).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"clip_guidance_preset\""); + + } + if (request.Sampler != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.Sampler).HasValue ? (request.Sampler).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"sampler\""); + + } + if (request.Samples != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Samples, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"samples\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.Steps != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Steps, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"steps\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareImageToImageAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + engineId: engineId!, + accept: accept, + organization: organization, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "ImageToImageAsBytes", + methodName: "ImageToImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "ImageToImageAsBytes", + methodName: "ImageToImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "ImageToImageAsBytes", + methodName: "ImageToImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessImageToImageAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "ImageToImageAsBytes", + methodName: "ImageToImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "ImageToImageAsBytes", + methodName: "ImageToImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // bad_request: general error for invalid parameters

More specific errors:

- invalid_samples: Sample count may only be greater than 1 when the accept header is set to `application/json` - invalid_height_or_width: Height and width must be specified in increments of 64 - invalid_file_size: The file size of one or more of the provided files is invalid - invalid_mime_type: The mime type of one or more of the provided files is invalid - invalid_image_dimensions: The dimensions of the provided `init_image` and `mask_image` do not match - invalid_mask_image: The parameter `mask_source` was set to `MASK_IMAGE_WHITE` or `MASK_IMAGE_BLACK` but no `mask_image` was provided - invalid_prompts: One or more of the prompts contains filtered words - invalid_pixel_count: Incorrect number of pixels specified. Requirements: - For 768 engines : 589,824 ≤ `height * width` ≤ 1,048,576 - All other engines: 262,144 ≤ `height * width` ≤ 1,048,576 + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.Error? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.Error.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.Error.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // unauthorized: API key missing or invalid + if ((int)__response.StatusCode == 401) + { + string? __content_401 = null; + global::System.Exception? __exception_401 = null; + global::StabilityAI.Error? __value_401 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_401 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_401 = global::StabilityAI.Error.FromJson(__content_401, JsonSerializerContext); + } + else + { + __content_401 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_401 = global::StabilityAI.Error.FromJson(__content_401, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_401 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_401 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_401, + responseBody: __content_401, + responseObject: __value_401, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // permission_denied: You lack the necessary permissions to perform this action + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.Error? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.Error.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.Error.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // not_found: The requested resource was not found (e.g. specifing a model that does not exist) + if ((int)__response.StatusCode == 404) + { + string? __content_404 = null; + global::System.Exception? __exception_404 = null; + global::StabilityAI.Error? __value_404 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_404 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_404 = global::StabilityAI.Error.FromJson(__content_404, JsonSerializerContext); + } + else + { + __content_404 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_404 = global::StabilityAI.Error.FromJson(__content_404, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_404 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_404 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_404, + responseBody: __content_404, + responseObject: __value_404, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // server_error: Some unexpected server error occurred + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.Error? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.Error.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.Error.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessImageToImageAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// image-to-image
+ /// Modify an image based on a text prompt + ///
+ /// + /// Example: stable-diffusion-v1-5 + /// + /// + /// Default Value: application/json + /// + /// + /// + /// An array of text prompts to use for generation.
+ /// Due to how arrays are represented in `multipart/form-data` requests, prompts must adhear to the format `text_prompts[index][text|weight]`,
+ /// where `index` is some integer used to tie the text and weight together. While `index` does not have to be sequential, duplicate entries
+ /// will override previous entries, so it is recommended to use sequential indices.
+ /// Given a text prompt with the text `A lighthouse on a cliff` and a weight of `0.5`, it would be represented as:
+ /// ```
+ /// text_prompts[0][text]: "A lighthouse on a cliff"
+ /// text_prompts[0][weight]: 0.5
+ /// ```
+ /// To add another prompt to that request simply provide the values under a new `index`:
+ /// ```
+ /// text_prompts[0][text]: "A lighthouse on a cliff"
+ /// text_prompts[0][weight]: 0.5
+ /// text_prompts[1][text]: "land, ground, dirt, grass"
+ /// text_prompts[1][weight]: -0.9
+ /// ``` + /// + /// + /// Image used to initialize the diffusion process, in lieu of random noise.
+ /// Example: <image binary> + /// + /// + /// Image used to initialize the diffusion process, in lieu of random noise.
+ /// Example: <image binary> + /// + /// + /// How much influence the `init_image` has on the diffusion process. Values close to `1` will yield images very similar to the `init_image` while values close to `0` will yield images wildly different than the `init_image`. The behavior of this is meant to mirror DreamStudio's "Image Strength" slider. <br/> <br/> This parameter is just an alternate way to set `step_schedule_start`, which is done via the calculation `1 - image_strength`. For example, passing in an Image Strength of 35% (`0.35`) would result in a `step_schedule_start` of `0.65`.
+ /// Default Value: 0.35F
+ /// Example: 0.4F + /// + /// + /// Skips a proportion of the start of the diffusion steps, allowing the init_image to influence the final generated image. Lower values will result in more influence from the init_image, while higher values will result in more influence from the diffusion steps. (e.g. a value of `0` would simply return you the init_image, where a value of `1` would return you a completely different image.)
+ /// Default Value: 0.65F
+ /// Example: 0.4F + /// + /// + /// Skips a proportion of the end of the diffusion steps, allowing the init_image to influence the final generated image. Lower values will result in more influence from the init_image, while higher values will result in more influence from the diffusion steps.
+ /// Example: 0.01F + /// + /// + /// How strictly the diffusion process adheres to the prompt text (higher values keep your image closer to your prompt)
+ /// Default Value: 7
+ /// Example: 7 + /// + /// + /// Default Value: NONE
+ /// Example: FAST_BLUE + /// + /// + /// Which sampler to use for the diffusion process. If this value is omitted we'll automatically select an appropriate sampler for you.
+ /// Example: K_DPM_2_ANCESTRAL + /// + /// + /// Number of images to generate
+ /// Default Value: 1
+ /// Example: 1 + /// + /// + /// Random noise seed (omit this option or use `0` for a random seed)
+ /// Default Value: 0
+ /// Example: 0 + /// + /// + /// Number of diffusion steps to run
+ /// Default Value: 50
+ /// Example: 75 + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + public async global::System.Threading.Tasks.Task ImageToImageAsBytesAsync( + string engineId, + global::System.Collections.Generic.IList textPrompts, + byte[] initImage, + string initImagename, + global::StabilityAI.ImageToImageAccept? accept = default, + string? organization = default, + float? imageStrength = default, + double? stepScheduleStart = default, + double? stepScheduleEnd = default, + double? cfgScale = default, + global::StabilityAI.ClipGuidancePreset? clipGuidancePreset = default, + global::StabilityAI.Sampler? sampler = default, + int? samples = default, + long? seed = default, + int? steps = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + var __request = new global::StabilityAI.ImageToImageRequestBody + { + TextPrompts = textPrompts, + InitImage = initImage, + InitImagename = initImagename, + ImageStrength = imageStrength, + StepScheduleStart = stepScheduleStart, + StepScheduleEnd = stepScheduleEnd, + CfgScale = cfgScale, + ClipGuidancePreset = clipGuidancePreset, + Sampler = sampler, + Samples = samples, + Seed = seed, + Steps = steps, + }; + + return await ImageToImageAsBytesAsync( + engineId: engineId, + accept: accept, + organization: organization, + request: __request, + requestOptions: requestOptions, + cancellationToken: cancellationToken).ConfigureAwait(false); + } + + /// + /// image-to-image
+ /// Modify an image based on a text prompt + ///
+ /// + /// Example: stable-diffusion-v1-5 + /// + /// + /// Default Value: application/json + /// + /// + /// + /// An array of text prompts to use for generation.
+ /// Due to how arrays are represented in `multipart/form-data` requests, prompts must adhear to the format `text_prompts[index][text|weight]`,
+ /// where `index` is some integer used to tie the text and weight together. While `index` does not have to be sequential, duplicate entries
+ /// will override previous entries, so it is recommended to use sequential indices.
+ /// Given a text prompt with the text `A lighthouse on a cliff` and a weight of `0.5`, it would be represented as:
+ /// ```
+ /// text_prompts[0][text]: "A lighthouse on a cliff"
+ /// text_prompts[0][weight]: 0.5
+ /// ```
+ /// To add another prompt to that request simply provide the values under a new `index`:
+ /// ```
+ /// text_prompts[0][text]: "A lighthouse on a cliff"
+ /// text_prompts[0][weight]: 0.5
+ /// text_prompts[1][text]: "land, ground, dirt, grass"
+ /// text_prompts[1][weight]: -0.9
+ /// ``` + /// + /// + /// Image used to initialize the diffusion process, in lieu of random noise.
+ /// Example: <image binary> + /// + /// + /// Image used to initialize the diffusion process, in lieu of random noise.
+ /// Example: <image binary> + /// + /// + /// How much influence the `init_image` has on the diffusion process. Values close to `1` will yield images very similar to the `init_image` while values close to `0` will yield images wildly different than the `init_image`. The behavior of this is meant to mirror DreamStudio's "Image Strength" slider. <br/> <br/> This parameter is just an alternate way to set `step_schedule_start`, which is done via the calculation `1 - image_strength`. For example, passing in an Image Strength of 35% (`0.35`) would result in a `step_schedule_start` of `0.65`.
+ /// Default Value: 0.35F
+ /// Example: 0.4F + /// + /// + /// Skips a proportion of the start of the diffusion steps, allowing the init_image to influence the final generated image. Lower values will result in more influence from the init_image, while higher values will result in more influence from the diffusion steps. (e.g. a value of `0` would simply return you the init_image, where a value of `1` would return you a completely different image.)
+ /// Default Value: 0.65F
+ /// Example: 0.4F + /// + /// + /// Skips a proportion of the end of the diffusion steps, allowing the init_image to influence the final generated image. Lower values will result in more influence from the init_image, while higher values will result in more influence from the diffusion steps.
+ /// Example: 0.01F + /// + /// + /// How strictly the diffusion process adheres to the prompt text (higher values keep your image closer to your prompt)
+ /// Default Value: 7
+ /// Example: 7 + /// + /// + /// Default Value: NONE
+ /// Example: FAST_BLUE + /// + /// + /// Which sampler to use for the diffusion process. If this value is omitted we'll automatically select an appropriate sampler for you.
+ /// Example: K_DPM_2_ANCESTRAL + /// + /// + /// Number of images to generate
+ /// Default Value: 1
+ /// Example: 1 + /// + /// + /// Random noise seed (omit this option or use `0` for a random seed)
+ /// Default Value: 0
+ /// Example: 0 + /// + /// + /// Number of diffusion steps to run
+ /// Default Value: 50
+ /// Example: 75 + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// if [ -z "$STABILITY_API_KEY" ]; then
+ /// echo "STABILITY_API_KEY environment variable is not set"
+ /// exit 1
+ /// fi
+ /// OUTPUT_FILE=./out/v1_img2img.png
+ /// BASE_URL=${API_HOST:-https://api.stability.ai}
+ /// URL="$BASE_URL/v1/generation/stable-diffusion-v1-5/image-to-image"
+ /// curl -f -sS -X POST "$URL" \
+ /// -H 'Content-Type: multipart/form-data' \
+ /// -H 'Accept: image/png' \
+ /// -H "Authorization: Bearer $STABILITY_API_KEY" \
+ /// -F 'init_image=@"../init_image.png"' \
+ /// -F 'init_image_mode=IMAGE_STRENGTH' \
+ /// -F 'image_strength=0.35' \
+ /// -F 'text_prompts[0][text]=A galactic dog in space' \
+ /// -F 'cfg_scale=7' \
+ /// -F 'clip_guidance_preset=FAST_BLUE' \
+ /// -F 'samples=1' \
+ /// -F 'steps=30' \
+ /// -o "$OUTPUT_FILE" + ///
+ public async global::System.Threading.Tasks.Task ImageToImageAsBytesAsync( + string engineId, + global::System.Collections.Generic.IList textPrompts, + global::System.IO.Stream initImage, + string initImagename, + global::StabilityAI.ImageToImageAccept? accept = default, + string? organization = default, + float? imageStrength = default, + double? stepScheduleStart = default, + double? stepScheduleEnd = default, + double? cfgScale = default, + global::StabilityAI.ClipGuidancePreset? clipGuidancePreset = default, + global::StabilityAI.Sampler? sampler = default, + int? samples = default, + long? seed = default, + int? steps = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + + initImage = initImage ?? throw new global::System.ArgumentNullException(nameof(initImage)); + var request = new global::StabilityAI.ImageToImageRequestBody + { + TextPrompts = textPrompts, + InitImage = global::System.Array.Empty(), + InitImagename = initImagename, + ImageStrength = imageStrength, + StepScheduleStart = stepScheduleStart, + StepScheduleEnd = stepScheduleEnd, + CfgScale = cfgScale, + ClipGuidancePreset = clipGuidancePreset, + Sampler = sampler, + Samples = samples, + Seed = seed, + Steps = steps, + }; + PrepareArguments( + client: HttpClient); + PrepareImageToImageAsBytesArguments( + httpClient: HttpClient, + engineId: ref engineId, + accept: ref accept, + organization: ref organization, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_ImageToImageAsBytesSecurityRequirements, + operationName: "ImageToImageAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: $"/v1/generation/{engineId}/image-to-image", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/png"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("Accept", accept?.ToValueString() ?? string.Empty); + } + if (organization != default) + { + __httpRequest.Headers.TryAddWithoutValidation("Organization", organization.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent($"[{string.Join(",", global::System.Linq.Enumerable.Select(request.TextPrompts, x => x.ToJson(JsonSerializerContext)))}]"), + name: "\"text_prompts\""); + + var __contentInitImage = new global::System.Net.Http.StreamContent(initImage); + __contentInitImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.InitImagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.InitImagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentInitImage, + name: "\"init_image\"", + fileName: request.InitImagename != null ? $"\"{request.InitImagename}\"" : string.Empty); + if (__contentInitImage.Headers.ContentDisposition != null) + { + __contentInitImage.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.ImageStrength != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.ImageStrength, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"image_strength\""); + + } + if (request.StepScheduleStart != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.StepScheduleStart, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"step_schedule_start\""); + + } + if (request.StepScheduleEnd != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.StepScheduleEnd, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"step_schedule_end\""); + + } + if (request.CfgScale != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.CfgScale, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"cfg_scale\""); + + } + if (request.ClipGuidancePreset != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.ClipGuidancePreset).HasValue ? (request.ClipGuidancePreset).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"clip_guidance_preset\""); + + } + if (request.Sampler != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.Sampler).HasValue ? (request.Sampler).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"sampler\""); + + } + if (request.Samples != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Samples, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"samples\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.Steps != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Steps, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"steps\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareImageToImageAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + engineId: engineId!, + accept: accept, + organization: organization, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "ImageToImageAsBytes", + methodName: "ImageToImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "ImageToImageAsBytes", + methodName: "ImageToImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "ImageToImageAsBytes", + methodName: "ImageToImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessImageToImageAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "ImageToImageAsBytes", + methodName: "ImageToImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "ImageToImageAsBytes", + methodName: "ImageToImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // bad_request: general error for invalid parameters

More specific errors:

- invalid_samples: Sample count may only be greater than 1 when the accept header is set to `application/json` - invalid_height_or_width: Height and width must be specified in increments of 64 - invalid_file_size: The file size of one or more of the provided files is invalid - invalid_mime_type: The mime type of one or more of the provided files is invalid - invalid_image_dimensions: The dimensions of the provided `init_image` and `mask_image` do not match - invalid_mask_image: The parameter `mask_source` was set to `MASK_IMAGE_WHITE` or `MASK_IMAGE_BLACK` but no `mask_image` was provided - invalid_prompts: One or more of the prompts contains filtered words - invalid_pixel_count: Incorrect number of pixels specified. Requirements: - For 768 engines : 589,824 ≤ `height * width` ≤ 1,048,576 - All other engines: 262,144 ≤ `height * width` ≤ 1,048,576 + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.Error? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.Error.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.Error.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // unauthorized: API key missing or invalid + if ((int)__response.StatusCode == 401) + { + string? __content_401 = null; + global::System.Exception? __exception_401 = null; + global::StabilityAI.Error? __value_401 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_401 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_401 = global::StabilityAI.Error.FromJson(__content_401, JsonSerializerContext); + } + else + { + __content_401 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_401 = global::StabilityAI.Error.FromJson(__content_401, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_401 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_401 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_401, + responseBody: __content_401, + responseObject: __value_401, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // permission_denied: You lack the necessary permissions to perform this action + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.Error? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.Error.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.Error.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // not_found: The requested resource was not found (e.g. specifing a model that does not exist) + if ((int)__response.StatusCode == 404) + { + string? __content_404 = null; + global::System.Exception? __exception_404 = null; + global::StabilityAI.Error? __value_404 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_404 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_404 = global::StabilityAI.Error.FromJson(__content_404, JsonSerializerContext); + } + else + { + __content_404 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_404 = global::StabilityAI.Error.FromJson(__content_404, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_404 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_404 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_404, + responseBody: __content_404, + responseObject: __value_404, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // server_error: Some unexpected server error occurred + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.Error? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.Error.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.Error.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessImageToImageAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return __content; + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return __content; + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// image-to-image
+ /// Modify an image based on a text prompt + ///
+ /// + /// Example: stable-diffusion-v1-5 + /// + /// + /// Default Value: application/json + /// + /// + /// + /// An array of text prompts to use for generation.
+ /// Due to how arrays are represented in `multipart/form-data` requests, prompts must adhear to the format `text_prompts[index][text|weight]`,
+ /// where `index` is some integer used to tie the text and weight together. While `index` does not have to be sequential, duplicate entries
+ /// will override previous entries, so it is recommended to use sequential indices.
+ /// Given a text prompt with the text `A lighthouse on a cliff` and a weight of `0.5`, it would be represented as:
+ /// ```
+ /// text_prompts[0][text]: "A lighthouse on a cliff"
+ /// text_prompts[0][weight]: 0.5
+ /// ```
+ /// To add another prompt to that request simply provide the values under a new `index`:
+ /// ```
+ /// text_prompts[0][text]: "A lighthouse on a cliff"
+ /// text_prompts[0][weight]: 0.5
+ /// text_prompts[1][text]: "land, ground, dirt, grass"
+ /// text_prompts[1][weight]: -0.9
+ /// ``` + /// + /// + /// Image used to initialize the diffusion process, in lieu of random noise.
+ /// Example: <image binary> + /// + /// + /// Image used to initialize the diffusion process, in lieu of random noise.
+ /// Example: <image binary> + /// + /// + /// How much influence the `init_image` has on the diffusion process. Values close to `1` will yield images very similar to the `init_image` while values close to `0` will yield images wildly different than the `init_image`. The behavior of this is meant to mirror DreamStudio's "Image Strength" slider. <br/> <br/> This parameter is just an alternate way to set `step_schedule_start`, which is done via the calculation `1 - image_strength`. For example, passing in an Image Strength of 35% (`0.35`) would result in a `step_schedule_start` of `0.65`.
+ /// Default Value: 0.35F
+ /// Example: 0.4F + /// + /// + /// Skips a proportion of the start of the diffusion steps, allowing the init_image to influence the final generated image. Lower values will result in more influence from the init_image, while higher values will result in more influence from the diffusion steps. (e.g. a value of `0` would simply return you the init_image, where a value of `1` would return you a completely different image.)
+ /// Default Value: 0.65F
+ /// Example: 0.4F + /// + /// + /// Skips a proportion of the end of the diffusion steps, allowing the init_image to influence the final generated image. Lower values will result in more influence from the init_image, while higher values will result in more influence from the diffusion steps.
+ /// Example: 0.01F + /// + /// + /// How strictly the diffusion process adheres to the prompt text (higher values keep your image closer to your prompt)
+ /// Default Value: 7
+ /// Example: 7 + /// + /// + /// Default Value: NONE
+ /// Example: FAST_BLUE + /// + /// + /// Which sampler to use for the diffusion process. If this value is omitted we'll automatically select an appropriate sampler for you.
+ /// Example: K_DPM_2_ANCESTRAL + /// + /// + /// Number of images to generate
+ /// Default Value: 1
+ /// Example: 1 + /// + /// + /// Random noise seed (omit this option or use `0` for a random seed)
+ /// Default Value: 0
+ /// Example: 0 + /// + /// + /// Number of diffusion steps to run
+ /// Default Value: 50
+ /// Example: 75 + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// if [ -z "$STABILITY_API_KEY" ]; then
+ /// echo "STABILITY_API_KEY environment variable is not set"
+ /// exit 1
+ /// fi
+ /// OUTPUT_FILE=./out/v1_img2img.png
+ /// BASE_URL=${API_HOST:-https://api.stability.ai}
+ /// URL="$BASE_URL/v1/generation/stable-diffusion-v1-5/image-to-image"
+ /// curl -f -sS -X POST "$URL" \
+ /// -H 'Content-Type: multipart/form-data' \
+ /// -H 'Accept: image/png' \
+ /// -H "Authorization: Bearer $STABILITY_API_KEY" \
+ /// -F 'init_image=@"../init_image.png"' \
+ /// -F 'init_image_mode=IMAGE_STRENGTH' \
+ /// -F 'image_strength=0.35' \
+ /// -F 'text_prompts[0][text]=A galactic dog in space' \
+ /// -F 'cfg_scale=7' \
+ /// -F 'clip_guidance_preset=FAST_BLUE' \
+ /// -F 'samples=1' \
+ /// -F 'steps=30' \
+ /// -o "$OUTPUT_FILE" + ///
+ public async global::System.Threading.Tasks.Task ImageToImageAsBytesAsStreamAsync( + string engineId, + global::System.Collections.Generic.IList textPrompts, + global::System.IO.Stream initImage, + string initImagename, + global::StabilityAI.ImageToImageAccept? accept = default, + string? organization = default, + float? imageStrength = default, + double? stepScheduleStart = default, + double? stepScheduleEnd = default, + double? cfgScale = default, + global::StabilityAI.ClipGuidancePreset? clipGuidancePreset = default, + global::StabilityAI.Sampler? sampler = default, + int? samples = default, + long? seed = default, + int? steps = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + + initImage = initImage ?? throw new global::System.ArgumentNullException(nameof(initImage)); + var request = new global::StabilityAI.ImageToImageRequestBody + { + TextPrompts = textPrompts, + InitImage = global::System.Array.Empty(), + InitImagename = initImagename, + ImageStrength = imageStrength, + StepScheduleStart = stepScheduleStart, + StepScheduleEnd = stepScheduleEnd, + CfgScale = cfgScale, + ClipGuidancePreset = clipGuidancePreset, + Sampler = sampler, + Samples = samples, + Seed = seed, + Steps = steps, + }; + PrepareArguments( + client: HttpClient); + PrepareImageToImageAsBytesArguments( + httpClient: HttpClient, + engineId: ref engineId, + accept: ref accept, + organization: ref organization, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_ImageToImageAsBytesSecurityRequirements, + operationName: "ImageToImageAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: $"/v1/generation/{engineId}/image-to-image", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/png"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("Accept", accept?.ToValueString() ?? string.Empty); + } + if (organization != default) + { + __httpRequest.Headers.TryAddWithoutValidation("Organization", organization.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent($"[{string.Join(",", global::System.Linq.Enumerable.Select(request.TextPrompts, x => x.ToJson(JsonSerializerContext)))}]"), + name: "\"text_prompts\""); + + var __contentInitImage = new global::System.Net.Http.StreamContent(initImage); + __contentInitImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.InitImagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.InitImagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentInitImage, + name: "\"init_image\"", + fileName: request.InitImagename != null ? $"\"{request.InitImagename}\"" : string.Empty); + if (__contentInitImage.Headers.ContentDisposition != null) + { + __contentInitImage.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.ImageStrength != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.ImageStrength, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"image_strength\""); + + } + if (request.StepScheduleStart != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.StepScheduleStart, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"step_schedule_start\""); + + } + if (request.StepScheduleEnd != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.StepScheduleEnd, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"step_schedule_end\""); + + } + if (request.CfgScale != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.CfgScale, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"cfg_scale\""); + + } + if (request.ClipGuidancePreset != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.ClipGuidancePreset).HasValue ? (request.ClipGuidancePreset).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"clip_guidance_preset\""); + + } + if (request.Sampler != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.Sampler).HasValue ? (request.Sampler).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"sampler\""); + + } + if (request.Samples != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Samples, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"samples\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.Steps != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Steps, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"steps\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareImageToImageAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + engineId: engineId!, + accept: accept, + organization: organization, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "ImageToImageAsBytes", + methodName: "ImageToImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseHeadersRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "ImageToImageAsBytes", + methodName: "ImageToImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "ImageToImageAsBytes", + methodName: "ImageToImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + try + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessImageToImageAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "ImageToImageAsBytes", + methodName: "ImageToImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "ImageToImageAsBytes", + methodName: "ImageToImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // bad_request: general error for invalid parameters

More specific errors:

- invalid_samples: Sample count may only be greater than 1 when the accept header is set to `application/json` - invalid_height_or_width: Height and width must be specified in increments of 64 - invalid_file_size: The file size of one or more of the provided files is invalid - invalid_mime_type: The mime type of one or more of the provided files is invalid - invalid_image_dimensions: The dimensions of the provided `init_image` and `mask_image` do not match - invalid_mask_image: The parameter `mask_source` was set to `MASK_IMAGE_WHITE` or `MASK_IMAGE_BLACK` but no `mask_image` was provided - invalid_prompts: One or more of the prompts contains filtered words - invalid_pixel_count: Incorrect number of pixels specified. Requirements: - For 768 engines : 589,824 ≤ `height * width` ≤ 1,048,576 - All other engines: 262,144 ≤ `height * width` ≤ 1,048,576 + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.Error? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.Error.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.Error.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // unauthorized: API key missing or invalid + if ((int)__response.StatusCode == 401) + { + string? __content_401 = null; + global::System.Exception? __exception_401 = null; + global::StabilityAI.Error? __value_401 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_401 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_401 = global::StabilityAI.Error.FromJson(__content_401, JsonSerializerContext); + } + else + { + __content_401 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_401 = global::StabilityAI.Error.FromJson(__content_401, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_401 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_401 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_401, + responseBody: __content_401, + responseObject: __value_401, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // permission_denied: You lack the necessary permissions to perform this action + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.Error? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.Error.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.Error.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // not_found: The requested resource was not found (e.g. specifing a model that does not exist) + if ((int)__response.StatusCode == 404) + { + string? __content_404 = null; + global::System.Exception? __exception_404 = null; + global::StabilityAI.Error? __value_404 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_404 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_404 = global::StabilityAI.Error.FromJson(__content_404, JsonSerializerContext); + } + else + { + __content_404 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_404 = global::StabilityAI.Error.FromJson(__content_404, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_404 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_404 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_404, + responseBody: __content_404, + responseObject: __value_404, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // server_error: Some unexpected server error occurred + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.Error? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.Error.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.Error.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + try + { + __response.EnsureSuccessStatusCode(); + + var __content = await __response.Content.ReadAsStreamAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.ResponseStream(__response, __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + } + catch + { + __response.Dispose(); + throw; + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// image-to-image
+ /// Modify an image based on a text prompt + ///
+ /// + /// Example: stable-diffusion-v1-5 + /// + /// + /// Default Value: application/json + /// + /// + /// + /// An array of text prompts to use for generation.
+ /// Due to how arrays are represented in `multipart/form-data` requests, prompts must adhear to the format `text_prompts[index][text|weight]`,
+ /// where `index` is some integer used to tie the text and weight together. While `index` does not have to be sequential, duplicate entries
+ /// will override previous entries, so it is recommended to use sequential indices.
+ /// Given a text prompt with the text `A lighthouse on a cliff` and a weight of `0.5`, it would be represented as:
+ /// ```
+ /// text_prompts[0][text]: "A lighthouse on a cliff"
+ /// text_prompts[0][weight]: 0.5
+ /// ```
+ /// To add another prompt to that request simply provide the values under a new `index`:
+ /// ```
+ /// text_prompts[0][text]: "A lighthouse on a cliff"
+ /// text_prompts[0][weight]: 0.5
+ /// text_prompts[1][text]: "land, ground, dirt, grass"
+ /// text_prompts[1][weight]: -0.9
+ /// ``` + /// + /// + /// Image used to initialize the diffusion process, in lieu of random noise.
+ /// Example: <image binary> + /// + /// + /// Image used to initialize the diffusion process, in lieu of random noise.
+ /// Example: <image binary> + /// + /// + /// How much influence the `init_image` has on the diffusion process. Values close to `1` will yield images very similar to the `init_image` while values close to `0` will yield images wildly different than the `init_image`. The behavior of this is meant to mirror DreamStudio's "Image Strength" slider. <br/> <br/> This parameter is just an alternate way to set `step_schedule_start`, which is done via the calculation `1 - image_strength`. For example, passing in an Image Strength of 35% (`0.35`) would result in a `step_schedule_start` of `0.65`.
+ /// Default Value: 0.35F
+ /// Example: 0.4F + /// + /// + /// Skips a proportion of the start of the diffusion steps, allowing the init_image to influence the final generated image. Lower values will result in more influence from the init_image, while higher values will result in more influence from the diffusion steps. (e.g. a value of `0` would simply return you the init_image, where a value of `1` would return you a completely different image.)
+ /// Default Value: 0.65F
+ /// Example: 0.4F + /// + /// + /// Skips a proportion of the end of the diffusion steps, allowing the init_image to influence the final generated image. Lower values will result in more influence from the init_image, while higher values will result in more influence from the diffusion steps.
+ /// Example: 0.01F + /// + /// + /// How strictly the diffusion process adheres to the prompt text (higher values keep your image closer to your prompt)
+ /// Default Value: 7
+ /// Example: 7 + /// + /// + /// Default Value: NONE
+ /// Example: FAST_BLUE + /// + /// + /// Which sampler to use for the diffusion process. If this value is omitted we'll automatically select an appropriate sampler for you.
+ /// Example: K_DPM_2_ANCESTRAL + /// + /// + /// Number of images to generate
+ /// Default Value: 1
+ /// Example: 1 + /// + /// + /// Random noise seed (omit this option or use `0` for a random seed)
+ /// Default Value: 0
+ /// Example: 0 + /// + /// + /// Number of diffusion steps to run
+ /// Default Value: 50
+ /// Example: 75 + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// if [ -z "$STABILITY_API_KEY" ]; then
+ /// echo "STABILITY_API_KEY environment variable is not set"
+ /// exit 1
+ /// fi
+ /// OUTPUT_FILE=./out/v1_img2img.png
+ /// BASE_URL=${API_HOST:-https://api.stability.ai}
+ /// URL="$BASE_URL/v1/generation/stable-diffusion-v1-5/image-to-image"
+ /// curl -f -sS -X POST "$URL" \
+ /// -H 'Content-Type: multipart/form-data' \
+ /// -H 'Accept: image/png' \
+ /// -H "Authorization: Bearer $STABILITY_API_KEY" \
+ /// -F 'init_image=@"../init_image.png"' \
+ /// -F 'init_image_mode=IMAGE_STRENGTH' \
+ /// -F 'image_strength=0.35' \
+ /// -F 'text_prompts[0][text]=A galactic dog in space' \
+ /// -F 'cfg_scale=7' \
+ /// -F 'clip_guidance_preset=FAST_BLUE' \
+ /// -F 'samples=1' \
+ /// -F 'steps=30' \
+ /// -o "$OUTPUT_FILE" + ///
+ public async global::System.Threading.Tasks.Task> ImageToImageAsBytesAsResponseAsync( + string engineId, + global::System.Collections.Generic.IList textPrompts, + global::System.IO.Stream initImage, + string initImagename, + global::StabilityAI.ImageToImageAccept? accept = default, + string? organization = default, + float? imageStrength = default, + double? stepScheduleStart = default, + double? stepScheduleEnd = default, + double? cfgScale = default, + global::StabilityAI.ClipGuidancePreset? clipGuidancePreset = default, + global::StabilityAI.Sampler? sampler = default, + int? samples = default, + long? seed = default, + int? steps = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + + initImage = initImage ?? throw new global::System.ArgumentNullException(nameof(initImage)); + var request = new global::StabilityAI.ImageToImageRequestBody + { + TextPrompts = textPrompts, + InitImage = global::System.Array.Empty(), + InitImagename = initImagename, + ImageStrength = imageStrength, + StepScheduleStart = stepScheduleStart, + StepScheduleEnd = stepScheduleEnd, + CfgScale = cfgScale, + ClipGuidancePreset = clipGuidancePreset, + Sampler = sampler, + Samples = samples, + Seed = seed, + Steps = steps, + }; + PrepareArguments( + client: HttpClient); + PrepareImageToImageAsBytesArguments( + httpClient: HttpClient, + engineId: ref engineId, + accept: ref accept, + organization: ref organization, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_ImageToImageAsBytesSecurityRequirements, + operationName: "ImageToImageAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: $"/v1/generation/{engineId}/image-to-image", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/png"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("Accept", accept?.ToValueString() ?? string.Empty); + } + if (organization != default) + { + __httpRequest.Headers.TryAddWithoutValidation("Organization", organization.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent($"[{string.Join(",", global::System.Linq.Enumerable.Select(request.TextPrompts, x => x.ToJson(JsonSerializerContext)))}]"), + name: "\"text_prompts\""); + + var __contentInitImage = new global::System.Net.Http.StreamContent(initImage); + __contentInitImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.InitImagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.InitImagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentInitImage, + name: "\"init_image\"", + fileName: request.InitImagename != null ? $"\"{request.InitImagename}\"" : string.Empty); + if (__contentInitImage.Headers.ContentDisposition != null) + { + __contentInitImage.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.ImageStrength != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.ImageStrength, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"image_strength\""); + + } + if (request.StepScheduleStart != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.StepScheduleStart, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"step_schedule_start\""); + + } + if (request.StepScheduleEnd != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.StepScheduleEnd, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"step_schedule_end\""); + + } + if (request.CfgScale != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.CfgScale, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"cfg_scale\""); + + } + if (request.ClipGuidancePreset != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.ClipGuidancePreset).HasValue ? (request.ClipGuidancePreset).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"clip_guidance_preset\""); + + } + if (request.Sampler != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.Sampler).HasValue ? (request.Sampler).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"sampler\""); + + } + if (request.Samples != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Samples, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"samples\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.Steps != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Steps, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"steps\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareImageToImageAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + engineId: engineId!, + accept: accept, + organization: organization, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "ImageToImageAsBytes", + methodName: "ImageToImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "ImageToImageAsBytes", + methodName: "ImageToImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "ImageToImageAsBytes", + methodName: "ImageToImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessImageToImageAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "ImageToImageAsBytes", + methodName: "ImageToImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "ImageToImageAsBytes", + methodName: "ImageToImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // bad_request: general error for invalid parameters

More specific errors:

- invalid_samples: Sample count may only be greater than 1 when the accept header is set to `application/json` - invalid_height_or_width: Height and width must be specified in increments of 64 - invalid_file_size: The file size of one or more of the provided files is invalid - invalid_mime_type: The mime type of one or more of the provided files is invalid - invalid_image_dimensions: The dimensions of the provided `init_image` and `mask_image` do not match - invalid_mask_image: The parameter `mask_source` was set to `MASK_IMAGE_WHITE` or `MASK_IMAGE_BLACK` but no `mask_image` was provided - invalid_prompts: One or more of the prompts contains filtered words - invalid_pixel_count: Incorrect number of pixels specified. Requirements: - For 768 engines : 589,824 ≤ `height * width` ≤ 1,048,576 - All other engines: 262,144 ≤ `height * width` ≤ 1,048,576 + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.Error? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.Error.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.Error.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // unauthorized: API key missing or invalid + if ((int)__response.StatusCode == 401) + { + string? __content_401 = null; + global::System.Exception? __exception_401 = null; + global::StabilityAI.Error? __value_401 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_401 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_401 = global::StabilityAI.Error.FromJson(__content_401, JsonSerializerContext); + } + else + { + __content_401 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_401 = global::StabilityAI.Error.FromJson(__content_401, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_401 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_401 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_401, + responseBody: __content_401, + responseObject: __value_401, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // permission_denied: You lack the necessary permissions to perform this action + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.Error? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.Error.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.Error.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // not_found: The requested resource was not found (e.g. specifing a model that does not exist) + if ((int)__response.StatusCode == 404) + { + string? __content_404 = null; + global::System.Exception? __exception_404 = null; + global::StabilityAI.Error? __value_404 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_404 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_404 = global::StabilityAI.Error.FromJson(__content_404, JsonSerializerContext); + } + else + { + __content_404 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_404 = global::StabilityAI.Error.FromJson(__content_404, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_404 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_404 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_404, + responseBody: __content_404, + responseObject: __value_404, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // server_error: Some unexpected server error occurred + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.Error? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.Error.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.Error.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessImageToImageAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + } +} \ No newline at end of file diff --git a/src/libs/StabilityAI/Generated/StabilityAI.V1GenerationClient.Masking.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.V1GenerationClient.Masking.g.cs index 9947d36..4d5e144 100644 --- a/src/libs/StabilityAI/Generated/StabilityAI.V1GenerationClient.Masking.g.cs +++ b/src/libs/StabilityAI/Generated/StabilityAI.V1GenerationClient.Masking.g.cs @@ -201,6 +201,10 @@ partial void ProcessMaskingResponseContent( __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || @@ -229,26 +233,6 @@ partial void ProcessMaskingResponseContent( var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(engineId ?? string.Empty), - name: "\"engine_id\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"Accept\""); - - } - if (organization != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(organization ?? string.Empty), - name: "\"Organization\""); - - } var __contentInitImage = new global::System.Net.Http.ByteArrayContent(request.InitImage ?? global::System.Array.Empty()); __contentInitImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( request.InitImagename is null @@ -1154,6 +1138,10 @@ request.MaskImagename is null __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || @@ -1182,26 +1170,6 @@ request.MaskImagename is null var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(engineId ?? string.Empty), - name: "\"engine_id\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"Accept\""); - - } - if (organization != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(organization ?? string.Empty), - name: "\"Organization\""); - - } var __contentInitImage = new global::System.Net.Http.StreamContent(initImage); __contentInitImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( request.InitImagename is null @@ -1983,6 +1951,10 @@ request.MaskImagename is null __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || @@ -2011,26 +1983,6 @@ request.MaskImagename is null var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(engineId ?? string.Empty), - name: "\"engine_id\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"Accept\""); - - } - if (organization != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(organization ?? string.Empty), - name: "\"Organization\""); - - } var __contentInitImage = new global::System.Net.Http.StreamContent(initImage); __contentInitImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( request.InitImagename is null diff --git a/src/libs/StabilityAI/Generated/StabilityAI.V1GenerationClient.MaskingAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.V1GenerationClient.MaskingAsBytes.g.cs new file mode 100644 index 0000000..71e6945 --- /dev/null +++ b/src/libs/StabilityAI/Generated/StabilityAI.V1GenerationClient.MaskingAsBytes.g.cs @@ -0,0 +1,4040 @@ + +#nullable enable + +namespace StabilityAI +{ + public partial class V1GenerationClient + { + + + private static readonly global::StabilityAI.EndPointSecurityRequirement s_MaskingAsBytesSecurityRequirement0 = + new global::StabilityAI.EndPointSecurityRequirement + { + Authorizations = new global::StabilityAI.EndPointAuthorizationRequirement[] + { new global::StabilityAI.EndPointAuthorizationRequirement + { + Type = "Http", + SchemeId = "HttpBearer", + Location = "Header", + Name = "Bearer", + FriendlyName = "Bearer", + }, + }, + }; + private static readonly global::StabilityAI.EndPointSecurityRequirement[] s_MaskingAsBytesSecurityRequirements = + new global::StabilityAI.EndPointSecurityRequirement[] + { s_MaskingAsBytesSecurityRequirement0, + }; + partial void PrepareMaskingAsBytesArguments( + global::System.Net.Http.HttpClient httpClient, + ref string engineId, + ref global::StabilityAI.MaskingAccept? accept, + ref string? organization, + global::StabilityAI.MaskingRequestBody request); + partial void PrepareMaskingAsBytesRequest( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpRequestMessage httpRequestMessage, + string engineId, + global::StabilityAI.MaskingAccept? accept, + string? organization, + global::StabilityAI.MaskingRequestBody request); + partial void ProcessMaskingAsBytesResponse( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpResponseMessage httpResponseMessage); + + partial void ProcessMaskingAsBytesResponseContent( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpResponseMessage httpResponseMessage, + ref byte[] content); + + /// + /// image-to-image/masking
+ /// Selectively modify portions of an image using a mask + ///
+ /// + /// + /// Default Value: application/json + /// + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// #!/bin/sh
+ /// set -e
+ /// if [ -z "$STABILITY_API_KEY" ]; then
+ /// echo "STABILITY_API_KEY environment variable is not set"
+ /// exit 1
+ /// fi
+ /// OUTPUT_FILE=./out/v1_img2img_masking.png
+ /// BASE_URL=${API_HOST:-https://api.stability.ai}
+ /// URL="$BASE_URL/v1/generation/stable-inpainting-512-v2-0/image-to-image/masking"
+ /// curl -f -sS -X POST "$URL" \
+ /// -H 'Content-Type: multipart/form-data' \
+ /// -H 'Accept: image/png' \
+ /// -H "Authorization: Bearer $STABILITY_API_KEY" \
+ /// -F 'init_image=@"../init_image.png"' \
+ /// -F 'mask_image=@"../mask_image_white.png"' \
+ /// -F 'mask_source=MASK_IMAGE_WHITE' \
+ /// -F 'text_prompts[0][text]=A large spiral galaxy with a bright central bulge and a ring of stars around it' \
+ /// -F 'cfg_scale=7' \
+ /// -F 'clip_guidance_preset=FAST_BLUE' \
+ /// -F 'samples=1' \
+ /// -F 'steps=30' \
+ /// -o "$OUTPUT_FILE" + ///
+ public async global::System.Threading.Tasks.Task MaskingAsBytesAsync( + string engineId, + + global::StabilityAI.MaskingRequestBody request, + global::StabilityAI.MaskingAccept? accept = default, + string? organization = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + var __response = await MaskingAsBytesAsResponseAsync( + engineId: engineId, + + request: request, + accept: accept, + organization: organization, + requestOptions: requestOptions, + cancellationToken: cancellationToken + ).ConfigureAwait(false); + + return __response.Body; + } + /// + /// image-to-image/masking
+ /// Selectively modify portions of an image using a mask + ///
+ /// + /// + /// Default Value: application/json + /// + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// #!/bin/sh
+ /// set -e
+ /// if [ -z "$STABILITY_API_KEY" ]; then
+ /// echo "STABILITY_API_KEY environment variable is not set"
+ /// exit 1
+ /// fi
+ /// OUTPUT_FILE=./out/v1_img2img_masking.png
+ /// BASE_URL=${API_HOST:-https://api.stability.ai}
+ /// URL="$BASE_URL/v1/generation/stable-inpainting-512-v2-0/image-to-image/masking"
+ /// curl -f -sS -X POST "$URL" \
+ /// -H 'Content-Type: multipart/form-data' \
+ /// -H 'Accept: image/png' \
+ /// -H "Authorization: Bearer $STABILITY_API_KEY" \
+ /// -F 'init_image=@"../init_image.png"' \
+ /// -F 'mask_image=@"../mask_image_white.png"' \
+ /// -F 'mask_source=MASK_IMAGE_WHITE' \
+ /// -F 'text_prompts[0][text]=A large spiral galaxy with a bright central bulge and a ring of stars around it' \
+ /// -F 'cfg_scale=7' \
+ /// -F 'clip_guidance_preset=FAST_BLUE' \
+ /// -F 'samples=1' \
+ /// -F 'steps=30' \
+ /// -o "$OUTPUT_FILE" + ///
+ public async global::System.Threading.Tasks.Task MaskingAsBytesAsStreamAsync( + string engineId, + + global::StabilityAI.MaskingRequestBody request, + global::StabilityAI.MaskingAccept? accept = default, + string? organization = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + request = request ?? throw new global::System.ArgumentNullException(nameof(request)); + + PrepareArguments( + client: HttpClient); + PrepareMaskingAsBytesArguments( + httpClient: HttpClient, + engineId: ref engineId, + accept: ref accept, + organization: ref organization, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_MaskingAsBytesSecurityRequirements, + operationName: "MaskingAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: $"/v1/generation/{engineId}/image-to-image/masking", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/png"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("Accept", accept?.ToValueString() ?? string.Empty); + } + if (organization != default) + { + __httpRequest.Headers.TryAddWithoutValidation("Organization", organization.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + var __contentInitImage = new global::System.Net.Http.ByteArrayContent(request.InitImage ?? global::System.Array.Empty()); + __contentInitImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.InitImagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.InitImagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentInitImage, + name: "\"init_image\"", + fileName: request.InitImagename != null ? $"\"{request.InitImagename}\"" : string.Empty); + if (__contentInitImage.Headers.ContentDisposition != null) + { + __contentInitImage.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.MaskImage != default) + { + + var __contentMaskImage = new global::System.Net.Http.ByteArrayContent(request.MaskImage ?? global::System.Array.Empty()); + __contentMaskImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.MaskImagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.MaskImagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentMaskImage, + name: "\"mask_image\"", + fileName: request.MaskImagename != null ? $"\"{request.MaskImagename}\"" : string.Empty); + if (__contentMaskImage.Headers.ContentDisposition != null) + { + __contentMaskImage.Headers.ContentDisposition.FileNameStar = null; + } + + } + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent($"[{string.Join(",", global::System.Linq.Enumerable.Select(request.TextPrompts, x => x.ToJson(JsonSerializerContext)))}]"), + name: "\"text_prompts\""); + + if (request.CfgScale != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.CfgScale, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"cfg_scale\""); + + } + if (request.ClipGuidancePreset != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.ClipGuidancePreset).HasValue ? (request.ClipGuidancePreset).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"clip_guidance_preset\""); + + } + if (request.Sampler != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.Sampler).HasValue ? (request.Sampler).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"sampler\""); + + } + if (request.Samples != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Samples, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"samples\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.Steps != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Steps, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"steps\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareMaskingAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + engineId: engineId!, + accept: accept, + organization: organization, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "MaskingAsBytes", + methodName: "MaskingAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image/masking\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseHeadersRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "MaskingAsBytes", + methodName: "MaskingAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image/masking\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "MaskingAsBytes", + methodName: "MaskingAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image/masking\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + try + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessMaskingAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "MaskingAsBytes", + methodName: "MaskingAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image/masking\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "MaskingAsBytes", + methodName: "MaskingAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image/masking\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // bad_request: general error for invalid parameters

More specific errors:

- invalid_samples: Sample count may only be greater than 1 when the accept header is set to `application/json` - invalid_height_or_width: Height and width must be specified in increments of 64 - invalid_file_size: The file size of one or more of the provided files is invalid - invalid_mime_type: The mime type of one or more of the provided files is invalid - invalid_image_dimensions: The dimensions of the provided `init_image` and `mask_image` do not match - invalid_mask_image: The parameter `mask_source` was set to `MASK_IMAGE_WHITE` or `MASK_IMAGE_BLACK` but no `mask_image` was provided - invalid_prompts: One or more of the prompts contains filtered words - invalid_pixel_count: Incorrect number of pixels specified. Requirements: - For 768 engines : 589,824 ≤ `height * width` ≤ 1,048,576 - All other engines: 262,144 ≤ `height * width` ≤ 1,048,576 + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.Error? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.Error.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.Error.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // unauthorized: API key missing or invalid + if ((int)__response.StatusCode == 401) + { + string? __content_401 = null; + global::System.Exception? __exception_401 = null; + global::StabilityAI.Error? __value_401 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_401 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_401 = global::StabilityAI.Error.FromJson(__content_401, JsonSerializerContext); + } + else + { + __content_401 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_401 = global::StabilityAI.Error.FromJson(__content_401, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_401 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_401 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_401, + responseBody: __content_401, + responseObject: __value_401, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // permission_denied: You lack the necessary permissions to perform this action + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.Error? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.Error.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.Error.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // not_found: The requested resource was not found (e.g. specifing a model that does not exist) + if ((int)__response.StatusCode == 404) + { + string? __content_404 = null; + global::System.Exception? __exception_404 = null; + global::StabilityAI.Error? __value_404 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_404 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_404 = global::StabilityAI.Error.FromJson(__content_404, JsonSerializerContext); + } + else + { + __content_404 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_404 = global::StabilityAI.Error.FromJson(__content_404, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_404 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_404 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_404, + responseBody: __content_404, + responseObject: __value_404, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // server_error: Some unexpected server error occurred + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.Error? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.Error.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.Error.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + try + { + __response.EnsureSuccessStatusCode(); + + var __content = await __response.Content.ReadAsStreamAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.ResponseStream(__response, __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + } + catch + { + __response.Dispose(); + throw; + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// image-to-image/masking
+ /// Selectively modify portions of an image using a mask + ///
+ /// + /// + /// Default Value: application/json + /// + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// #!/bin/sh
+ /// set -e
+ /// if [ -z "$STABILITY_API_KEY" ]; then
+ /// echo "STABILITY_API_KEY environment variable is not set"
+ /// exit 1
+ /// fi
+ /// OUTPUT_FILE=./out/v1_img2img_masking.png
+ /// BASE_URL=${API_HOST:-https://api.stability.ai}
+ /// URL="$BASE_URL/v1/generation/stable-inpainting-512-v2-0/image-to-image/masking"
+ /// curl -f -sS -X POST "$URL" \
+ /// -H 'Content-Type: multipart/form-data' \
+ /// -H 'Accept: image/png' \
+ /// -H "Authorization: Bearer $STABILITY_API_KEY" \
+ /// -F 'init_image=@"../init_image.png"' \
+ /// -F 'mask_image=@"../mask_image_white.png"' \
+ /// -F 'mask_source=MASK_IMAGE_WHITE' \
+ /// -F 'text_prompts[0][text]=A large spiral galaxy with a bright central bulge and a ring of stars around it' \
+ /// -F 'cfg_scale=7' \
+ /// -F 'clip_guidance_preset=FAST_BLUE' \
+ /// -F 'samples=1' \
+ /// -F 'steps=30' \
+ /// -o "$OUTPUT_FILE" + ///
+ public async global::System.Threading.Tasks.Task> MaskingAsBytesAsResponseAsync( + string engineId, + + global::StabilityAI.MaskingRequestBody request, + global::StabilityAI.MaskingAccept? accept = default, + string? organization = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + request = request ?? throw new global::System.ArgumentNullException(nameof(request)); + + PrepareArguments( + client: HttpClient); + PrepareMaskingAsBytesArguments( + httpClient: HttpClient, + engineId: ref engineId, + accept: ref accept, + organization: ref organization, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_MaskingAsBytesSecurityRequirements, + operationName: "MaskingAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: $"/v1/generation/{engineId}/image-to-image/masking", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/png"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("Accept", accept?.ToValueString() ?? string.Empty); + } + if (organization != default) + { + __httpRequest.Headers.TryAddWithoutValidation("Organization", organization.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + var __contentInitImage = new global::System.Net.Http.ByteArrayContent(request.InitImage ?? global::System.Array.Empty()); + __contentInitImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.InitImagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.InitImagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentInitImage, + name: "\"init_image\"", + fileName: request.InitImagename != null ? $"\"{request.InitImagename}\"" : string.Empty); + if (__contentInitImage.Headers.ContentDisposition != null) + { + __contentInitImage.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.MaskImage != default) + { + + var __contentMaskImage = new global::System.Net.Http.ByteArrayContent(request.MaskImage ?? global::System.Array.Empty()); + __contentMaskImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.MaskImagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.MaskImagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentMaskImage, + name: "\"mask_image\"", + fileName: request.MaskImagename != null ? $"\"{request.MaskImagename}\"" : string.Empty); + if (__contentMaskImage.Headers.ContentDisposition != null) + { + __contentMaskImage.Headers.ContentDisposition.FileNameStar = null; + } + + } + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent($"[{string.Join(",", global::System.Linq.Enumerable.Select(request.TextPrompts, x => x.ToJson(JsonSerializerContext)))}]"), + name: "\"text_prompts\""); + + if (request.CfgScale != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.CfgScale, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"cfg_scale\""); + + } + if (request.ClipGuidancePreset != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.ClipGuidancePreset).HasValue ? (request.ClipGuidancePreset).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"clip_guidance_preset\""); + + } + if (request.Sampler != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.Sampler).HasValue ? (request.Sampler).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"sampler\""); + + } + if (request.Samples != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Samples, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"samples\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.Steps != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Steps, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"steps\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareMaskingAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + engineId: engineId!, + accept: accept, + organization: organization, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "MaskingAsBytes", + methodName: "MaskingAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image/masking\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "MaskingAsBytes", + methodName: "MaskingAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image/masking\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "MaskingAsBytes", + methodName: "MaskingAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image/masking\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessMaskingAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "MaskingAsBytes", + methodName: "MaskingAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image/masking\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "MaskingAsBytes", + methodName: "MaskingAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image/masking\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // bad_request: general error for invalid parameters

More specific errors:

- invalid_samples: Sample count may only be greater than 1 when the accept header is set to `application/json` - invalid_height_or_width: Height and width must be specified in increments of 64 - invalid_file_size: The file size of one or more of the provided files is invalid - invalid_mime_type: The mime type of one or more of the provided files is invalid - invalid_image_dimensions: The dimensions of the provided `init_image` and `mask_image` do not match - invalid_mask_image: The parameter `mask_source` was set to `MASK_IMAGE_WHITE` or `MASK_IMAGE_BLACK` but no `mask_image` was provided - invalid_prompts: One or more of the prompts contains filtered words - invalid_pixel_count: Incorrect number of pixels specified. Requirements: - For 768 engines : 589,824 ≤ `height * width` ≤ 1,048,576 - All other engines: 262,144 ≤ `height * width` ≤ 1,048,576 + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.Error? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.Error.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.Error.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // unauthorized: API key missing or invalid + if ((int)__response.StatusCode == 401) + { + string? __content_401 = null; + global::System.Exception? __exception_401 = null; + global::StabilityAI.Error? __value_401 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_401 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_401 = global::StabilityAI.Error.FromJson(__content_401, JsonSerializerContext); + } + else + { + __content_401 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_401 = global::StabilityAI.Error.FromJson(__content_401, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_401 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_401 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_401, + responseBody: __content_401, + responseObject: __value_401, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // permission_denied: You lack the necessary permissions to perform this action + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.Error? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.Error.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.Error.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // not_found: The requested resource was not found (e.g. specifing a model that does not exist) + if ((int)__response.StatusCode == 404) + { + string? __content_404 = null; + global::System.Exception? __exception_404 = null; + global::StabilityAI.Error? __value_404 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_404 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_404 = global::StabilityAI.Error.FromJson(__content_404, JsonSerializerContext); + } + else + { + __content_404 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_404 = global::StabilityAI.Error.FromJson(__content_404, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_404 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_404 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_404, + responseBody: __content_404, + responseObject: __value_404, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // server_error: Some unexpected server error occurred + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.Error? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.Error.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.Error.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessMaskingAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// image-to-image/masking
+ /// Selectively modify portions of an image using a mask + ///
+ /// + /// + /// Default Value: application/json + /// + /// + /// + /// Image used to initialize the diffusion process, in lieu of random noise.
+ /// Example: <image binary> + /// + /// + /// Image used to initialize the diffusion process, in lieu of random noise.
+ /// Example: <image binary> + /// + /// + /// Optional grayscale mask that allows for influence over which pixels are eligible for diffusion and at what strength. Must be the same dimensions as the `init_image`. Use the `mask_source` option to specify whether the white or black pixels should be inpainted.
+ /// Example: <image binary> + /// + /// + /// Optional grayscale mask that allows for influence over which pixels are eligible for diffusion and at what strength. Must be the same dimensions as the `init_image`. Use the `mask_source` option to specify whether the white or black pixels should be inpainted.
+ /// Example: <image binary> + /// + /// + /// An array of text prompts to use for generation.
+ /// Due to how arrays are represented in `multipart/form-data` requests, prompts must adhear to the format `text_prompts[index][text|weight]`,
+ /// where `index` is some integer used to tie the text and weight together. While `index` does not have to be sequential, duplicate entries
+ /// will override previous entries, so it is recommended to use sequential indices.
+ /// Given a text prompt with the text `A lighthouse on a cliff` and a weight of `0.5`, it would be represented as:
+ /// ```
+ /// text_prompts[0][text]: "A lighthouse on a cliff"
+ /// text_prompts[0][weight]: 0.5
+ /// ```
+ /// To add another prompt to that request simply provide the values under a new `index`:
+ /// ```
+ /// text_prompts[0][text]: "A lighthouse on a cliff"
+ /// text_prompts[0][weight]: 0.5
+ /// text_prompts[1][text]: "land, ground, dirt, grass"
+ /// text_prompts[1][weight]: -0.9
+ /// ``` + /// + /// + /// How strictly the diffusion process adheres to the prompt text (higher values keep your image closer to your prompt)
+ /// Default Value: 7
+ /// Example: 7 + /// + /// + /// Default Value: NONE
+ /// Example: FAST_BLUE + /// + /// + /// Which sampler to use for the diffusion process. If this value is omitted we'll automatically select an appropriate sampler for you.
+ /// Example: K_DPM_2_ANCESTRAL + /// + /// + /// Number of images to generate
+ /// Default Value: 1
+ /// Example: 1 + /// + /// + /// Random noise seed (omit this option or use `0` for a random seed)
+ /// Default Value: 0
+ /// Example: 0 + /// + /// + /// Number of diffusion steps to run
+ /// Default Value: 50
+ /// Example: 75 + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + public async global::System.Threading.Tasks.Task MaskingAsBytesAsync( + string engineId, + byte[] initImage, + string initImagename, + global::System.Collections.Generic.IList textPrompts, + global::StabilityAI.MaskingAccept? accept = default, + string? organization = default, + byte[]? maskImage = default, + string? maskImagename = default, + double? cfgScale = default, + global::StabilityAI.ClipGuidancePreset? clipGuidancePreset = default, + global::StabilityAI.Sampler? sampler = default, + int? samples = default, + long? seed = default, + int? steps = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + var __request = new global::StabilityAI.MaskingRequestBody + { + InitImage = initImage, + InitImagename = initImagename, + MaskImage = maskImage, + MaskImagename = maskImagename, + TextPrompts = textPrompts, + CfgScale = cfgScale, + ClipGuidancePreset = clipGuidancePreset, + Sampler = sampler, + Samples = samples, + Seed = seed, + Steps = steps, + }; + + return await MaskingAsBytesAsync( + engineId: engineId, + accept: accept, + organization: organization, + request: __request, + requestOptions: requestOptions, + cancellationToken: cancellationToken).ConfigureAwait(false); + } + + /// + /// image-to-image/masking
+ /// Selectively modify portions of an image using a mask + ///
+ /// + /// + /// Default Value: application/json + /// + /// + /// + /// Image used to initialize the diffusion process, in lieu of random noise.
+ /// Example: <image binary> + /// + /// + /// Image used to initialize the diffusion process, in lieu of random noise.
+ /// Example: <image binary> + /// + /// + /// Optional grayscale mask that allows for influence over which pixels are eligible for diffusion and at what strength. Must be the same dimensions as the `init_image`. Use the `mask_source` option to specify whether the white or black pixels should be inpainted.
+ /// Example: <image binary> + /// + /// + /// Optional grayscale mask that allows for influence over which pixels are eligible for diffusion and at what strength. Must be the same dimensions as the `init_image`. Use the `mask_source` option to specify whether the white or black pixels should be inpainted.
+ /// Example: <image binary> + /// + /// + /// An array of text prompts to use for generation.
+ /// Due to how arrays are represented in `multipart/form-data` requests, prompts must adhear to the format `text_prompts[index][text|weight]`,
+ /// where `index` is some integer used to tie the text and weight together. While `index` does not have to be sequential, duplicate entries
+ /// will override previous entries, so it is recommended to use sequential indices.
+ /// Given a text prompt with the text `A lighthouse on a cliff` and a weight of `0.5`, it would be represented as:
+ /// ```
+ /// text_prompts[0][text]: "A lighthouse on a cliff"
+ /// text_prompts[0][weight]: 0.5
+ /// ```
+ /// To add another prompt to that request simply provide the values under a new `index`:
+ /// ```
+ /// text_prompts[0][text]: "A lighthouse on a cliff"
+ /// text_prompts[0][weight]: 0.5
+ /// text_prompts[1][text]: "land, ground, dirt, grass"
+ /// text_prompts[1][weight]: -0.9
+ /// ``` + /// + /// + /// How strictly the diffusion process adheres to the prompt text (higher values keep your image closer to your prompt)
+ /// Default Value: 7
+ /// Example: 7 + /// + /// + /// Default Value: NONE
+ /// Example: FAST_BLUE + /// + /// + /// Which sampler to use for the diffusion process. If this value is omitted we'll automatically select an appropriate sampler for you.
+ /// Example: K_DPM_2_ANCESTRAL + /// + /// + /// Number of images to generate
+ /// Default Value: 1
+ /// Example: 1 + /// + /// + /// Random noise seed (omit this option or use `0` for a random seed)
+ /// Default Value: 0
+ /// Example: 0 + /// + /// + /// Number of diffusion steps to run
+ /// Default Value: 50
+ /// Example: 75 + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// #!/bin/sh
+ /// set -e
+ /// if [ -z "$STABILITY_API_KEY" ]; then
+ /// echo "STABILITY_API_KEY environment variable is not set"
+ /// exit 1
+ /// fi
+ /// OUTPUT_FILE=./out/v1_img2img_masking.png
+ /// BASE_URL=${API_HOST:-https://api.stability.ai}
+ /// URL="$BASE_URL/v1/generation/stable-inpainting-512-v2-0/image-to-image/masking"
+ /// curl -f -sS -X POST "$URL" \
+ /// -H 'Content-Type: multipart/form-data' \
+ /// -H 'Accept: image/png' \
+ /// -H "Authorization: Bearer $STABILITY_API_KEY" \
+ /// -F 'init_image=@"../init_image.png"' \
+ /// -F 'mask_image=@"../mask_image_white.png"' \
+ /// -F 'mask_source=MASK_IMAGE_WHITE' \
+ /// -F 'text_prompts[0][text]=A large spiral galaxy with a bright central bulge and a ring of stars around it' \
+ /// -F 'cfg_scale=7' \
+ /// -F 'clip_guidance_preset=FAST_BLUE' \
+ /// -F 'samples=1' \
+ /// -F 'steps=30' \
+ /// -o "$OUTPUT_FILE" + ///
+ public async global::System.Threading.Tasks.Task MaskingAsBytesAsync( + string engineId, + global::System.IO.Stream initImage, + string initImagename, + global::System.Collections.Generic.IList textPrompts, + global::StabilityAI.MaskingAccept? accept = default, + string? organization = default, + global::System.IO.Stream? maskImage = default, + string? maskImagename = default, + double? cfgScale = default, + global::StabilityAI.ClipGuidancePreset? clipGuidancePreset = default, + global::StabilityAI.Sampler? sampler = default, + int? samples = default, + long? seed = default, + int? steps = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + + initImage = initImage ?? throw new global::System.ArgumentNullException(nameof(initImage)); + var request = new global::StabilityAI.MaskingRequestBody + { + InitImage = global::System.Array.Empty(), + InitImagename = initImagename, + MaskImage = global::System.Array.Empty(), + MaskImagename = maskImagename, + TextPrompts = textPrompts, + CfgScale = cfgScale, + ClipGuidancePreset = clipGuidancePreset, + Sampler = sampler, + Samples = samples, + Seed = seed, + Steps = steps, + }; + PrepareArguments( + client: HttpClient); + PrepareMaskingAsBytesArguments( + httpClient: HttpClient, + engineId: ref engineId, + accept: ref accept, + organization: ref organization, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_MaskingAsBytesSecurityRequirements, + operationName: "MaskingAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: $"/v1/generation/{engineId}/image-to-image/masking", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/png"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("Accept", accept?.ToValueString() ?? string.Empty); + } + if (organization != default) + { + __httpRequest.Headers.TryAddWithoutValidation("Organization", organization.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + var __contentInitImage = new global::System.Net.Http.StreamContent(initImage); + __contentInitImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.InitImagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.InitImagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentInitImage, + name: "\"init_image\"", + fileName: request.InitImagename != null ? $"\"{request.InitImagename}\"" : string.Empty); + if (__contentInitImage.Headers.ContentDisposition != null) + { + __contentInitImage.Headers.ContentDisposition.FileNameStar = null; + } + + if (maskImage != default) + { + + var __contentMaskImage = new global::System.Net.Http.StreamContent(maskImage); + __contentMaskImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.MaskImagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.MaskImagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentMaskImage, + name: "\"mask_image\"", + fileName: request.MaskImagename != null ? $"\"{request.MaskImagename}\"" : string.Empty); + if (__contentMaskImage.Headers.ContentDisposition != null) + { + __contentMaskImage.Headers.ContentDisposition.FileNameStar = null; + } + + } + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent($"[{string.Join(",", global::System.Linq.Enumerable.Select(request.TextPrompts, x => x.ToJson(JsonSerializerContext)))}]"), + name: "\"text_prompts\""); + + if (request.CfgScale != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.CfgScale, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"cfg_scale\""); + + } + if (request.ClipGuidancePreset != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.ClipGuidancePreset).HasValue ? (request.ClipGuidancePreset).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"clip_guidance_preset\""); + + } + if (request.Sampler != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.Sampler).HasValue ? (request.Sampler).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"sampler\""); + + } + if (request.Samples != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Samples, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"samples\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.Steps != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Steps, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"steps\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareMaskingAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + engineId: engineId!, + accept: accept, + organization: organization, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "MaskingAsBytes", + methodName: "MaskingAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image/masking\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "MaskingAsBytes", + methodName: "MaskingAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image/masking\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "MaskingAsBytes", + methodName: "MaskingAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image/masking\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessMaskingAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "MaskingAsBytes", + methodName: "MaskingAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image/masking\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "MaskingAsBytes", + methodName: "MaskingAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image/masking\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // bad_request: general error for invalid parameters

More specific errors:

- invalid_samples: Sample count may only be greater than 1 when the accept header is set to `application/json` - invalid_height_or_width: Height and width must be specified in increments of 64 - invalid_file_size: The file size of one or more of the provided files is invalid - invalid_mime_type: The mime type of one or more of the provided files is invalid - invalid_image_dimensions: The dimensions of the provided `init_image` and `mask_image` do not match - invalid_mask_image: The parameter `mask_source` was set to `MASK_IMAGE_WHITE` or `MASK_IMAGE_BLACK` but no `mask_image` was provided - invalid_prompts: One or more of the prompts contains filtered words - invalid_pixel_count: Incorrect number of pixels specified. Requirements: - For 768 engines : 589,824 ≤ `height * width` ≤ 1,048,576 - All other engines: 262,144 ≤ `height * width` ≤ 1,048,576 + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.Error? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.Error.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.Error.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // unauthorized: API key missing or invalid + if ((int)__response.StatusCode == 401) + { + string? __content_401 = null; + global::System.Exception? __exception_401 = null; + global::StabilityAI.Error? __value_401 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_401 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_401 = global::StabilityAI.Error.FromJson(__content_401, JsonSerializerContext); + } + else + { + __content_401 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_401 = global::StabilityAI.Error.FromJson(__content_401, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_401 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_401 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_401, + responseBody: __content_401, + responseObject: __value_401, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // permission_denied: You lack the necessary permissions to perform this action + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.Error? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.Error.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.Error.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // not_found: The requested resource was not found (e.g. specifing a model that does not exist) + if ((int)__response.StatusCode == 404) + { + string? __content_404 = null; + global::System.Exception? __exception_404 = null; + global::StabilityAI.Error? __value_404 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_404 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_404 = global::StabilityAI.Error.FromJson(__content_404, JsonSerializerContext); + } + else + { + __content_404 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_404 = global::StabilityAI.Error.FromJson(__content_404, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_404 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_404 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_404, + responseBody: __content_404, + responseObject: __value_404, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // server_error: Some unexpected server error occurred + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.Error? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.Error.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.Error.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessMaskingAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return __content; + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return __content; + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// image-to-image/masking
+ /// Selectively modify portions of an image using a mask + ///
+ /// + /// + /// Default Value: application/json + /// + /// + /// + /// Image used to initialize the diffusion process, in lieu of random noise.
+ /// Example: <image binary> + /// + /// + /// Image used to initialize the diffusion process, in lieu of random noise.
+ /// Example: <image binary> + /// + /// + /// Optional grayscale mask that allows for influence over which pixels are eligible for diffusion and at what strength. Must be the same dimensions as the `init_image`. Use the `mask_source` option to specify whether the white or black pixels should be inpainted.
+ /// Example: <image binary> + /// + /// + /// Optional grayscale mask that allows for influence over which pixels are eligible for diffusion and at what strength. Must be the same dimensions as the `init_image`. Use the `mask_source` option to specify whether the white or black pixels should be inpainted.
+ /// Example: <image binary> + /// + /// + /// An array of text prompts to use for generation.
+ /// Due to how arrays are represented in `multipart/form-data` requests, prompts must adhear to the format `text_prompts[index][text|weight]`,
+ /// where `index` is some integer used to tie the text and weight together. While `index` does not have to be sequential, duplicate entries
+ /// will override previous entries, so it is recommended to use sequential indices.
+ /// Given a text prompt with the text `A lighthouse on a cliff` and a weight of `0.5`, it would be represented as:
+ /// ```
+ /// text_prompts[0][text]: "A lighthouse on a cliff"
+ /// text_prompts[0][weight]: 0.5
+ /// ```
+ /// To add another prompt to that request simply provide the values under a new `index`:
+ /// ```
+ /// text_prompts[0][text]: "A lighthouse on a cliff"
+ /// text_prompts[0][weight]: 0.5
+ /// text_prompts[1][text]: "land, ground, dirt, grass"
+ /// text_prompts[1][weight]: -0.9
+ /// ``` + /// + /// + /// How strictly the diffusion process adheres to the prompt text (higher values keep your image closer to your prompt)
+ /// Default Value: 7
+ /// Example: 7 + /// + /// + /// Default Value: NONE
+ /// Example: FAST_BLUE + /// + /// + /// Which sampler to use for the diffusion process. If this value is omitted we'll automatically select an appropriate sampler for you.
+ /// Example: K_DPM_2_ANCESTRAL + /// + /// + /// Number of images to generate
+ /// Default Value: 1
+ /// Example: 1 + /// + /// + /// Random noise seed (omit this option or use `0` for a random seed)
+ /// Default Value: 0
+ /// Example: 0 + /// + /// + /// Number of diffusion steps to run
+ /// Default Value: 50
+ /// Example: 75 + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// #!/bin/sh
+ /// set -e
+ /// if [ -z "$STABILITY_API_KEY" ]; then
+ /// echo "STABILITY_API_KEY environment variable is not set"
+ /// exit 1
+ /// fi
+ /// OUTPUT_FILE=./out/v1_img2img_masking.png
+ /// BASE_URL=${API_HOST:-https://api.stability.ai}
+ /// URL="$BASE_URL/v1/generation/stable-inpainting-512-v2-0/image-to-image/masking"
+ /// curl -f -sS -X POST "$URL" \
+ /// -H 'Content-Type: multipart/form-data' \
+ /// -H 'Accept: image/png' \
+ /// -H "Authorization: Bearer $STABILITY_API_KEY" \
+ /// -F 'init_image=@"../init_image.png"' \
+ /// -F 'mask_image=@"../mask_image_white.png"' \
+ /// -F 'mask_source=MASK_IMAGE_WHITE' \
+ /// -F 'text_prompts[0][text]=A large spiral galaxy with a bright central bulge and a ring of stars around it' \
+ /// -F 'cfg_scale=7' \
+ /// -F 'clip_guidance_preset=FAST_BLUE' \
+ /// -F 'samples=1' \
+ /// -F 'steps=30' \
+ /// -o "$OUTPUT_FILE" + ///
+ public async global::System.Threading.Tasks.Task MaskingAsBytesAsStreamAsync( + string engineId, + global::System.IO.Stream initImage, + string initImagename, + global::System.Collections.Generic.IList textPrompts, + global::StabilityAI.MaskingAccept? accept = default, + string? organization = default, + global::System.IO.Stream? maskImage = default, + string? maskImagename = default, + double? cfgScale = default, + global::StabilityAI.ClipGuidancePreset? clipGuidancePreset = default, + global::StabilityAI.Sampler? sampler = default, + int? samples = default, + long? seed = default, + int? steps = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + + initImage = initImage ?? throw new global::System.ArgumentNullException(nameof(initImage)); + var request = new global::StabilityAI.MaskingRequestBody + { + InitImage = global::System.Array.Empty(), + InitImagename = initImagename, + MaskImage = global::System.Array.Empty(), + MaskImagename = maskImagename, + TextPrompts = textPrompts, + CfgScale = cfgScale, + ClipGuidancePreset = clipGuidancePreset, + Sampler = sampler, + Samples = samples, + Seed = seed, + Steps = steps, + }; + PrepareArguments( + client: HttpClient); + PrepareMaskingAsBytesArguments( + httpClient: HttpClient, + engineId: ref engineId, + accept: ref accept, + organization: ref organization, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_MaskingAsBytesSecurityRequirements, + operationName: "MaskingAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: $"/v1/generation/{engineId}/image-to-image/masking", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/png"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("Accept", accept?.ToValueString() ?? string.Empty); + } + if (organization != default) + { + __httpRequest.Headers.TryAddWithoutValidation("Organization", organization.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + var __contentInitImage = new global::System.Net.Http.StreamContent(initImage); + __contentInitImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.InitImagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.InitImagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentInitImage, + name: "\"init_image\"", + fileName: request.InitImagename != null ? $"\"{request.InitImagename}\"" : string.Empty); + if (__contentInitImage.Headers.ContentDisposition != null) + { + __contentInitImage.Headers.ContentDisposition.FileNameStar = null; + } + + if (maskImage != default) + { + + var __contentMaskImage = new global::System.Net.Http.StreamContent(maskImage); + __contentMaskImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.MaskImagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.MaskImagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentMaskImage, + name: "\"mask_image\"", + fileName: request.MaskImagename != null ? $"\"{request.MaskImagename}\"" : string.Empty); + if (__contentMaskImage.Headers.ContentDisposition != null) + { + __contentMaskImage.Headers.ContentDisposition.FileNameStar = null; + } + + } + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent($"[{string.Join(",", global::System.Linq.Enumerable.Select(request.TextPrompts, x => x.ToJson(JsonSerializerContext)))}]"), + name: "\"text_prompts\""); + + if (request.CfgScale != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.CfgScale, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"cfg_scale\""); + + } + if (request.ClipGuidancePreset != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.ClipGuidancePreset).HasValue ? (request.ClipGuidancePreset).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"clip_guidance_preset\""); + + } + if (request.Sampler != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.Sampler).HasValue ? (request.Sampler).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"sampler\""); + + } + if (request.Samples != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Samples, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"samples\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.Steps != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Steps, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"steps\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareMaskingAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + engineId: engineId!, + accept: accept, + organization: organization, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "MaskingAsBytes", + methodName: "MaskingAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image/masking\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseHeadersRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "MaskingAsBytes", + methodName: "MaskingAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image/masking\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "MaskingAsBytes", + methodName: "MaskingAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image/masking\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + try + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessMaskingAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "MaskingAsBytes", + methodName: "MaskingAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image/masking\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "MaskingAsBytes", + methodName: "MaskingAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image/masking\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // bad_request: general error for invalid parameters

More specific errors:

- invalid_samples: Sample count may only be greater than 1 when the accept header is set to `application/json` - invalid_height_or_width: Height and width must be specified in increments of 64 - invalid_file_size: The file size of one or more of the provided files is invalid - invalid_mime_type: The mime type of one or more of the provided files is invalid - invalid_image_dimensions: The dimensions of the provided `init_image` and `mask_image` do not match - invalid_mask_image: The parameter `mask_source` was set to `MASK_IMAGE_WHITE` or `MASK_IMAGE_BLACK` but no `mask_image` was provided - invalid_prompts: One or more of the prompts contains filtered words - invalid_pixel_count: Incorrect number of pixels specified. Requirements: - For 768 engines : 589,824 ≤ `height * width` ≤ 1,048,576 - All other engines: 262,144 ≤ `height * width` ≤ 1,048,576 + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.Error? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.Error.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.Error.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // unauthorized: API key missing or invalid + if ((int)__response.StatusCode == 401) + { + string? __content_401 = null; + global::System.Exception? __exception_401 = null; + global::StabilityAI.Error? __value_401 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_401 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_401 = global::StabilityAI.Error.FromJson(__content_401, JsonSerializerContext); + } + else + { + __content_401 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_401 = global::StabilityAI.Error.FromJson(__content_401, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_401 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_401 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_401, + responseBody: __content_401, + responseObject: __value_401, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // permission_denied: You lack the necessary permissions to perform this action + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.Error? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.Error.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.Error.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // not_found: The requested resource was not found (e.g. specifing a model that does not exist) + if ((int)__response.StatusCode == 404) + { + string? __content_404 = null; + global::System.Exception? __exception_404 = null; + global::StabilityAI.Error? __value_404 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_404 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_404 = global::StabilityAI.Error.FromJson(__content_404, JsonSerializerContext); + } + else + { + __content_404 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_404 = global::StabilityAI.Error.FromJson(__content_404, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_404 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_404 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_404, + responseBody: __content_404, + responseObject: __value_404, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // server_error: Some unexpected server error occurred + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.Error? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.Error.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.Error.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + try + { + __response.EnsureSuccessStatusCode(); + + var __content = await __response.Content.ReadAsStreamAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.ResponseStream(__response, __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + } + catch + { + __response.Dispose(); + throw; + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// image-to-image/masking
+ /// Selectively modify portions of an image using a mask + ///
+ /// + /// + /// Default Value: application/json + /// + /// + /// + /// Image used to initialize the diffusion process, in lieu of random noise.
+ /// Example: <image binary> + /// + /// + /// Image used to initialize the diffusion process, in lieu of random noise.
+ /// Example: <image binary> + /// + /// + /// Optional grayscale mask that allows for influence over which pixels are eligible for diffusion and at what strength. Must be the same dimensions as the `init_image`. Use the `mask_source` option to specify whether the white or black pixels should be inpainted.
+ /// Example: <image binary> + /// + /// + /// Optional grayscale mask that allows for influence over which pixels are eligible for diffusion and at what strength. Must be the same dimensions as the `init_image`. Use the `mask_source` option to specify whether the white or black pixels should be inpainted.
+ /// Example: <image binary> + /// + /// + /// An array of text prompts to use for generation.
+ /// Due to how arrays are represented in `multipart/form-data` requests, prompts must adhear to the format `text_prompts[index][text|weight]`,
+ /// where `index` is some integer used to tie the text and weight together. While `index` does not have to be sequential, duplicate entries
+ /// will override previous entries, so it is recommended to use sequential indices.
+ /// Given a text prompt with the text `A lighthouse on a cliff` and a weight of `0.5`, it would be represented as:
+ /// ```
+ /// text_prompts[0][text]: "A lighthouse on a cliff"
+ /// text_prompts[0][weight]: 0.5
+ /// ```
+ /// To add another prompt to that request simply provide the values under a new `index`:
+ /// ```
+ /// text_prompts[0][text]: "A lighthouse on a cliff"
+ /// text_prompts[0][weight]: 0.5
+ /// text_prompts[1][text]: "land, ground, dirt, grass"
+ /// text_prompts[1][weight]: -0.9
+ /// ``` + /// + /// + /// How strictly the diffusion process adheres to the prompt text (higher values keep your image closer to your prompt)
+ /// Default Value: 7
+ /// Example: 7 + /// + /// + /// Default Value: NONE
+ /// Example: FAST_BLUE + /// + /// + /// Which sampler to use for the diffusion process. If this value is omitted we'll automatically select an appropriate sampler for you.
+ /// Example: K_DPM_2_ANCESTRAL + /// + /// + /// Number of images to generate
+ /// Default Value: 1
+ /// Example: 1 + /// + /// + /// Random noise seed (omit this option or use `0` for a random seed)
+ /// Default Value: 0
+ /// Example: 0 + /// + /// + /// Number of diffusion steps to run
+ /// Default Value: 50
+ /// Example: 75 + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// #!/bin/sh
+ /// set -e
+ /// if [ -z "$STABILITY_API_KEY" ]; then
+ /// echo "STABILITY_API_KEY environment variable is not set"
+ /// exit 1
+ /// fi
+ /// OUTPUT_FILE=./out/v1_img2img_masking.png
+ /// BASE_URL=${API_HOST:-https://api.stability.ai}
+ /// URL="$BASE_URL/v1/generation/stable-inpainting-512-v2-0/image-to-image/masking"
+ /// curl -f -sS -X POST "$URL" \
+ /// -H 'Content-Type: multipart/form-data' \
+ /// -H 'Accept: image/png' \
+ /// -H "Authorization: Bearer $STABILITY_API_KEY" \
+ /// -F 'init_image=@"../init_image.png"' \
+ /// -F 'mask_image=@"../mask_image_white.png"' \
+ /// -F 'mask_source=MASK_IMAGE_WHITE' \
+ /// -F 'text_prompts[0][text]=A large spiral galaxy with a bright central bulge and a ring of stars around it' \
+ /// -F 'cfg_scale=7' \
+ /// -F 'clip_guidance_preset=FAST_BLUE' \
+ /// -F 'samples=1' \
+ /// -F 'steps=30' \
+ /// -o "$OUTPUT_FILE" + ///
+ public async global::System.Threading.Tasks.Task> MaskingAsBytesAsResponseAsync( + string engineId, + global::System.IO.Stream initImage, + string initImagename, + global::System.Collections.Generic.IList textPrompts, + global::StabilityAI.MaskingAccept? accept = default, + string? organization = default, + global::System.IO.Stream? maskImage = default, + string? maskImagename = default, + double? cfgScale = default, + global::StabilityAI.ClipGuidancePreset? clipGuidancePreset = default, + global::StabilityAI.Sampler? sampler = default, + int? samples = default, + long? seed = default, + int? steps = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + + initImage = initImage ?? throw new global::System.ArgumentNullException(nameof(initImage)); + var request = new global::StabilityAI.MaskingRequestBody + { + InitImage = global::System.Array.Empty(), + InitImagename = initImagename, + MaskImage = global::System.Array.Empty(), + MaskImagename = maskImagename, + TextPrompts = textPrompts, + CfgScale = cfgScale, + ClipGuidancePreset = clipGuidancePreset, + Sampler = sampler, + Samples = samples, + Seed = seed, + Steps = steps, + }; + PrepareArguments( + client: HttpClient); + PrepareMaskingAsBytesArguments( + httpClient: HttpClient, + engineId: ref engineId, + accept: ref accept, + organization: ref organization, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_MaskingAsBytesSecurityRequirements, + operationName: "MaskingAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: $"/v1/generation/{engineId}/image-to-image/masking", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/png"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("Accept", accept?.ToValueString() ?? string.Empty); + } + if (organization != default) + { + __httpRequest.Headers.TryAddWithoutValidation("Organization", organization.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + var __contentInitImage = new global::System.Net.Http.StreamContent(initImage); + __contentInitImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.InitImagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.InitImagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentInitImage, + name: "\"init_image\"", + fileName: request.InitImagename != null ? $"\"{request.InitImagename}\"" : string.Empty); + if (__contentInitImage.Headers.ContentDisposition != null) + { + __contentInitImage.Headers.ContentDisposition.FileNameStar = null; + } + + if (maskImage != default) + { + + var __contentMaskImage = new global::System.Net.Http.StreamContent(maskImage); + __contentMaskImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.MaskImagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.MaskImagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentMaskImage, + name: "\"mask_image\"", + fileName: request.MaskImagename != null ? $"\"{request.MaskImagename}\"" : string.Empty); + if (__contentMaskImage.Headers.ContentDisposition != null) + { + __contentMaskImage.Headers.ContentDisposition.FileNameStar = null; + } + + } + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent($"[{string.Join(",", global::System.Linq.Enumerable.Select(request.TextPrompts, x => x.ToJson(JsonSerializerContext)))}]"), + name: "\"text_prompts\""); + + if (request.CfgScale != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.CfgScale, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"cfg_scale\""); + + } + if (request.ClipGuidancePreset != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.ClipGuidancePreset).HasValue ? (request.ClipGuidancePreset).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"clip_guidance_preset\""); + + } + if (request.Sampler != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent((request.Sampler).HasValue ? (request.Sampler).GetValueOrDefault().ToValueString() : string.Empty), + name: "\"sampler\""); + + } + if (request.Samples != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Samples, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"samples\""); + + } + if (request.Seed != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"seed\""); + + } + if (request.Steps != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Steps, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"steps\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareMaskingAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + engineId: engineId!, + accept: accept, + organization: organization, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "MaskingAsBytes", + methodName: "MaskingAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image/masking\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "MaskingAsBytes", + methodName: "MaskingAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image/masking\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "MaskingAsBytes", + methodName: "MaskingAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image/masking\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessMaskingAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "MaskingAsBytes", + methodName: "MaskingAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image/masking\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "MaskingAsBytes", + methodName: "MaskingAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image/masking\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // bad_request: general error for invalid parameters

More specific errors:

- invalid_samples: Sample count may only be greater than 1 when the accept header is set to `application/json` - invalid_height_or_width: Height and width must be specified in increments of 64 - invalid_file_size: The file size of one or more of the provided files is invalid - invalid_mime_type: The mime type of one or more of the provided files is invalid - invalid_image_dimensions: The dimensions of the provided `init_image` and `mask_image` do not match - invalid_mask_image: The parameter `mask_source` was set to `MASK_IMAGE_WHITE` or `MASK_IMAGE_BLACK` but no `mask_image` was provided - invalid_prompts: One or more of the prompts contains filtered words - invalid_pixel_count: Incorrect number of pixels specified. Requirements: - For 768 engines : 589,824 ≤ `height * width` ≤ 1,048,576 - All other engines: 262,144 ≤ `height * width` ≤ 1,048,576 + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.Error? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.Error.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.Error.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // unauthorized: API key missing or invalid + if ((int)__response.StatusCode == 401) + { + string? __content_401 = null; + global::System.Exception? __exception_401 = null; + global::StabilityAI.Error? __value_401 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_401 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_401 = global::StabilityAI.Error.FromJson(__content_401, JsonSerializerContext); + } + else + { + __content_401 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_401 = global::StabilityAI.Error.FromJson(__content_401, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_401 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_401 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_401, + responseBody: __content_401, + responseObject: __value_401, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // permission_denied: You lack the necessary permissions to perform this action + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.Error? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.Error.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.Error.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // not_found: The requested resource was not found (e.g. specifing a model that does not exist) + if ((int)__response.StatusCode == 404) + { + string? __content_404 = null; + global::System.Exception? __exception_404 = null; + global::StabilityAI.Error? __value_404 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_404 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_404 = global::StabilityAI.Error.FromJson(__content_404, JsonSerializerContext); + } + else + { + __content_404 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_404 = global::StabilityAI.Error.FromJson(__content_404, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_404 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_404 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_404, + responseBody: __content_404, + responseObject: __value_404, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // server_error: Some unexpected server error occurred + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.Error? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.Error.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.Error.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessMaskingAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + } +} \ No newline at end of file diff --git a/src/libs/StabilityAI/Generated/StabilityAI.V1GenerationClient.TextToImage.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.V1GenerationClient.TextToImage.g.cs index c5e7ae7..bb6819a 100644 --- a/src/libs/StabilityAI/Generated/StabilityAI.V1GenerationClient.TextToImage.g.cs +++ b/src/libs/StabilityAI/Generated/StabilityAI.V1GenerationClient.TextToImage.g.cs @@ -209,6 +209,10 @@ partial void ProcessTextToImageResponseContent( __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || diff --git a/src/libs/StabilityAI/Generated/StabilityAI.V1GenerationClient.TextToImageAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.V1GenerationClient.TextToImageAsBytes.g.cs new file mode 100644 index 0000000..ddf3443 --- /dev/null +++ b/src/libs/StabilityAI/Generated/StabilityAI.V1GenerationClient.TextToImageAsBytes.g.cs @@ -0,0 +1,1312 @@ + +#nullable enable + +namespace StabilityAI +{ + public partial class V1GenerationClient + { + + + private static readonly global::StabilityAI.EndPointSecurityRequirement s_TextToImageAsBytesSecurityRequirement0 = + new global::StabilityAI.EndPointSecurityRequirement + { + Authorizations = new global::StabilityAI.EndPointAuthorizationRequirement[] + { new global::StabilityAI.EndPointAuthorizationRequirement + { + Type = "Http", + SchemeId = "HttpBearer", + Location = "Header", + Name = "Bearer", + FriendlyName = "Bearer", + }, + }, + }; + private static readonly global::StabilityAI.EndPointSecurityRequirement[] s_TextToImageAsBytesSecurityRequirements = + new global::StabilityAI.EndPointSecurityRequirement[] + { s_TextToImageAsBytesSecurityRequirement0, + }; + partial void PrepareTextToImageAsBytesArguments( + global::System.Net.Http.HttpClient httpClient, + ref string engineId, + ref global::StabilityAI.TextToImageAccept? accept, + ref string? organization, + global::StabilityAI.TextToImageRequestBody request); + partial void PrepareTextToImageAsBytesRequest( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpRequestMessage httpRequestMessage, + string engineId, + global::StabilityAI.TextToImageAccept? accept, + string? organization, + global::StabilityAI.TextToImageRequestBody request); + partial void ProcessTextToImageAsBytesResponse( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpResponseMessage httpResponseMessage); + + partial void ProcessTextToImageAsBytesResponseContent( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpResponseMessage httpResponseMessage, + ref byte[] content); + + /// + /// text-to-image
+ /// Generate a new image from a text prompt + ///
+ /// + /// Example: stable-diffusion-v1-5 + /// + /// + /// Default Value: application/json + /// + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// if [ -z "$STABILITY_API_KEY" ]; then
+ /// echo "STABILITY_API_KEY environment variable is not set"
+ /// exit 1
+ /// fi
+ /// OUTPUT_FILE=./out/v1_txt2img.png
+ /// BASE_URL=${API_HOST:-https://api.stability.ai}
+ /// URL="$BASE_URL/v1/generation/stable-diffusion-v1-5/text-to-image"
+ /// curl -f -sS -X POST "$URL" \
+ /// -H 'Content-Type: application/json' \
+ /// -H 'Accept: image/png' \
+ /// -H "Authorization: Bearer $STABILITY_API_KEY" \
+ /// --data-raw '{
+ /// "text_prompts": [
+ /// {
+ /// "text": "A lighthouse on a cliff"
+ /// }
+ /// ],
+ /// "cfg_scale": 7,
+ /// "clip_guidance_preset": "FAST_BLUE",
+ /// "height": 512,
+ /// "width": 512,
+ /// "samples": 1,
+ /// "steps": 30
+ /// }' \
+ /// -o "$OUTPUT_FILE" + ///
+ public async global::System.Threading.Tasks.Task TextToImageAsBytesAsync( + string engineId, + + global::StabilityAI.TextToImageRequestBody request, + global::StabilityAI.TextToImageAccept? accept = default, + string? organization = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + var __response = await TextToImageAsBytesAsResponseAsync( + engineId: engineId, + + request: request, + accept: accept, + organization: organization, + requestOptions: requestOptions, + cancellationToken: cancellationToken + ).ConfigureAwait(false); + + return __response.Body; + } + /// + /// text-to-image
+ /// Generate a new image from a text prompt + ///
+ /// + /// Example: stable-diffusion-v1-5 + /// + /// + /// Default Value: application/json + /// + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// if [ -z "$STABILITY_API_KEY" ]; then
+ /// echo "STABILITY_API_KEY environment variable is not set"
+ /// exit 1
+ /// fi
+ /// OUTPUT_FILE=./out/v1_txt2img.png
+ /// BASE_URL=${API_HOST:-https://api.stability.ai}
+ /// URL="$BASE_URL/v1/generation/stable-diffusion-v1-5/text-to-image"
+ /// curl -f -sS -X POST "$URL" \
+ /// -H 'Content-Type: application/json' \
+ /// -H 'Accept: image/png' \
+ /// -H "Authorization: Bearer $STABILITY_API_KEY" \
+ /// --data-raw '{
+ /// "text_prompts": [
+ /// {
+ /// "text": "A lighthouse on a cliff"
+ /// }
+ /// ],
+ /// "cfg_scale": 7,
+ /// "clip_guidance_preset": "FAST_BLUE",
+ /// "height": 512,
+ /// "width": 512,
+ /// "samples": 1,
+ /// "steps": 30
+ /// }' \
+ /// -o "$OUTPUT_FILE" + ///
+ public async global::System.Threading.Tasks.Task TextToImageAsBytesAsStreamAsync( + string engineId, + + global::StabilityAI.TextToImageRequestBody request, + global::StabilityAI.TextToImageAccept? accept = default, + string? organization = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + PrepareArguments( + client: HttpClient); + PrepareTextToImageAsBytesArguments( + httpClient: HttpClient, + engineId: ref engineId, + accept: ref accept, + organization: ref organization, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_TextToImageAsBytesSecurityRequirements, + operationName: "TextToImageAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: true); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: $"/v1/generation/{engineId}/text-to-image", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/png"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("Accept", accept?.ToValueString() ?? string.Empty); + } + if (organization != default) + { + __httpRequest.Headers.TryAddWithoutValidation("Organization", organization.ToString()); + } + + var __httpRequestContentBody = request.ToJson(JsonSerializerContext); + var __httpRequestContent = new global::System.Net.Http.StringContent( + content: __httpRequestContentBody, + encoding: global::System.Text.Encoding.UTF8, + mediaType: "application/json"); + __httpRequest.Content = __httpRequestContent; + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareTextToImageAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + engineId: engineId!, + accept: accept, + organization: organization, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "TextToImageAsBytes", + methodName: "TextToImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/text-to-image\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseHeadersRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "TextToImageAsBytes", + methodName: "TextToImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/text-to-image\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "TextToImageAsBytes", + methodName: "TextToImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/text-to-image\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + try + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessTextToImageAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "TextToImageAsBytes", + methodName: "TextToImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/text-to-image\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "TextToImageAsBytes", + methodName: "TextToImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/text-to-image\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // bad_request: general error for invalid parameters

More specific errors:

- invalid_samples: Sample count may only be greater than 1 when the accept header is set to `application/json` - invalid_height_or_width: Height and width must be specified in increments of 64 - invalid_file_size: The file size of one or more of the provided files is invalid - invalid_mime_type: The mime type of one or more of the provided files is invalid - invalid_image_dimensions: The dimensions of the provided `init_image` and `mask_image` do not match - invalid_mask_image: The parameter `mask_source` was set to `MASK_IMAGE_WHITE` or `MASK_IMAGE_BLACK` but no `mask_image` was provided - invalid_prompts: One or more of the prompts contains filtered words - invalid_pixel_count: Incorrect number of pixels specified. Requirements: - For 768 engines : 589,824 ≤ `height * width` ≤ 1,048,576 - All other engines: 262,144 ≤ `height * width` ≤ 1,048,576 + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.Error? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.Error.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.Error.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // unauthorized: API key missing or invalid + if ((int)__response.StatusCode == 401) + { + string? __content_401 = null; + global::System.Exception? __exception_401 = null; + global::StabilityAI.Error? __value_401 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_401 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_401 = global::StabilityAI.Error.FromJson(__content_401, JsonSerializerContext); + } + else + { + __content_401 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_401 = global::StabilityAI.Error.FromJson(__content_401, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_401 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_401 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_401, + responseBody: __content_401, + responseObject: __value_401, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // permission_denied: You lack the necessary permissions to perform this action + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.Error? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.Error.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.Error.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // not_found: The requested resource was not found (e.g. specifing a model that does not exist) + if ((int)__response.StatusCode == 404) + { + string? __content_404 = null; + global::System.Exception? __exception_404 = null; + global::StabilityAI.Error? __value_404 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_404 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_404 = global::StabilityAI.Error.FromJson(__content_404, JsonSerializerContext); + } + else + { + __content_404 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_404 = global::StabilityAI.Error.FromJson(__content_404, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_404 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_404 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_404, + responseBody: __content_404, + responseObject: __value_404, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // server_error: Some unexpected server error occurred + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.Error? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.Error.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.Error.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + try + { + __response.EnsureSuccessStatusCode(); + + var __content = await __response.Content.ReadAsStreamAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.ResponseStream(__response, __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + } + catch + { + __response.Dispose(); + throw; + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// text-to-image
+ /// Generate a new image from a text prompt + ///
+ /// + /// Example: stable-diffusion-v1-5 + /// + /// + /// Default Value: application/json + /// + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// if [ -z "$STABILITY_API_KEY" ]; then
+ /// echo "STABILITY_API_KEY environment variable is not set"
+ /// exit 1
+ /// fi
+ /// OUTPUT_FILE=./out/v1_txt2img.png
+ /// BASE_URL=${API_HOST:-https://api.stability.ai}
+ /// URL="$BASE_URL/v1/generation/stable-diffusion-v1-5/text-to-image"
+ /// curl -f -sS -X POST "$URL" \
+ /// -H 'Content-Type: application/json' \
+ /// -H 'Accept: image/png' \
+ /// -H "Authorization: Bearer $STABILITY_API_KEY" \
+ /// --data-raw '{
+ /// "text_prompts": [
+ /// {
+ /// "text": "A lighthouse on a cliff"
+ /// }
+ /// ],
+ /// "cfg_scale": 7,
+ /// "clip_guidance_preset": "FAST_BLUE",
+ /// "height": 512,
+ /// "width": 512,
+ /// "samples": 1,
+ /// "steps": 30
+ /// }' \
+ /// -o "$OUTPUT_FILE" + ///
+ public async global::System.Threading.Tasks.Task> TextToImageAsBytesAsResponseAsync( + string engineId, + + global::StabilityAI.TextToImageRequestBody request, + global::StabilityAI.TextToImageAccept? accept = default, + string? organization = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + PrepareArguments( + client: HttpClient); + PrepareTextToImageAsBytesArguments( + httpClient: HttpClient, + engineId: ref engineId, + accept: ref accept, + organization: ref organization, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_TextToImageAsBytesSecurityRequirements, + operationName: "TextToImageAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: true); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: $"/v1/generation/{engineId}/text-to-image", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/png"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("Accept", accept?.ToValueString() ?? string.Empty); + } + if (organization != default) + { + __httpRequest.Headers.TryAddWithoutValidation("Organization", organization.ToString()); + } + + var __httpRequestContentBody = request.ToJson(JsonSerializerContext); + var __httpRequestContent = new global::System.Net.Http.StringContent( + content: __httpRequestContentBody, + encoding: global::System.Text.Encoding.UTF8, + mediaType: "application/json"); + __httpRequest.Content = __httpRequestContent; + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareTextToImageAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + engineId: engineId!, + accept: accept, + organization: organization, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "TextToImageAsBytes", + methodName: "TextToImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/text-to-image\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "TextToImageAsBytes", + methodName: "TextToImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/text-to-image\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "TextToImageAsBytes", + methodName: "TextToImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/text-to-image\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessTextToImageAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "TextToImageAsBytes", + methodName: "TextToImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/text-to-image\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "TextToImageAsBytes", + methodName: "TextToImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/text-to-image\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // bad_request: general error for invalid parameters

More specific errors:

- invalid_samples: Sample count may only be greater than 1 when the accept header is set to `application/json` - invalid_height_or_width: Height and width must be specified in increments of 64 - invalid_file_size: The file size of one or more of the provided files is invalid - invalid_mime_type: The mime type of one or more of the provided files is invalid - invalid_image_dimensions: The dimensions of the provided `init_image` and `mask_image` do not match - invalid_mask_image: The parameter `mask_source` was set to `MASK_IMAGE_WHITE` or `MASK_IMAGE_BLACK` but no `mask_image` was provided - invalid_prompts: One or more of the prompts contains filtered words - invalid_pixel_count: Incorrect number of pixels specified. Requirements: - For 768 engines : 589,824 ≤ `height * width` ≤ 1,048,576 - All other engines: 262,144 ≤ `height * width` ≤ 1,048,576 + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.Error? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.Error.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.Error.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // unauthorized: API key missing or invalid + if ((int)__response.StatusCode == 401) + { + string? __content_401 = null; + global::System.Exception? __exception_401 = null; + global::StabilityAI.Error? __value_401 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_401 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_401 = global::StabilityAI.Error.FromJson(__content_401, JsonSerializerContext); + } + else + { + __content_401 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_401 = global::StabilityAI.Error.FromJson(__content_401, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_401 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_401 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_401, + responseBody: __content_401, + responseObject: __value_401, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // permission_denied: You lack the necessary permissions to perform this action + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.Error? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.Error.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.Error.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // not_found: The requested resource was not found (e.g. specifing a model that does not exist) + if ((int)__response.StatusCode == 404) + { + string? __content_404 = null; + global::System.Exception? __exception_404 = null; + global::StabilityAI.Error? __value_404 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_404 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_404 = global::StabilityAI.Error.FromJson(__content_404, JsonSerializerContext); + } + else + { + __content_404 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_404 = global::StabilityAI.Error.FromJson(__content_404, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_404 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_404 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_404, + responseBody: __content_404, + responseObject: __value_404, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // server_error: Some unexpected server error occurred + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.Error? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.Error.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.Error.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessTextToImageAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// text-to-image
+ /// Generate a new image from a text prompt + ///
+ /// + /// Example: stable-diffusion-v1-5 + /// + /// + /// Default Value: application/json + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + public async global::System.Threading.Tasks.Task TextToImageAsBytesAsync( + string engineId, + global::StabilityAI.TextToImageAccept? accept = default, + string? organization = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + var __request = new global::StabilityAI.TextToImageRequestBody + { + }; + + return await TextToImageAsBytesAsync( + engineId: engineId, + accept: accept, + organization: organization, + request: __request, + requestOptions: requestOptions, + cancellationToken: cancellationToken).ConfigureAwait(false); + } + } +} \ No newline at end of file diff --git a/src/libs/StabilityAI/Generated/StabilityAI.V1GenerationClient.UpscaleImage.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.V1GenerationClient.UpscaleImage.g.cs index ff88efb..cd44bc4 100644 --- a/src/libs/StabilityAI/Generated/StabilityAI.V1GenerationClient.UpscaleImage.g.cs +++ b/src/libs/StabilityAI/Generated/StabilityAI.V1GenerationClient.UpscaleImage.g.cs @@ -189,6 +189,10 @@ partial void ProcessUpscaleImageResponseContent( __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || @@ -217,26 +221,6 @@ partial void ProcessUpscaleImageResponseContent( var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(engineId ?? string.Empty), - name: "\"engine_id\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"Accept\""); - - } - if (organization != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(organization ?? string.Empty), - name: "\"Organization\""); - - } var __contentImage = new global::System.Net.Http.ByteArrayContent(request.Image ?? global::System.Array.Empty()); __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( request.Imagename is null @@ -932,6 +916,10 @@ request.Imagename is null __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || @@ -960,26 +948,6 @@ request.Imagename is null var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(engineId ?? string.Empty), - name: "\"engine_id\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"Accept\""); - - } - if (organization != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(organization ?? string.Empty), - name: "\"Organization\""); - - } var __contentImage = new global::System.Net.Http.StreamContent(image); __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( request.Imagename is null @@ -1613,6 +1581,10 @@ request.Imagename is null __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || @@ -1641,26 +1613,6 @@ request.Imagename is null var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(engineId ?? string.Empty), - name: "\"engine_id\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"Accept\""); - - } - if (organization != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(organization ?? string.Empty), - name: "\"Organization\""); - - } var __contentImage = new global::System.Net.Http.StreamContent(image); __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( request.Imagename is null diff --git a/src/libs/StabilityAI/Generated/StabilityAI.V1GenerationClient.UpscaleImageAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.V1GenerationClient.UpscaleImageAsBytes.g.cs new file mode 100644 index 0000000..1776533 --- /dev/null +++ b/src/libs/StabilityAI/Generated/StabilityAI.V1GenerationClient.UpscaleImageAsBytes.g.cs @@ -0,0 +1,3360 @@ + +#nullable enable + +namespace StabilityAI +{ + public partial class V1GenerationClient + { + + + private static readonly global::StabilityAI.EndPointSecurityRequirement s_UpscaleImageAsBytesSecurityRequirement0 = + new global::StabilityAI.EndPointSecurityRequirement + { + Authorizations = new global::StabilityAI.EndPointAuthorizationRequirement[] + { new global::StabilityAI.EndPointAuthorizationRequirement + { + Type = "Http", + SchemeId = "HttpBearer", + Location = "Header", + Name = "Bearer", + FriendlyName = "Bearer", + }, + }, + }; + private static readonly global::StabilityAI.EndPointSecurityRequirement[] s_UpscaleImageAsBytesSecurityRequirements = + new global::StabilityAI.EndPointSecurityRequirement[] + { s_UpscaleImageAsBytesSecurityRequirement0, + }; + partial void PrepareUpscaleImageAsBytesArguments( + global::System.Net.Http.HttpClient httpClient, + ref string engineId, + ref global::StabilityAI.UpscaleImageAccept? accept, + ref string? organization, + global::StabilityAI.UpscaleImageRequestBody request); + partial void PrepareUpscaleImageAsBytesRequest( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpRequestMessage httpRequestMessage, + string engineId, + global::StabilityAI.UpscaleImageAccept? accept, + string? organization, + global::StabilityAI.UpscaleImageRequestBody request); + partial void ProcessUpscaleImageAsBytesResponse( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpResponseMessage httpResponseMessage); + + partial void ProcessUpscaleImageAsBytesResponseContent( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpResponseMessage httpResponseMessage, + ref byte[] content); + + /// + /// image-to-image/upscale
+ /// Create a higher resolution version of an input image.
+ /// This operation outputs an image with a maximum pixel count of **4,194,304**. This is equivalent to dimensions such as `2048x2048` and `4096x1024`.
+ /// By default, the input image will be upscaled by a factor of 2. For additional control over the output dimensions, a `width` or `height` parameter may be specified. + ///
+ /// + /// + /// Default Value: application/json + /// + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// if [ -z "$STABILITY_API_KEY" ]; then
+ /// echo "STABILITY_API_KEY environment variable is not set"
+ /// exit 1
+ /// fi
+ /// OUTPUT_FILE=./out/v1_upscaled_image.png
+ /// BASE_URL=${API_HOST:-https://api.stability.ai}
+ /// URL="$BASE_URL/v1/generation/esrgan-v1-x2plus/image-to-image/upscale"
+ /// curl -f -sS -X POST "$URL" \
+ /// -H 'Content-Type: multipart/form-data' \
+ /// -H 'Accept: image/png' \
+ /// -H "Authorization: Bearer $STABILITY_API_KEY" \
+ /// -F 'image=@"../init_image.png"' \
+ /// -F 'width=1024' \
+ /// -o "$OUTPUT_FILE" + ///
+ public async global::System.Threading.Tasks.Task UpscaleImageAsBytesAsync( + string engineId, + + global::StabilityAI.UpscaleImageRequestBody request, + global::StabilityAI.UpscaleImageAccept? accept = default, + string? organization = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + var __response = await UpscaleImageAsBytesAsResponseAsync( + engineId: engineId, + + request: request, + accept: accept, + organization: organization, + requestOptions: requestOptions, + cancellationToken: cancellationToken + ).ConfigureAwait(false); + + return __response.Body; + } + /// + /// image-to-image/upscale
+ /// Create a higher resolution version of an input image.
+ /// This operation outputs an image with a maximum pixel count of **4,194,304**. This is equivalent to dimensions such as `2048x2048` and `4096x1024`.
+ /// By default, the input image will be upscaled by a factor of 2. For additional control over the output dimensions, a `width` or `height` parameter may be specified. + ///
+ /// + /// + /// Default Value: application/json + /// + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// if [ -z "$STABILITY_API_KEY" ]; then
+ /// echo "STABILITY_API_KEY environment variable is not set"
+ /// exit 1
+ /// fi
+ /// OUTPUT_FILE=./out/v1_upscaled_image.png
+ /// BASE_URL=${API_HOST:-https://api.stability.ai}
+ /// URL="$BASE_URL/v1/generation/esrgan-v1-x2plus/image-to-image/upscale"
+ /// curl -f -sS -X POST "$URL" \
+ /// -H 'Content-Type: multipart/form-data' \
+ /// -H 'Accept: image/png' \
+ /// -H "Authorization: Bearer $STABILITY_API_KEY" \
+ /// -F 'image=@"../init_image.png"' \
+ /// -F 'width=1024' \
+ /// -o "$OUTPUT_FILE" + ///
+ public async global::System.Threading.Tasks.Task UpscaleImageAsBytesAsStreamAsync( + string engineId, + + global::StabilityAI.UpscaleImageRequestBody request, + global::StabilityAI.UpscaleImageAccept? accept = default, + string? organization = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + request = request ?? throw new global::System.ArgumentNullException(nameof(request)); + + PrepareArguments( + client: HttpClient); + PrepareUpscaleImageAsBytesArguments( + httpClient: HttpClient, + engineId: ref engineId, + accept: ref accept, + organization: ref organization, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_UpscaleImageAsBytesSecurityRequirements, + operationName: "UpscaleImageAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: $"/v1/generation/{engineId}/image-to-image/upscale", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/png"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("Accept", accept?.ToValueString() ?? string.Empty); + } + if (organization != default) + { + __httpRequest.Headers.TryAddWithoutValidation("Organization", organization.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + var __contentImage = new global::System.Net.Http.ByteArrayContent(request.Image ?? global::System.Array.Empty()); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.Width != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Width, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"width\""); + + } + if (request.Height != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Height, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"height\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareUpscaleImageAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + engineId: engineId!, + accept: accept, + organization: organization, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "UpscaleImageAsBytes", + methodName: "UpscaleImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image/upscale\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseHeadersRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "UpscaleImageAsBytes", + methodName: "UpscaleImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image/upscale\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "UpscaleImageAsBytes", + methodName: "UpscaleImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image/upscale\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + try + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessUpscaleImageAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "UpscaleImageAsBytes", + methodName: "UpscaleImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image/upscale\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "UpscaleImageAsBytes", + methodName: "UpscaleImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image/upscale\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // bad_request: general error for invalid parameters

More specific errors:

- invalid_file_size: The file size of one or more of the provided files is invalid - invalid_mime_type: The mime type of one or more of the provided files is invalid - invalid_pixel_count: The requested image would exceed the maximum pixel count of 4,194,304 + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.Error? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.Error.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.Error.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // unauthorized: API key missing or invalid + if ((int)__response.StatusCode == 401) + { + string? __content_401 = null; + global::System.Exception? __exception_401 = null; + global::StabilityAI.Error? __value_401 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_401 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_401 = global::StabilityAI.Error.FromJson(__content_401, JsonSerializerContext); + } + else + { + __content_401 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_401 = global::StabilityAI.Error.FromJson(__content_401, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_401 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_401 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_401, + responseBody: __content_401, + responseObject: __value_401, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // permission_denied: You lack the necessary permissions to perform this action + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.Error? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.Error.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.Error.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // not_found: The requested resource was not found (e.g. specifing a model that does not exist) + if ((int)__response.StatusCode == 404) + { + string? __content_404 = null; + global::System.Exception? __exception_404 = null; + global::StabilityAI.Error? __value_404 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_404 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_404 = global::StabilityAI.Error.FromJson(__content_404, JsonSerializerContext); + } + else + { + __content_404 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_404 = global::StabilityAI.Error.FromJson(__content_404, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_404 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_404 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_404, + responseBody: __content_404, + responseObject: __value_404, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // server_error: Some unexpected server error occurred + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.Error? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.Error.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.Error.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + try + { + __response.EnsureSuccessStatusCode(); + + var __content = await __response.Content.ReadAsStreamAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.ResponseStream(__response, __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + } + catch + { + __response.Dispose(); + throw; + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// image-to-image/upscale
+ /// Create a higher resolution version of an input image.
+ /// This operation outputs an image with a maximum pixel count of **4,194,304**. This is equivalent to dimensions such as `2048x2048` and `4096x1024`.
+ /// By default, the input image will be upscaled by a factor of 2. For additional control over the output dimensions, a `width` or `height` parameter may be specified. + ///
+ /// + /// + /// Default Value: application/json + /// + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// if [ -z "$STABILITY_API_KEY" ]; then
+ /// echo "STABILITY_API_KEY environment variable is not set"
+ /// exit 1
+ /// fi
+ /// OUTPUT_FILE=./out/v1_upscaled_image.png
+ /// BASE_URL=${API_HOST:-https://api.stability.ai}
+ /// URL="$BASE_URL/v1/generation/esrgan-v1-x2plus/image-to-image/upscale"
+ /// curl -f -sS -X POST "$URL" \
+ /// -H 'Content-Type: multipart/form-data' \
+ /// -H 'Accept: image/png' \
+ /// -H "Authorization: Bearer $STABILITY_API_KEY" \
+ /// -F 'image=@"../init_image.png"' \
+ /// -F 'width=1024' \
+ /// -o "$OUTPUT_FILE" + ///
+ public async global::System.Threading.Tasks.Task> UpscaleImageAsBytesAsResponseAsync( + string engineId, + + global::StabilityAI.UpscaleImageRequestBody request, + global::StabilityAI.UpscaleImageAccept? accept = default, + string? organization = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + request = request ?? throw new global::System.ArgumentNullException(nameof(request)); + + PrepareArguments( + client: HttpClient); + PrepareUpscaleImageAsBytesArguments( + httpClient: HttpClient, + engineId: ref engineId, + accept: ref accept, + organization: ref organization, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_UpscaleImageAsBytesSecurityRequirements, + operationName: "UpscaleImageAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: $"/v1/generation/{engineId}/image-to-image/upscale", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/png"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("Accept", accept?.ToValueString() ?? string.Empty); + } + if (organization != default) + { + __httpRequest.Headers.TryAddWithoutValidation("Organization", organization.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + var __contentImage = new global::System.Net.Http.ByteArrayContent(request.Image ?? global::System.Array.Empty()); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.Width != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Width, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"width\""); + + } + if (request.Height != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Height, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"height\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareUpscaleImageAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + engineId: engineId!, + accept: accept, + organization: organization, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "UpscaleImageAsBytes", + methodName: "UpscaleImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image/upscale\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "UpscaleImageAsBytes", + methodName: "UpscaleImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image/upscale\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "UpscaleImageAsBytes", + methodName: "UpscaleImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image/upscale\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessUpscaleImageAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "UpscaleImageAsBytes", + methodName: "UpscaleImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image/upscale\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "UpscaleImageAsBytes", + methodName: "UpscaleImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image/upscale\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // bad_request: general error for invalid parameters

More specific errors:

- invalid_file_size: The file size of one or more of the provided files is invalid - invalid_mime_type: The mime type of one or more of the provided files is invalid - invalid_pixel_count: The requested image would exceed the maximum pixel count of 4,194,304 + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.Error? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.Error.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.Error.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // unauthorized: API key missing or invalid + if ((int)__response.StatusCode == 401) + { + string? __content_401 = null; + global::System.Exception? __exception_401 = null; + global::StabilityAI.Error? __value_401 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_401 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_401 = global::StabilityAI.Error.FromJson(__content_401, JsonSerializerContext); + } + else + { + __content_401 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_401 = global::StabilityAI.Error.FromJson(__content_401, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_401 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_401 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_401, + responseBody: __content_401, + responseObject: __value_401, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // permission_denied: You lack the necessary permissions to perform this action + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.Error? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.Error.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.Error.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // not_found: The requested resource was not found (e.g. specifing a model that does not exist) + if ((int)__response.StatusCode == 404) + { + string? __content_404 = null; + global::System.Exception? __exception_404 = null; + global::StabilityAI.Error? __value_404 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_404 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_404 = global::StabilityAI.Error.FromJson(__content_404, JsonSerializerContext); + } + else + { + __content_404 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_404 = global::StabilityAI.Error.FromJson(__content_404, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_404 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_404 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_404, + responseBody: __content_404, + responseObject: __value_404, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // server_error: Some unexpected server error occurred + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.Error? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.Error.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.Error.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessUpscaleImageAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// image-to-image/upscale
+ /// Create a higher resolution version of an input image.
+ /// This operation outputs an image with a maximum pixel count of **4,194,304**. This is equivalent to dimensions such as `2048x2048` and `4096x1024`.
+ /// By default, the input image will be upscaled by a factor of 2. For additional control over the output dimensions, a `width` or `height` parameter may be specified. + ///
+ /// + /// + /// Default Value: application/json + /// + /// + /// + /// Example: <image binary> + /// + /// + /// Example: <image binary> + /// + /// + /// Desired width of the output image. Only one of `width` or `height` may be specified. + /// + /// + /// Desired height of the output image. Only one of `width` or `height` may be specified. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + public async global::System.Threading.Tasks.Task UpscaleImageAsBytesAsync( + string engineId, + byte[] image, + string imagename, + global::StabilityAI.UpscaleImageAccept? accept = default, + string? organization = default, + int? width = default, + int? height = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + var __request = new global::StabilityAI.UpscaleImageRequestBody + { + Image = image, + Imagename = imagename, + Width = width, + Height = height, + }; + + return await UpscaleImageAsBytesAsync( + engineId: engineId, + accept: accept, + organization: organization, + request: __request, + requestOptions: requestOptions, + cancellationToken: cancellationToken).ConfigureAwait(false); + } + + /// + /// image-to-image/upscale
+ /// Create a higher resolution version of an input image.
+ /// This operation outputs an image with a maximum pixel count of **4,194,304**. This is equivalent to dimensions such as `2048x2048` and `4096x1024`.
+ /// By default, the input image will be upscaled by a factor of 2. For additional control over the output dimensions, a `width` or `height` parameter may be specified. + ///
+ /// + /// + /// Default Value: application/json + /// + /// + /// + /// Example: <image binary> + /// + /// + /// Example: <image binary> + /// + /// + /// Desired width of the output image. Only one of `width` or `height` may be specified. + /// + /// + /// Desired height of the output image. Only one of `width` or `height` may be specified. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// if [ -z "$STABILITY_API_KEY" ]; then
+ /// echo "STABILITY_API_KEY environment variable is not set"
+ /// exit 1
+ /// fi
+ /// OUTPUT_FILE=./out/v1_upscaled_image.png
+ /// BASE_URL=${API_HOST:-https://api.stability.ai}
+ /// URL="$BASE_URL/v1/generation/esrgan-v1-x2plus/image-to-image/upscale"
+ /// curl -f -sS -X POST "$URL" \
+ /// -H 'Content-Type: multipart/form-data' \
+ /// -H 'Accept: image/png' \
+ /// -H "Authorization: Bearer $STABILITY_API_KEY" \
+ /// -F 'image=@"../init_image.png"' \
+ /// -F 'width=1024' \
+ /// -o "$OUTPUT_FILE" + ///
+ public async global::System.Threading.Tasks.Task UpscaleImageAsBytesAsync( + string engineId, + global::System.IO.Stream image, + string imagename, + global::StabilityAI.UpscaleImageAccept? accept = default, + string? organization = default, + int? width = default, + int? height = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + + image = image ?? throw new global::System.ArgumentNullException(nameof(image)); + var request = new global::StabilityAI.UpscaleImageRequestBody + { + Image = global::System.Array.Empty(), + Imagename = imagename, + Width = width, + Height = height, + }; + PrepareArguments( + client: HttpClient); + PrepareUpscaleImageAsBytesArguments( + httpClient: HttpClient, + engineId: ref engineId, + accept: ref accept, + organization: ref organization, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_UpscaleImageAsBytesSecurityRequirements, + operationName: "UpscaleImageAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: $"/v1/generation/{engineId}/image-to-image/upscale", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/png"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("Accept", accept?.ToValueString() ?? string.Empty); + } + if (organization != default) + { + __httpRequest.Headers.TryAddWithoutValidation("Organization", organization.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + var __contentImage = new global::System.Net.Http.StreamContent(image); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.Width != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Width, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"width\""); + + } + if (request.Height != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Height, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"height\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareUpscaleImageAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + engineId: engineId!, + accept: accept, + organization: organization, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "UpscaleImageAsBytes", + methodName: "UpscaleImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image/upscale\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "UpscaleImageAsBytes", + methodName: "UpscaleImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image/upscale\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "UpscaleImageAsBytes", + methodName: "UpscaleImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image/upscale\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessUpscaleImageAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "UpscaleImageAsBytes", + methodName: "UpscaleImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image/upscale\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "UpscaleImageAsBytes", + methodName: "UpscaleImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image/upscale\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // bad_request: general error for invalid parameters

More specific errors:

- invalid_file_size: The file size of one or more of the provided files is invalid - invalid_mime_type: The mime type of one or more of the provided files is invalid - invalid_pixel_count: The requested image would exceed the maximum pixel count of 4,194,304 + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.Error? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.Error.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.Error.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // unauthorized: API key missing or invalid + if ((int)__response.StatusCode == 401) + { + string? __content_401 = null; + global::System.Exception? __exception_401 = null; + global::StabilityAI.Error? __value_401 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_401 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_401 = global::StabilityAI.Error.FromJson(__content_401, JsonSerializerContext); + } + else + { + __content_401 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_401 = global::StabilityAI.Error.FromJson(__content_401, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_401 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_401 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_401, + responseBody: __content_401, + responseObject: __value_401, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // permission_denied: You lack the necessary permissions to perform this action + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.Error? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.Error.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.Error.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // not_found: The requested resource was not found (e.g. specifing a model that does not exist) + if ((int)__response.StatusCode == 404) + { + string? __content_404 = null; + global::System.Exception? __exception_404 = null; + global::StabilityAI.Error? __value_404 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_404 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_404 = global::StabilityAI.Error.FromJson(__content_404, JsonSerializerContext); + } + else + { + __content_404 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_404 = global::StabilityAI.Error.FromJson(__content_404, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_404 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_404 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_404, + responseBody: __content_404, + responseObject: __value_404, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // server_error: Some unexpected server error occurred + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.Error? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.Error.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.Error.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessUpscaleImageAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return __content; + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return __content; + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// image-to-image/upscale
+ /// Create a higher resolution version of an input image.
+ /// This operation outputs an image with a maximum pixel count of **4,194,304**. This is equivalent to dimensions such as `2048x2048` and `4096x1024`.
+ /// By default, the input image will be upscaled by a factor of 2. For additional control over the output dimensions, a `width` or `height` parameter may be specified. + ///
+ /// + /// + /// Default Value: application/json + /// + /// + /// + /// Example: <image binary> + /// + /// + /// Example: <image binary> + /// + /// + /// Desired width of the output image. Only one of `width` or `height` may be specified. + /// + /// + /// Desired height of the output image. Only one of `width` or `height` may be specified. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// if [ -z "$STABILITY_API_KEY" ]; then
+ /// echo "STABILITY_API_KEY environment variable is not set"
+ /// exit 1
+ /// fi
+ /// OUTPUT_FILE=./out/v1_upscaled_image.png
+ /// BASE_URL=${API_HOST:-https://api.stability.ai}
+ /// URL="$BASE_URL/v1/generation/esrgan-v1-x2plus/image-to-image/upscale"
+ /// curl -f -sS -X POST "$URL" \
+ /// -H 'Content-Type: multipart/form-data' \
+ /// -H 'Accept: image/png' \
+ /// -H "Authorization: Bearer $STABILITY_API_KEY" \
+ /// -F 'image=@"../init_image.png"' \
+ /// -F 'width=1024' \
+ /// -o "$OUTPUT_FILE" + ///
+ public async global::System.Threading.Tasks.Task UpscaleImageAsBytesAsStreamAsync( + string engineId, + global::System.IO.Stream image, + string imagename, + global::StabilityAI.UpscaleImageAccept? accept = default, + string? organization = default, + int? width = default, + int? height = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + + image = image ?? throw new global::System.ArgumentNullException(nameof(image)); + var request = new global::StabilityAI.UpscaleImageRequestBody + { + Image = global::System.Array.Empty(), + Imagename = imagename, + Width = width, + Height = height, + }; + PrepareArguments( + client: HttpClient); + PrepareUpscaleImageAsBytesArguments( + httpClient: HttpClient, + engineId: ref engineId, + accept: ref accept, + organization: ref organization, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_UpscaleImageAsBytesSecurityRequirements, + operationName: "UpscaleImageAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: $"/v1/generation/{engineId}/image-to-image/upscale", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/png"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("Accept", accept?.ToValueString() ?? string.Empty); + } + if (organization != default) + { + __httpRequest.Headers.TryAddWithoutValidation("Organization", organization.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + var __contentImage = new global::System.Net.Http.StreamContent(image); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.Width != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Width, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"width\""); + + } + if (request.Height != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Height, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"height\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareUpscaleImageAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + engineId: engineId!, + accept: accept, + organization: organization, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "UpscaleImageAsBytes", + methodName: "UpscaleImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image/upscale\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseHeadersRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "UpscaleImageAsBytes", + methodName: "UpscaleImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image/upscale\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "UpscaleImageAsBytes", + methodName: "UpscaleImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image/upscale\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + try + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessUpscaleImageAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "UpscaleImageAsBytes", + methodName: "UpscaleImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image/upscale\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "UpscaleImageAsBytes", + methodName: "UpscaleImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image/upscale\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // bad_request: general error for invalid parameters

More specific errors:

- invalid_file_size: The file size of one or more of the provided files is invalid - invalid_mime_type: The mime type of one or more of the provided files is invalid - invalid_pixel_count: The requested image would exceed the maximum pixel count of 4,194,304 + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.Error? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.Error.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.Error.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // unauthorized: API key missing or invalid + if ((int)__response.StatusCode == 401) + { + string? __content_401 = null; + global::System.Exception? __exception_401 = null; + global::StabilityAI.Error? __value_401 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_401 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_401 = global::StabilityAI.Error.FromJson(__content_401, JsonSerializerContext); + } + else + { + __content_401 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_401 = global::StabilityAI.Error.FromJson(__content_401, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_401 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_401 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_401, + responseBody: __content_401, + responseObject: __value_401, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // permission_denied: You lack the necessary permissions to perform this action + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.Error? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.Error.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.Error.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // not_found: The requested resource was not found (e.g. specifing a model that does not exist) + if ((int)__response.StatusCode == 404) + { + string? __content_404 = null; + global::System.Exception? __exception_404 = null; + global::StabilityAI.Error? __value_404 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_404 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_404 = global::StabilityAI.Error.FromJson(__content_404, JsonSerializerContext); + } + else + { + __content_404 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_404 = global::StabilityAI.Error.FromJson(__content_404, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_404 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_404 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_404, + responseBody: __content_404, + responseObject: __value_404, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // server_error: Some unexpected server error occurred + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.Error? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.Error.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.Error.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + try + { + __response.EnsureSuccessStatusCode(); + + var __content = await __response.Content.ReadAsStreamAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.ResponseStream(__response, __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + } + catch + { + __response.Dispose(); + throw; + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// image-to-image/upscale
+ /// Create a higher resolution version of an input image.
+ /// This operation outputs an image with a maximum pixel count of **4,194,304**. This is equivalent to dimensions such as `2048x2048` and `4096x1024`.
+ /// By default, the input image will be upscaled by a factor of 2. For additional control over the output dimensions, a `width` or `height` parameter may be specified. + ///
+ /// + /// + /// Default Value: application/json + /// + /// + /// + /// Example: <image binary> + /// + /// + /// Example: <image binary> + /// + /// + /// Desired width of the output image. Only one of `width` or `height` may be specified. + /// + /// + /// Desired height of the output image. Only one of `width` or `height` may be specified. + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// if [ -z "$STABILITY_API_KEY" ]; then
+ /// echo "STABILITY_API_KEY environment variable is not set"
+ /// exit 1
+ /// fi
+ /// OUTPUT_FILE=./out/v1_upscaled_image.png
+ /// BASE_URL=${API_HOST:-https://api.stability.ai}
+ /// URL="$BASE_URL/v1/generation/esrgan-v1-x2plus/image-to-image/upscale"
+ /// curl -f -sS -X POST "$URL" \
+ /// -H 'Content-Type: multipart/form-data' \
+ /// -H 'Accept: image/png' \
+ /// -H "Authorization: Bearer $STABILITY_API_KEY" \
+ /// -F 'image=@"../init_image.png"' \
+ /// -F 'width=1024' \
+ /// -o "$OUTPUT_FILE" + ///
+ public async global::System.Threading.Tasks.Task> UpscaleImageAsBytesAsResponseAsync( + string engineId, + global::System.IO.Stream image, + string imagename, + global::StabilityAI.UpscaleImageAccept? accept = default, + string? organization = default, + int? width = default, + int? height = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + + image = image ?? throw new global::System.ArgumentNullException(nameof(image)); + var request = new global::StabilityAI.UpscaleImageRequestBody + { + Image = global::System.Array.Empty(), + Imagename = imagename, + Width = width, + Height = height, + }; + PrepareArguments( + client: HttpClient); + PrepareUpscaleImageAsBytesArguments( + httpClient: HttpClient, + engineId: ref engineId, + accept: ref accept, + organization: ref organization, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_UpscaleImageAsBytesSecurityRequirements, + operationName: "UpscaleImageAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: $"/v1/generation/{engineId}/image-to-image/upscale", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/png"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("Accept", accept?.ToValueString() ?? string.Empty); + } + if (organization != default) + { + __httpRequest.Headers.TryAddWithoutValidation("Organization", organization.ToString()); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + var __contentImage = new global::System.Net.Http.StreamContent(image); + __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( + request.Imagename is null + ? "application/octet-stream" + : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch + { + ".aac" => "audio/aac", + ".flac" => "audio/flac", + ".gif" => "image/gif", + ".jpeg" => "image/jpeg", + ".jpg" => "image/jpeg", + ".json" => "application/json", + ".m4a" => "audio/mp4", + ".mp3" => "audio/mpeg", + ".mp4" => "video/mp4", + ".mpeg" => "audio/mpeg", + ".mpga" => "audio/mpeg", + ".oga" => "audio/ogg", + ".ogg" => "audio/ogg", + ".opus" => "audio/ogg", + ".pdf" => "application/pdf", + ".png" => "image/png", + ".txt" => "text/plain", + ".wav" => "audio/wav", + ".weba" => "audio/webm", + ".webm" => "video/webm", + ".webp" => "image/webp", + _ => "application/octet-stream", + }); + __httpRequestContent.Add( + content: __contentImage, + name: "\"image\"", + fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty); + if (__contentImage.Headers.ContentDisposition != null) + { + __contentImage.Headers.ContentDisposition.FileNameStar = null; + } + + if (request.Width != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Width, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"width\""); + + } + if (request.Height != default) + { + + __httpRequestContent.Add( + content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Height, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty), + name: "\"height\""); + + } + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareUpscaleImageAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + engineId: engineId!, + accept: accept, + organization: organization, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "UpscaleImageAsBytes", + methodName: "UpscaleImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image/upscale\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "UpscaleImageAsBytes", + methodName: "UpscaleImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image/upscale\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "UpscaleImageAsBytes", + methodName: "UpscaleImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image/upscale\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessUpscaleImageAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "UpscaleImageAsBytes", + methodName: "UpscaleImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image/upscale\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "UpscaleImageAsBytes", + methodName: "UpscaleImageAsBytesAsync", + pathTemplate: "$\"/v1/generation/{engineId}/image-to-image/upscale\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // bad_request: general error for invalid parameters

More specific errors:

- invalid_file_size: The file size of one or more of the provided files is invalid - invalid_mime_type: The mime type of one or more of the provided files is invalid - invalid_pixel_count: The requested image would exceed the maximum pixel count of 4,194,304 + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.Error? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.Error.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.Error.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // unauthorized: API key missing or invalid + if ((int)__response.StatusCode == 401) + { + string? __content_401 = null; + global::System.Exception? __exception_401 = null; + global::StabilityAI.Error? __value_401 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_401 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_401 = global::StabilityAI.Error.FromJson(__content_401, JsonSerializerContext); + } + else + { + __content_401 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_401 = global::StabilityAI.Error.FromJson(__content_401, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_401 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_401 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_401, + responseBody: __content_401, + responseObject: __value_401, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // permission_denied: You lack the necessary permissions to perform this action + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.Error? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.Error.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.Error.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // not_found: The requested resource was not found (e.g. specifing a model that does not exist) + if ((int)__response.StatusCode == 404) + { + string? __content_404 = null; + global::System.Exception? __exception_404 = null; + global::StabilityAI.Error? __value_404 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_404 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_404 = global::StabilityAI.Error.FromJson(__content_404, JsonSerializerContext); + } + else + { + __content_404 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_404 = global::StabilityAI.Error.FromJson(__content_404, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_404 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_404 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_404, + responseBody: __content_404, + responseObject: __value_404, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // server_error: Some unexpected server error occurred + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.Error? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.Error.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.Error.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessUpscaleImageAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + } +} \ No newline at end of file diff --git a/src/libs/StabilityAI/Generated/StabilityAI.V2alphaGenerationClient.CreateV2alphaGenerationStableImageInpaint.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.V2alphaGenerationClient.CreateV2alphaGenerationStableImageInpaint.g.cs index 2de6aff..8fb8b17 100644 --- a/src/libs/StabilityAI/Generated/StabilityAI.V2alphaGenerationClient.CreateV2alphaGenerationStableImageInpaint.g.cs +++ b/src/libs/StabilityAI/Generated/StabilityAI.V2alphaGenerationClient.CreateV2alphaGenerationStableImageInpaint.g.cs @@ -231,6 +231,10 @@ partial void ProcessCreateV2alphaGenerationStableImageInpaintResponseContent( __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || @@ -256,18 +260,6 @@ partial void ProcessCreateV2alphaGenerationStableImageInpaintResponseContent( var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (accept != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty), - name: "\"accept\""); - - } __httpRequest.Content = __httpRequestContent; diff --git a/src/libs/StabilityAI/Generated/StabilityAI.V2alphaGenerationClient.CreateV2alphaGenerationStableImageInpaintAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.V2alphaGenerationClient.CreateV2alphaGenerationStableImageInpaintAsBytes.g.cs new file mode 100644 index 0000000..8f1eef6 --- /dev/null +++ b/src/libs/StabilityAI/Generated/StabilityAI.V2alphaGenerationClient.CreateV2alphaGenerationStableImageInpaintAsBytes.g.cs @@ -0,0 +1,1204 @@ + +#nullable enable + +namespace StabilityAI +{ + public partial class V2alphaGenerationClient + { + + + private static readonly global::StabilityAI.EndPointSecurityRequirement s_CreateV2alphaGenerationStableImageInpaintAsBytesSecurityRequirement0 = + new global::StabilityAI.EndPointSecurityRequirement + { + Authorizations = new global::StabilityAI.EndPointAuthorizationRequirement[] + { new global::StabilityAI.EndPointAuthorizationRequirement + { + Type = "Http", + SchemeId = "HttpBearer", + Location = "Header", + Name = "Bearer", + FriendlyName = "Bearer", + }, + }, + }; + private static readonly global::StabilityAI.EndPointSecurityRequirement[] s_CreateV2alphaGenerationStableImageInpaintAsBytesSecurityRequirements = + new global::StabilityAI.EndPointSecurityRequirement[] + { s_CreateV2alphaGenerationStableImageInpaintAsBytesSecurityRequirement0, + }; + partial void PrepareCreateV2alphaGenerationStableImageInpaintAsBytesArguments( + global::System.Net.Http.HttpClient httpClient, + ref string contentType, + ref global::StabilityAI.CreateV2alphaGenerationStableImageInpaintAccept? accept, + global::StabilityAI.CreateV2alphaGenerationStableImageInpaintRequest request); + partial void PrepareCreateV2alphaGenerationStableImageInpaintAsBytesRequest( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpRequestMessage httpRequestMessage, + string contentType, + global::StabilityAI.CreateV2alphaGenerationStableImageInpaintAccept? accept, + global::StabilityAI.CreateV2alphaGenerationStableImageInpaintRequest request); + partial void ProcessCreateV2alphaGenerationStableImageInpaintAsBytesResponse( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpResponseMessage httpResponseMessage); + + partial void ProcessCreateV2alphaGenerationStableImageInpaintAsBytesResponseContent( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpResponseMessage httpResponseMessage, + ref byte[] content); + + /// + /// stable-image/inpaint
+ /// Inpaint an existing image, with or without a mask, using our latest-and-greatest inpainting model.
+ /// ### Search-and-Replace Mode
+ /// This mode is ideal for individuals of all levels of skill in design. It can be used for straightforward
+ /// adjustments to images. The service will automatically mask the most appropriate object based on the contents
+ /// of the `search_prompt`, and replace it with a generated result based on the `prompt`.
+ /// **How to use:** set the `mode` parameter to `search` and provide a short description of what to
+ /// search-and-replace in the `search_prompt` parameter.
+ /// ### Mask Mode
+ /// This mode allows for precise control of generative fill tasks on an image, down to the level of
+ /// individual pixels. Design professionals can provide a `mask` for the section of the image to be replaced,
+ /// and use standard image prompting to describe the full image as it should appear after the editing.
+ /// The resulting image will incorporate all of the elements described in the `prompt`.
+ /// **How to use:** set the `mode` parameter to `mask` and either pass in an `image` with an alpha channel
+ /// or provide an explicit mask image to the `mask` parameter. If both are present the `mask` parameter will
+ /// take precedence.
+ /// ### Price
+ /// - Requests with `mode` set to `search` cost 4 cents.
+ /// - Requests with `mode` set to `mask` cost 3 cents. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to get the image bytes directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2alpha/generation/stable-image/inpaint",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY"
+ /// },
+ /// files={
+ /// "image": open("./husky-in-a-field.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "golden retriever in a field",
+ /// "mode": "search",
+ /// "search_prompt": "dog",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./golden-retriever-in-a-field.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateV2alphaGenerationStableImageInpaintAsBytesAsync( + string contentType, + + global::StabilityAI.CreateV2alphaGenerationStableImageInpaintRequest request, + global::StabilityAI.CreateV2alphaGenerationStableImageInpaintAccept? accept = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + var __response = await CreateV2alphaGenerationStableImageInpaintAsBytesAsResponseAsync( + contentType: contentType, + + request: request, + accept: accept, + requestOptions: requestOptions, + cancellationToken: cancellationToken + ).ConfigureAwait(false); + + return __response.Body; + } + /// + /// stable-image/inpaint
+ /// Inpaint an existing image, with or without a mask, using our latest-and-greatest inpainting model.
+ /// ### Search-and-Replace Mode
+ /// This mode is ideal for individuals of all levels of skill in design. It can be used for straightforward
+ /// adjustments to images. The service will automatically mask the most appropriate object based on the contents
+ /// of the `search_prompt`, and replace it with a generated result based on the `prompt`.
+ /// **How to use:** set the `mode` parameter to `search` and provide a short description of what to
+ /// search-and-replace in the `search_prompt` parameter.
+ /// ### Mask Mode
+ /// This mode allows for precise control of generative fill tasks on an image, down to the level of
+ /// individual pixels. Design professionals can provide a `mask` for the section of the image to be replaced,
+ /// and use standard image prompting to describe the full image as it should appear after the editing.
+ /// The resulting image will incorporate all of the elements described in the `prompt`.
+ /// **How to use:** set the `mode` parameter to `mask` and either pass in an `image` with an alpha channel
+ /// or provide an explicit mask image to the `mask` parameter. If both are present the `mask` parameter will
+ /// take precedence.
+ /// ### Price
+ /// - Requests with `mode` set to `search` cost 4 cents.
+ /// - Requests with `mode` set to `mask` cost 3 cents. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to get the image bytes directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2alpha/generation/stable-image/inpaint",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY"
+ /// },
+ /// files={
+ /// "image": open("./husky-in-a-field.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "golden retriever in a field",
+ /// "mode": "search",
+ /// "search_prompt": "dog",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./golden-retriever-in-a-field.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task CreateV2alphaGenerationStableImageInpaintAsBytesAsStreamAsync( + string contentType, + + global::StabilityAI.CreateV2alphaGenerationStableImageInpaintRequest request, + global::StabilityAI.CreateV2alphaGenerationStableImageInpaintAccept? accept = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + PrepareArguments( + client: HttpClient); + PrepareCreateV2alphaGenerationStableImageInpaintAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateV2alphaGenerationStableImageInpaintAsBytesSecurityRequirements, + operationName: "CreateV2alphaGenerationStableImageInpaintAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2alpha/generation/stable-image/inpaint", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/jpeg"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateV2alphaGenerationStableImageInpaintAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createV2alphaGenerationStableImageInpaintAsBytes", + methodName: "CreateV2alphaGenerationStableImageInpaintAsBytesAsync", + pathTemplate: "\"/v2alpha/generation/stable-image/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseHeadersRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createV2alphaGenerationStableImageInpaintAsBytes", + methodName: "CreateV2alphaGenerationStableImageInpaintAsBytesAsync", + pathTemplate: "\"/v2alpha/generation/stable-image/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createV2alphaGenerationStableImageInpaintAsBytes", + methodName: "CreateV2alphaGenerationStableImageInpaintAsBytesAsync", + pathTemplate: "\"/v2alpha/generation/stable-image/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + try + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateV2alphaGenerationStableImageInpaintAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createV2alphaGenerationStableImageInpaintAsBytes", + methodName: "CreateV2alphaGenerationStableImageInpaintAsBytesAsync", + pathTemplate: "\"/v2alpha/generation/stable-image/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createV2alphaGenerationStableImageInpaintAsBytes", + methodName: "CreateV2alphaGenerationStableImageInpaintAsBytesAsync", + pathTemplate: "\"/v2alpha/generation/stable-image/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateV2alphaGenerationStableImageInpaintResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateV2alphaGenerationStableImageInpaintResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateV2alphaGenerationStableImageInpaintResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateV2alphaGenerationStableImageInpaintResponse5? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateV2alphaGenerationStableImageInpaintResponse5.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateV2alphaGenerationStableImageInpaintResponse5.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + try + { + __response.EnsureSuccessStatusCode(); + + var __content = await __response.Content.ReadAsStreamAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.ResponseStream(__response, __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + } + catch + { + __response.Dispose(); + throw; + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// stable-image/inpaint
+ /// Inpaint an existing image, with or without a mask, using our latest-and-greatest inpainting model.
+ /// ### Search-and-Replace Mode
+ /// This mode is ideal for individuals of all levels of skill in design. It can be used for straightforward
+ /// adjustments to images. The service will automatically mask the most appropriate object based on the contents
+ /// of the `search_prompt`, and replace it with a generated result based on the `prompt`.
+ /// **How to use:** set the `mode` parameter to `search` and provide a short description of what to
+ /// search-and-replace in the `search_prompt` parameter.
+ /// ### Mask Mode
+ /// This mode allows for precise control of generative fill tasks on an image, down to the level of
+ /// individual pixels. Design professionals can provide a `mask` for the section of the image to be replaced,
+ /// and use standard image prompting to describe the full image as it should appear after the editing.
+ /// The resulting image will incorporate all of the elements described in the `prompt`.
+ /// **How to use:** set the `mode` parameter to `mask` and either pass in an `image` with an alpha channel
+ /// or provide an explicit mask image to the `mask` parameter. If both are present the `mask` parameter will
+ /// take precedence.
+ /// ### Price
+ /// - Requests with `mode` set to `search` cost 4 cents.
+ /// - Requests with `mode` set to `mask` cost 3 cents. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to get the image bytes directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2alpha/generation/stable-image/inpaint",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY"
+ /// },
+ /// files={
+ /// "image": open("./husky-in-a-field.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "golden retriever in a field",
+ /// "mode": "search",
+ /// "search_prompt": "dog",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./golden-retriever-in-a-field.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task> CreateV2alphaGenerationStableImageInpaintAsBytesAsResponseAsync( + string contentType, + + global::StabilityAI.CreateV2alphaGenerationStableImageInpaintRequest request, + global::StabilityAI.CreateV2alphaGenerationStableImageInpaintAccept? accept = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + PrepareArguments( + client: HttpClient); + PrepareCreateV2alphaGenerationStableImageInpaintAsBytesArguments( + httpClient: HttpClient, + contentType: ref contentType, + accept: ref accept, + request: request); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_CreateV2alphaGenerationStableImageInpaintAsBytesSecurityRequirements, + operationName: "CreateV2alphaGenerationStableImageInpaintAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: false); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: "/v2alpha/generation/stable-image/inpaint", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Post, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/jpeg"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString()); + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + + + var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); + + __httpRequest.Content = __httpRequestContent; + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareCreateV2alphaGenerationStableImageInpaintAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + contentType: contentType!, + accept: accept, + request: request); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createV2alphaGenerationStableImageInpaintAsBytes", + methodName: "CreateV2alphaGenerationStableImageInpaintAsBytesAsync", + pathTemplate: "\"/v2alpha/generation/stable-image/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createV2alphaGenerationStableImageInpaintAsBytes", + methodName: "CreateV2alphaGenerationStableImageInpaintAsBytesAsync", + pathTemplate: "\"/v2alpha/generation/stable-image/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createV2alphaGenerationStableImageInpaintAsBytes", + methodName: "CreateV2alphaGenerationStableImageInpaintAsBytesAsync", + pathTemplate: "\"/v2alpha/generation/stable-image/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessCreateV2alphaGenerationStableImageInpaintAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createV2alphaGenerationStableImageInpaintAsBytes", + methodName: "CreateV2alphaGenerationStableImageInpaintAsBytesAsync", + pathTemplate: "\"/v2alpha/generation/stable-image/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "createV2alphaGenerationStableImageInpaintAsBytes", + methodName: "CreateV2alphaGenerationStableImageInpaintAsBytesAsync", + pathTemplate: "\"/v2alpha/generation/stable-image/inpaint\"", + httpMethod: "POST", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.CreateV2alphaGenerationStableImageInpaintResponse4? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.CreateV2alphaGenerationStableImageInpaintResponse4.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.CreateV2alphaGenerationStableImageInpaintResponse4.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.CreateV2alphaGenerationStableImageInpaintResponse5? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.CreateV2alphaGenerationStableImageInpaintResponse5.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.CreateV2alphaGenerationStableImageInpaintResponse5.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessCreateV2alphaGenerationStableImageInpaintAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// stable-image/inpaint
+ /// Inpaint an existing image, with or without a mask, using our latest-and-greatest inpainting model.
+ /// ### Search-and-Replace Mode
+ /// This mode is ideal for individuals of all levels of skill in design. It can be used for straightforward
+ /// adjustments to images. The service will automatically mask the most appropriate object based on the contents
+ /// of the `search_prompt`, and replace it with a generated result based on the `prompt`.
+ /// **How to use:** set the `mode` parameter to `search` and provide a short description of what to
+ /// search-and-replace in the `search_prompt` parameter.
+ /// ### Mask Mode
+ /// This mode allows for precise control of generative fill tasks on an image, down to the level of
+ /// individual pixels. Design professionals can provide a `mask` for the section of the image to be replaced,
+ /// and use standard image prompting to describe the full image as it should appear after the editing.
+ /// The resulting image will incorporate all of the elements described in the `prompt`.
+ /// **How to use:** set the `mode` parameter to `mask` and either pass in an `image` with an alpha channel
+ /// or provide an explicit mask image to the `mask` parameter. If both are present the `mask` parameter will
+ /// take precedence.
+ /// ### Price
+ /// - Requests with `mode` set to `search` cost 4 cents.
+ /// - Requests with `mode` set to `mask` cost 3 cents. + ///
+ /// + /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data + /// + /// + /// Specify `image/*` to get the image bytes directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + public async global::System.Threading.Tasks.Task CreateV2alphaGenerationStableImageInpaintAsBytesAsync( + string contentType, + global::StabilityAI.CreateV2alphaGenerationStableImageInpaintAccept? accept = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + var __request = new global::StabilityAI.CreateV2alphaGenerationStableImageInpaintRequest + { + }; + + return await CreateV2alphaGenerationStableImageInpaintAsBytesAsync( + contentType: contentType, + accept: accept, + request: __request, + requestOptions: requestOptions, + cancellationToken: cancellationToken).ConfigureAwait(false); + } + } +} \ No newline at end of file diff --git a/src/libs/StabilityAI/Generated/StabilityAI.V2alphaGenerationClient.CreateV2alphaGenerationStableImageUpscale.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.V2alphaGenerationClient.CreateV2alphaGenerationStableImageUpscale.g.cs index 0d7a2c2..a67c254 100644 --- a/src/libs/StabilityAI/Generated/StabilityAI.V2alphaGenerationClient.CreateV2alphaGenerationStableImageUpscale.g.cs +++ b/src/libs/StabilityAI/Generated/StabilityAI.V2alphaGenerationClient.CreateV2alphaGenerationStableImageUpscale.g.cs @@ -208,10 +208,6 @@ partial void ProcessCreateV2alphaGenerationStableImageUpscaleResponseContent( var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - var __contentImage = new global::System.Net.Http.ByteArrayContent(request.Image ?? global::System.Array.Empty()); __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( request.Imagename is null @@ -973,10 +969,6 @@ request.Imagename is null var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - var __contentImage = new global::System.Net.Http.StreamContent(image); __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( request.Imagename is null @@ -1630,10 +1622,6 @@ request.Imagename is null var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - var __contentImage = new global::System.Net.Http.StreamContent(image); __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( request.Imagename is null diff --git a/src/libs/StabilityAI/Generated/StabilityAI.V2alphaGenerationClient.GetV2alphaGenerationStableImageUpscaleResultById.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.V2alphaGenerationClient.GetV2alphaGenerationStableImageUpscaleResultById.g.cs index b511ea8..ccd7799 100644 --- a/src/libs/StabilityAI/Generated/StabilityAI.V2alphaGenerationClient.GetV2alphaGenerationStableImageUpscaleResultById.g.cs +++ b/src/libs/StabilityAI/Generated/StabilityAI.V2alphaGenerationClient.GetV2alphaGenerationStableImageUpscaleResultById.g.cs @@ -192,6 +192,10 @@ partial void ProcessGetV2alphaGenerationStableImageUpscaleResultByIdResponseCont __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; #endif + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "application/json"); + foreach (var __authorization in __authorizations) { if (__authorization.Type == "Http" || diff --git a/src/libs/StabilityAI/Generated/StabilityAI.V2alphaGenerationClient.GetV2alphaGenerationStableImageUpscaleResultByIdAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.V2alphaGenerationClient.GetV2alphaGenerationStableImageUpscaleResultByIdAsBytes.g.cs new file mode 100644 index 0000000..cd01a46 --- /dev/null +++ b/src/libs/StabilityAI/Generated/StabilityAI.V2alphaGenerationClient.GetV2alphaGenerationStableImageUpscaleResultByIdAsBytes.g.cs @@ -0,0 +1,1158 @@ + +#nullable enable + +namespace StabilityAI +{ + public partial class V2alphaGenerationClient + { + + + private static readonly global::StabilityAI.EndPointSecurityRequirement s_GetV2alphaGenerationStableImageUpscaleResultByIdAsBytesSecurityRequirement0 = + new global::StabilityAI.EndPointSecurityRequirement + { + Authorizations = new global::StabilityAI.EndPointAuthorizationRequirement[] + { new global::StabilityAI.EndPointAuthorizationRequirement + { + Type = "Http", + SchemeId = "HttpBearer", + Location = "Header", + Name = "Bearer", + FriendlyName = "Bearer", + }, + }, + }; + private static readonly global::StabilityAI.EndPointSecurityRequirement[] s_GetV2alphaGenerationStableImageUpscaleResultByIdAsBytesSecurityRequirements = + new global::StabilityAI.EndPointSecurityRequirement[] + { s_GetV2alphaGenerationStableImageUpscaleResultByIdAsBytesSecurityRequirement0, + }; + partial void PrepareGetV2alphaGenerationStableImageUpscaleResultByIdAsBytesArguments( + global::System.Net.Http.HttpClient httpClient, + ref string id, + ref global::StabilityAI.GetV2alphaGenerationStableImageUpscaleResultAccept? accept); + partial void PrepareGetV2alphaGenerationStableImageUpscaleResultByIdAsBytesRequest( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpRequestMessage httpRequestMessage, + string id, + global::StabilityAI.GetV2alphaGenerationStableImageUpscaleResultAccept? accept); + partial void ProcessGetV2alphaGenerationStableImageUpscaleResultByIdAsBytesResponse( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpResponseMessage httpResponseMessage); + + partial void ProcessGetV2alphaGenerationStableImageUpscaleResultByIdAsBytesResponseContent( + global::System.Net.Http.HttpClient httpClient, + global::System.Net.Http.HttpResponseMessage httpResponseMessage, + ref byte[] content); + + /// + /// stable-image/upscale/result
+ /// Fetch the result of an upscale generation by ID. Make sure to use the same API key to fetch the generation result
+ /// that you used to create the generation, otherwise you will receive a `404` response.
+ /// ### How is progress reported?
+ /// Your generation is either `in-progress` (i.e. status code `202`) or it is complete (i.e. status code `200`).
+ /// We may add more fine-grained progress reporting in the future (e.g. a numerical progress).
+ /// ### How long are results stored?
+ /// Results are stored for 24 hours after generation. After that, the results are deleted. + ///
+ /// + /// The `id` of a generation, typically used for async generations, that can be used to check the status of the generation or retrieve the result.
+ /// Example: a6dc6c6e20acda010fe14d71f180658f2896ed9b4ec25aa99a6ff06c796987c4 + /// + /// + /// Specify `image/*` to get the image bytes directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// generation_id = "e52772ac75b..."
+ /// response = requests.request(
+ /// "GET",
+ /// f"https://api.stability.ai/v2alpha/generation/stable-image/upscale/result/{generation_id}",
+ /// headers={
+ /// 'Accept': "image/*", # Use 'application/json' to receive base64 encoded JSON
+ /// 'authorization': f"Bearer sk-MYAPIKEY"
+ /// },
+ /// )
+ /// if response.status_code == 202:
+ /// print("Generation in-progress, try again in 10 seconds.")
+ /// elif response.status_code == 200:
+ /// print("Generation complete!")
+ /// with open("upscaled.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task GetV2alphaGenerationStableImageUpscaleResultByIdAsBytesAsync( + string id, + global::StabilityAI.GetV2alphaGenerationStableImageUpscaleResultAccept? accept = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + var __response = await GetV2alphaGenerationStableImageUpscaleResultByIdAsBytesAsResponseAsync( + id: id, + accept: accept, + requestOptions: requestOptions, + cancellationToken: cancellationToken + ).ConfigureAwait(false); + + return __response.Body; + } + /// + /// stable-image/upscale/result
+ /// Fetch the result of an upscale generation by ID. Make sure to use the same API key to fetch the generation result
+ /// that you used to create the generation, otherwise you will receive a `404` response.
+ /// ### How is progress reported?
+ /// Your generation is either `in-progress` (i.e. status code `202`) or it is complete (i.e. status code `200`).
+ /// We may add more fine-grained progress reporting in the future (e.g. a numerical progress).
+ /// ### How long are results stored?
+ /// Results are stored for 24 hours after generation. After that, the results are deleted. + ///
+ /// + /// The `id` of a generation, typically used for async generations, that can be used to check the status of the generation or retrieve the result.
+ /// Example: a6dc6c6e20acda010fe14d71f180658f2896ed9b4ec25aa99a6ff06c796987c4 + /// + /// + /// Specify `image/*` to get the image bytes directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// generation_id = "e52772ac75b..."
+ /// response = requests.request(
+ /// "GET",
+ /// f"https://api.stability.ai/v2alpha/generation/stable-image/upscale/result/{generation_id}",
+ /// headers={
+ /// 'Accept': "image/*", # Use 'application/json' to receive base64 encoded JSON
+ /// 'authorization': f"Bearer sk-MYAPIKEY"
+ /// },
+ /// )
+ /// if response.status_code == 202:
+ /// print("Generation in-progress, try again in 10 seconds.")
+ /// elif response.status_code == 200:
+ /// print("Generation complete!")
+ /// with open("upscaled.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task GetV2alphaGenerationStableImageUpscaleResultByIdAsBytesAsStreamAsync( + string id, + global::StabilityAI.GetV2alphaGenerationStableImageUpscaleResultAccept? accept = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + PrepareArguments( + client: HttpClient); + PrepareGetV2alphaGenerationStableImageUpscaleResultByIdAsBytesArguments( + httpClient: HttpClient, + id: ref id, + accept: ref accept); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_GetV2alphaGenerationStableImageUpscaleResultByIdAsBytesSecurityRequirements, + operationName: "GetV2alphaGenerationStableImageUpscaleResultByIdAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: true); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: $"/v2alpha/generation/stable-image/upscale/result/{id}", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Get, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/jpeg"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareGetV2alphaGenerationStableImageUpscaleResultByIdAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + id: id!, + accept: accept); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "getV2alphaGenerationStableImageUpscaleResultByIdAsBytes", + methodName: "GetV2alphaGenerationStableImageUpscaleResultByIdAsBytesAsync", + pathTemplate: "$\"/v2alpha/generation/stable-image/upscale/result/{id}\"", + httpMethod: "GET", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseHeadersRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "getV2alphaGenerationStableImageUpscaleResultByIdAsBytes", + methodName: "GetV2alphaGenerationStableImageUpscaleResultByIdAsBytesAsync", + pathTemplate: "$\"/v2alpha/generation/stable-image/upscale/result/{id}\"", + httpMethod: "GET", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "getV2alphaGenerationStableImageUpscaleResultByIdAsBytes", + methodName: "GetV2alphaGenerationStableImageUpscaleResultByIdAsBytesAsync", + pathTemplate: "$\"/v2alpha/generation/stable-image/upscale/result/{id}\"", + httpMethod: "GET", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + try + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessGetV2alphaGenerationStableImageUpscaleResultByIdAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "getV2alphaGenerationStableImageUpscaleResultByIdAsBytes", + methodName: "GetV2alphaGenerationStableImageUpscaleResultByIdAsBytesAsync", + pathTemplate: "$\"/v2alpha/generation/stable-image/upscale/result/{id}\"", + httpMethod: "GET", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "getV2alphaGenerationStableImageUpscaleResultByIdAsBytes", + methodName: "GetV2alphaGenerationStableImageUpscaleResultByIdAsBytesAsync", + pathTemplate: "$\"/v2alpha/generation/stable-image/upscale/result/{id}\"", + httpMethod: "GET", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.GetV2alphaGenerationStableImageUpscaleResultResponse5? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.GetV2alphaGenerationStableImageUpscaleResultResponse5.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.GetV2alphaGenerationStableImageUpscaleResultResponse5.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // id: the generation either does not exist or has expired. + if ((int)__response.StatusCode == 404) + { + string? __content_404 = null; + global::System.Exception? __exception_404 = null; + global::StabilityAI.GetV2alphaGenerationStableImageUpscaleResultResponse6? __value_404 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_404 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_404 = global::StabilityAI.GetV2alphaGenerationStableImageUpscaleResultResponse6.FromJson(__content_404, JsonSerializerContext); + } + else + { + __content_404 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_404 = global::StabilityAI.GetV2alphaGenerationStableImageUpscaleResultResponse6.FromJson(__content_404, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_404 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_404 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_404, + responseBody: __content_404, + responseObject: __value_404, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.GetV2alphaGenerationStableImageUpscaleResultResponse7? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.GetV2alphaGenerationStableImageUpscaleResultResponse7.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.GetV2alphaGenerationStableImageUpscaleResultResponse7.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + try + { + __response.EnsureSuccessStatusCode(); + + var __content = await __response.Content.ReadAsStreamAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.ResponseStream(__response, __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + } + catch + { + __response.Dispose(); + throw; + } + } + finally + { + __httpRequest?.Dispose(); + } + } + /// + /// stable-image/upscale/result
+ /// Fetch the result of an upscale generation by ID. Make sure to use the same API key to fetch the generation result
+ /// that you used to create the generation, otherwise you will receive a `404` response.
+ /// ### How is progress reported?
+ /// Your generation is either `in-progress` (i.e. status code `202`) or it is complete (i.e. status code `200`).
+ /// We may add more fine-grained progress reporting in the future (e.g. a numerical progress).
+ /// ### How long are results stored?
+ /// Results are stored for 24 hours after generation. After that, the results are deleted. + ///
+ /// + /// The `id` of a generation, typically used for async generations, that can be used to check the status of the generation or retrieve the result.
+ /// Example: a6dc6c6e20acda010fe14d71f180658f2896ed9b4ec25aa99a6ff06c796987c4 + /// + /// + /// Specify `image/*` to get the image bytes directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/* + /// + /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering. + /// The token to cancel the operation with + /// + /// + /// import requests
+ /// generation_id = "e52772ac75b..."
+ /// response = requests.request(
+ /// "GET",
+ /// f"https://api.stability.ai/v2alpha/generation/stable-image/upscale/result/{generation_id}",
+ /// headers={
+ /// 'Accept': "image/*", # Use 'application/json' to receive base64 encoded JSON
+ /// 'authorization': f"Bearer sk-MYAPIKEY"
+ /// },
+ /// )
+ /// if response.status_code == 202:
+ /// print("Generation in-progress, try again in 10 seconds.")
+ /// elif response.status_code == 200:
+ /// print("Generation complete!")
+ /// with open("upscaled.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json())) + ///
+ public async global::System.Threading.Tasks.Task> GetV2alphaGenerationStableImageUpscaleResultByIdAsBytesAsResponseAsync( + string id, + global::StabilityAI.GetV2alphaGenerationStableImageUpscaleResultAccept? accept = default, + global::StabilityAI.AutoSDKRequestOptions? requestOptions = default, + global::System.Threading.CancellationToken cancellationToken = default) + { + PrepareArguments( + client: HttpClient); + PrepareGetV2alphaGenerationStableImageUpscaleResultByIdAsBytesArguments( + httpClient: HttpClient, + id: ref id, + accept: ref accept); + + + var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations( + availableAuthorizations: Authorizations, + securityRequirements: s_GetV2alphaGenerationStableImageUpscaleResultByIdAsBytesSecurityRequirements, + operationName: "GetV2alphaGenerationStableImageUpscaleResultByIdAsBytesAsync"); + + using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource( + clientOptions: Options, + requestOptions: requestOptions, + cancellationToken: cancellationToken); + var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken; + var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString( + clientOptions: Options, + requestOptions: requestOptions, + fallbackValue: ReadResponseAsString); + var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts( + clientOptions: Options, + requestOptions: requestOptions, + supportsRetry: true); + + global::System.Net.Http.HttpRequestMessage __CreateHttpRequest() + { + + var __pathBuilder = new global::StabilityAI.PathBuilder( + path: $"/v2alpha/generation/stable-image/upscale/result/{id}", + baseUri: HttpClient.BaseAddress); + var __path = __pathBuilder.ToString(); + __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters( + path: __path, + clientParameters: Options.QueryParameters, + requestParameters: requestOptions?.QueryParameters); + var __httpRequest = new global::System.Net.Http.HttpRequestMessage( + method: global::System.Net.Http.HttpMethod.Get, + requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute)); +#if NET6_0_OR_GREATER + __httpRequest.Version = global::System.Net.HttpVersion.Version11; + __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher; +#endif + + __httpRequest.Headers.TryAddWithoutValidation( + "Accept", + "image/jpeg"); + + foreach (var __authorization in __authorizations) + { + if (__authorization.Type == "Http" || + __authorization.Type == "OAuth2" || + __authorization.Type == "OpenIdConnect") + { + __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue( + scheme: __authorization.Name, + parameter: __authorization.Value); + } + else if (__authorization.Type == "ApiKey" && + __authorization.Location == "Header") + { + __httpRequest.Headers.Add(__authorization.Name, __authorization.Value); + } + } + + if (accept != default) + { + __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty); + } + + global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders( + request: __httpRequest, + clientHeaders: Options.Headers, + requestHeaders: requestOptions?.Headers); + + PrepareRequest( + client: HttpClient, + request: __httpRequest); + PrepareGetV2alphaGenerationStableImageUpscaleResultByIdAsBytesRequest( + httpClient: HttpClient, + httpRequestMessage: __httpRequest, + id: id!, + accept: accept); + + return __httpRequest; + } + + global::System.Net.Http.HttpRequestMessage? __httpRequest = null; + global::System.Net.Http.HttpResponseMessage? __response = null; + var __attemptNumber = 0; + try + { + for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++) + { + __attemptNumber = __attempt; + __httpRequest = __CreateHttpRequest(); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "getV2alphaGenerationStableImageUpscaleResultByIdAsBytes", + methodName: "GetV2alphaGenerationStableImageUpscaleResultByIdAsBytesAsync", + pathTemplate: "$\"/v2alpha/generation/stable-image/upscale/result/{id}\"", + httpMethod: "GET", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + try + { + __response = await HttpClient.SendAsync( + request: __httpRequest, + completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + } + catch (global::System.Net.Http.HttpRequestException __exception) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: null, + attempt: __attempt); + var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested; + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "getV2alphaGenerationStableImageUpscaleResultByIdAsBytes", + methodName: "GetV2alphaGenerationStableImageUpscaleResultByIdAsBytesAsync", + pathTemplate: "$\"/v2alpha/generation/stable-image/upscale/result/{id}\"", + httpMethod: "GET", + baseUri: BaseUri, + request: __httpRequest!, + response: null, + exception: __exception, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: __willRetry, + retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null, + retryReason: "exception", + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + if (!__willRetry) + { + throw; + } + + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + if (__response != null && + __attempt < __maxAttempts && + global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode)) + { + var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay( + clientOptions: Options, + requestOptions: requestOptions, + response: __response, + attempt: __attempt); + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "getV2alphaGenerationStableImageUpscaleResultByIdAsBytes", + methodName: "GetV2alphaGenerationStableImageUpscaleResultByIdAsBytesAsync", + pathTemplate: "$\"/v2alpha/generation/stable-image/upscale/result/{id}\"", + httpMethod: "GET", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attempt, + maxAttempts: __maxAttempts, + willRetry: true, + retryDelay: __retryDelay, + retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture), + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + __response.Dispose(); + __response = null; + __httpRequest.Dispose(); + __httpRequest = null; + await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync( + retryDelay: __retryDelay, + cancellationToken: __effectiveCancellationToken).ConfigureAwait(false); + continue; + } + + break; + } + + if (__response == null) + { + throw new global::System.InvalidOperationException("No response received."); + } + + using (__response) + { + + ProcessResponse( + client: HttpClient, + response: __response); + ProcessGetV2alphaGenerationStableImageUpscaleResultByIdAsBytesResponse( + httpClient: HttpClient, + httpResponseMessage: __response); + if (__response.IsSuccessStatusCode) + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "getV2alphaGenerationStableImageUpscaleResultByIdAsBytes", + methodName: "GetV2alphaGenerationStableImageUpscaleResultByIdAsBytesAsync", + pathTemplate: "$\"/v2alpha/generation/stable-image/upscale/result/{id}\"", + httpMethod: "GET", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + else + { + await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync( + clientOptions: Options, + context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext( + operationId: "getV2alphaGenerationStableImageUpscaleResultByIdAsBytes", + methodName: "GetV2alphaGenerationStableImageUpscaleResultByIdAsBytesAsync", + pathTemplate: "$\"/v2alpha/generation/stable-image/upscale/result/{id}\"", + httpMethod: "GET", + baseUri: BaseUri, + request: __httpRequest!, + response: __response, + exception: null, + clientOptions: Options, + requestOptions: requestOptions, + attempt: __attemptNumber, + maxAttempts: __maxAttempts, + willRetry: false, + retryDelay: null, + retryReason: global::System.String.Empty, + cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false); + } + // Invalid parameter(s), see the `errors` field for details. + if ((int)__response.StatusCode == 400) + { + string? __content_400 = null; + global::System.Exception? __exception_400 = null; + global::StabilityAI.GetV2alphaGenerationStableImageUpscaleResultResponse5? __value_400 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_400 = global::StabilityAI.GetV2alphaGenerationStableImageUpscaleResultResponse5.FromJson(__content_400, JsonSerializerContext); + } + else + { + __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_400 = global::StabilityAI.GetV2alphaGenerationStableImageUpscaleResultResponse5.FromJson(__content_400, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_400 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_400 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_400, + responseBody: __content_400, + responseObject: __value_400, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // Your request was flagged by our content moderation system. + if ((int)__response.StatusCode == 403) + { + string? __content_403 = null; + global::System.Exception? __exception_403 = null; + global::StabilityAI.ContentModerationResponse? __value_403 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + else + { + __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_403 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_403 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_403, + responseBody: __content_403, + responseObject: __value_403, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // id: the generation either does not exist or has expired. + if ((int)__response.StatusCode == 404) + { + string? __content_404 = null; + global::System.Exception? __exception_404 = null; + global::StabilityAI.GetV2alphaGenerationStableImageUpscaleResultResponse6? __value_404 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_404 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_404 = global::StabilityAI.GetV2alphaGenerationStableImageUpscaleResultResponse6.FromJson(__content_404, JsonSerializerContext); + } + else + { + __content_404 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_404 = global::StabilityAI.GetV2alphaGenerationStableImageUpscaleResultResponse6.FromJson(__content_404, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_404 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_404 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_404, + responseBody: __content_404, + responseObject: __value_404, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new). + if ((int)__response.StatusCode == 500) + { + string? __content_500 = null; + global::System.Exception? __exception_500 = null; + global::StabilityAI.GetV2alphaGenerationStableImageUpscaleResultResponse7? __value_500 = null; + try + { + if (__effectiveReadResponseAsString) + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + __value_500 = global::StabilityAI.GetV2alphaGenerationStableImageUpscaleResultResponse7.FromJson(__content_500, JsonSerializerContext); + } + else + { + __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false); + + __value_500 = global::StabilityAI.GetV2alphaGenerationStableImageUpscaleResultResponse7.FromJson(__content_500, JsonSerializerContext); + } + } + catch (global::System.Exception __ex) + { + __exception_500 = __ex; + } + + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content_500 ?? __response.ReasonPhrase ?? string.Empty, + innerException: __exception_500, + responseBody: __content_500, + responseObject: __value_500, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + + if (__effectiveReadResponseAsString) + { + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + ProcessGetV2alphaGenerationStableImageUpscaleResultByIdAsBytesResponseContent( + httpClient: HttpClient, + httpResponseMessage: __response, + content: ref __content); + + try + { + __response.EnsureSuccessStatusCode(); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: null, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + else + { + try + { + __response.EnsureSuccessStatusCode(); + var __content = await __response.Content.ReadAsByteArrayAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + + return new global::StabilityAI.AutoSDKHttpResponse( + statusCode: __response.StatusCode, + headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response), + requestUri: __response.RequestMessage?.RequestUri, + body: __content); + } + catch (global::System.Exception __ex) + { + string? __content = null; + try + { + __content = await __response.Content.ReadAsStringAsync( + #if NET5_0_OR_GREATER + __effectiveCancellationToken + #endif + ).ConfigureAwait(false); + } + catch (global::System.Exception) + { + } + + throw global::StabilityAI.ApiException.Create( + statusCode: __response.StatusCode, + message: __content ?? __response.ReasonPhrase ?? string.Empty, + innerException: __ex, + responseBody: __content, + responseHeaders: global::System.Linq.Enumerable.ToDictionary( + __response.Headers, + h => h.Key, + h => h.Value)); + } + } + + } + } + finally + { + __httpRequest?.Dispose(); + } + } + } +} \ No newline at end of file diff --git a/src/libs/StabilityAI/Generated/StabilityAI.x3dClient.Create3dStableFast3d.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.x3dClient.Create3dStableFast3d.g.cs index 735b16e..af26b38 100644 --- a/src/libs/StabilityAI/Generated/StabilityAI.x3dClient.Create3dStableFast3d.g.cs +++ b/src/libs/StabilityAI/Generated/StabilityAI.x3dClient.Create3dStableFast3d.g.cs @@ -284,34 +284,6 @@ partial void ProcessCreate3dStableFast3dResponseContent( var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } var __contentImage = new global::System.Net.Http.ByteArrayContent(request.Image ?? global::System.Array.Empty()); __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( request.Imagename is null @@ -968,34 +940,6 @@ request.Imagename is null var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } var __contentImage = new global::System.Net.Http.ByteArrayContent(request.Image ?? global::System.Array.Empty()); __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( request.Imagename is null @@ -1889,34 +1833,6 @@ request.Imagename is null var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } var __contentImage = new global::System.Net.Http.StreamContent(image); __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( request.Imagename is null @@ -2671,34 +2587,6 @@ request.Imagename is null var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } var __contentImage = new global::System.Net.Http.StreamContent(image); __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( request.Imagename is null @@ -3424,34 +3312,6 @@ request.Imagename is null var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } var __contentImage = new global::System.Net.Http.StreamContent(image); __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( request.Imagename is null diff --git a/src/libs/StabilityAI/Generated/StabilityAI.x3dClient.Create3dStablePointAware3d.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.x3dClient.Create3dStablePointAware3d.g.cs index d5ba095..a8c24f1 100644 --- a/src/libs/StabilityAI/Generated/StabilityAI.x3dClient.Create3dStablePointAware3d.g.cs +++ b/src/libs/StabilityAI/Generated/StabilityAI.x3dClient.Create3dStablePointAware3d.g.cs @@ -314,34 +314,6 @@ partial void ProcessCreate3dStablePointAware3dResponseContent( var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } var __contentImage = new global::System.Net.Http.ByteArrayContent(request.Image ?? global::System.Array.Empty()); __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( request.Imagename is null @@ -1037,34 +1009,6 @@ request.Imagename is null var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } var __contentImage = new global::System.Net.Http.ByteArrayContent(request.Image ?? global::System.Array.Empty()); __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( request.Imagename is null @@ -2048,34 +1992,6 @@ request.Imagename is null var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } var __contentImage = new global::System.Net.Http.StreamContent(image); __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( request.Imagename is null @@ -2887,34 +2803,6 @@ request.Imagename is null var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } var __contentImage = new global::System.Net.Http.StreamContent(image); __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( request.Imagename is null @@ -3697,34 +3585,6 @@ request.Imagename is null var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent(); - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(contentType ?? string.Empty), - name: "\"content-type\""); - - if (stabilityClientId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty), - name: "\"stability-client-id\""); - - } - if (stabilityClientUserId != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty), - name: "\"stability-client-user-id\""); - - } - if (stabilityClientVersion != default) - { - - __httpRequestContent.Add( - content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty), - name: "\"stability-client-version\""); - - } var __contentImage = new global::System.Net.Http.StreamContent(image); __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue( request.Imagename is null diff --git a/src/libs/StabilityAI/Generated/autosdk.generated-examples.json b/src/libs/StabilityAI/Generated/autosdk.generated-examples.json index 5d0863e..476b94a 100644 --- a/src/libs/StabilityAI/Generated/autosdk.generated-examples.json +++ b/src/libs/StabilityAI/Generated/autosdk.generated-examples.json @@ -28,7 +28,7 @@ "Slug": "sketch", "Description": "This service offers an ideal solution for design projects that require brainstorming and\nfrequent iterations. It upgrades rough hand-drawn sketches to refined outputs with precise\ncontrol. For non-sketch images, it allows detailed manipulation of the final appearance by\nleveraging the contour lines and edges within the image.\n\n### Try it out\nGrab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=ZKIAqHzJzzUo)\n\n### How to use\nPlease invoke this endpoint with a \u0060POST\u0060 request.\n\nThe headers of the request must include an API key in the \u0060authorization\u0060 field. The body of the request must be\n\u0060multipart/form-data\u0060, and the \u0060accept\u0060 header should be set to one of the following:\n - \u0060image/*\u0060 to receive the image in the format specified by the \u0060output_format\u0060 parameter.\n - \u0060application/json\u0060 to receive the image encoded as base64 in a JSON response.\n\nThe body of the request should include:\n- \u0060image\u0060\n- \u0060prompt\u0060\n\nThe body may optionally include:\n- \u0060control_strength\u0060\n- \u0060negative_prompt\u0060\n- \u0060seed\u0060\n- \u0060output_format\u0060\n- \u0060style_preset\u0060\n\n\u003E **Note:** for more details about these parameters please see the request schema below.\n\n### Output\nThe resolution of the generated image will match that of the input image.\n\n### Credits\nFlat rate of 5 credits per successful generation. You will not be charged for failed generations.", "Language": "http", - "Code": "### Sketch\nPOST {{host}}/v2beta/stable-image/control/sketch\nAuthorization: Bearer {{token}}\ncontent-type: {{content-type}}\naccept: image/*\nstability-client-id: {{stability-client-id}}\nstability-client-user-id: {{stability-client-user-id}}\nstability-client-version: {{stability-client-version}}\nContent-Type: multipart/form-data\nAccept: application/json, application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n\n## Responses\n# 200\n# Description: Generation was successful.\n# Content-Type: application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n# 400\n# Description: Invalid parameter(s), see the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 403\n# Description: Your request was flagged by our content moderation system.\n# Content-Type: application/json\n# 413\n# Description: Your request was larger than 10MiB.\n# Content-Type: application/json\n# 422\n# Description: Your request was well-formed, but rejected. See the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 429\n# Description: You have made more than 150 requests in 10 seconds.\n# Content-Type: application/json\n# 500\n# Description: An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).\n# Content-Type: application/json", + "Code": "### Sketch\nPOST {{host}}/v2beta/stable-image/control/sketch\nAuthorization: Bearer {{token}}\ncontent-type: {{content-type}}\naccept: image/*\nstability-client-id: {{stability-client-id}}\nstability-client-user-id: {{stability-client-user-id}}\nstability-client-version: {{stability-client-version}}\nContent-Type: multipart/form-data; boundary=AutoSDKBoundary\nAccept: application/json, application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022prompt\u0022\n\nstring\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022image\u0022; filename=\u0022image.bin\u0022\nContent-Type: application/octet-stream\n\n\u003C ./image.bin\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022control_strength\u0022\n\n0.7\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022negative_prompt\u0022\n\nstring\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022seed\u0022\n\n0\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022output_format\u0022\n\npng\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022style_preset\u0022\n\nenhance\n--AutoSDKBoundary--\n\n## Responses\n# 200\n# Description: Generation was successful.\n# Content-Type: application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n# 400\n# Description: Invalid parameter(s), see the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 403\n# Description: Your request was flagged by our content moderation system.\n# Content-Type: application/json\n# 413\n# Description: Your request was larger than 10MiB.\n# Content-Type: application/json\n# 422\n# Description: Your request was well-formed, but rejected. See the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 429\n# Description: You have made more than 150 requests in 10 seconds.\n# Content-Type: application/json\n# 500\n# Description: An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).\n# Content-Type: application/json", "Format": "http", "OperationId": "createStableImageControlSketch", "Setup": null @@ -39,7 +39,7 @@ "Slug": "structure", "Description": "This service excels in generating images by maintaining the structure of an input image,\nmaking it especially valuable for advanced content creation scenarios such as recreating\nscenes or rendering characters from models.\n\n### Try it out\nGrab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=59RaZazXz0AU)\n\n### How to use\nPlease invoke this endpoint with a \u0060POST\u0060 request.\n\nThe headers of the request must include an API key in the \u0060authorization\u0060 field. The body of the request must be\n\u0060multipart/form-data\u0060, and the \u0060accept\u0060 header should be set to one of the following:\n - \u0060image/*\u0060 to receive the image in the format specified by the \u0060output_format\u0060 parameter.\n - \u0060application/json\u0060 to receive the image encoded as base64 in a JSON response.\n\nThe body of the request should include:\n- \u0060image\u0060\n- \u0060prompt\u0060\n\nThe body may optionally include:\n- \u0060control_strength\u0060\n- \u0060negative_prompt\u0060\n- \u0060seed\u0060\n- \u0060output_format\u0060\n- \u0060style_preset\u0060\n\n\u003E **Note:** for more details about these parameters please see the request schema below.\n\n### Output\nThe resolution of the generated image will match that of the input image.\n\n### Credits\nFlat rate of 5 credits per successful generation. You will not be charged for failed generations.", "Language": "http", - "Code": "### Structure\nPOST {{host}}/v2beta/stable-image/control/structure\nAuthorization: Bearer {{token}}\ncontent-type: {{content-type}}\naccept: image/*\nstability-client-id: {{stability-client-id}}\nstability-client-user-id: {{stability-client-user-id}}\nstability-client-version: {{stability-client-version}}\nContent-Type: multipart/form-data\nAccept: application/json, application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n\n## Responses\n# 200\n# Description: Generation was successful.\n# Content-Type: application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n# 400\n# Description: Invalid parameter(s), see the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 403\n# Description: Your request was flagged by our content moderation system.\n# Content-Type: application/json\n# 413\n# Description: Your request was larger than 10MiB.\n# Content-Type: application/json\n# 422\n# Description: Your request was well-formed, but rejected. See the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 429\n# Description: You have made more than 150 requests in 10 seconds.\n# Content-Type: application/json\n# 500\n# Description: An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).\n# Content-Type: application/json", + "Code": "### Structure\nPOST {{host}}/v2beta/stable-image/control/structure\nAuthorization: Bearer {{token}}\ncontent-type: {{content-type}}\naccept: image/*\nstability-client-id: {{stability-client-id}}\nstability-client-user-id: {{stability-client-user-id}}\nstability-client-version: {{stability-client-version}}\nContent-Type: multipart/form-data; boundary=AutoSDKBoundary\nAccept: application/json, application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022prompt\u0022\n\nstring\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022image\u0022; filename=\u0022image.bin\u0022\nContent-Type: application/octet-stream\n\n\u003C ./image.bin\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022control_strength\u0022\n\n0.7\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022negative_prompt\u0022\n\nstring\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022seed\u0022\n\n0\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022output_format\u0022\n\npng\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022style_preset\u0022\n\nenhance\n--AutoSDKBoundary--\n\n## Responses\n# 200\n# Description: Generation was successful.\n# Content-Type: application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n# 400\n# Description: Invalid parameter(s), see the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 403\n# Description: Your request was flagged by our content moderation system.\n# Content-Type: application/json\n# 413\n# Description: Your request was larger than 10MiB.\n# Content-Type: application/json\n# 422\n# Description: Your request was well-formed, but rejected. See the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 429\n# Description: You have made more than 150 requests in 10 seconds.\n# Content-Type: application/json\n# 500\n# Description: An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).\n# Content-Type: application/json", "Format": "http", "OperationId": "createStableImageControlStructure", "Setup": null @@ -50,7 +50,7 @@ "Slug": "style-guide", "Description": "This service extracts stylistic elements from an input image (control image) and uses it to guide the creation of an output image based on the prompt. The result is a new image in the same style as the control image.\n\n### Try it out\nGrab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=y0WKjG72RvTE)\n\n### How to use\nPlease invoke this endpoint with a \u0060POST\u0060 request.\n\nThe headers of the request must include an API key in the \u0060authorization\u0060 field. The body of the request must be\n\u0060multipart/form-data\u0060, and the \u0060accept\u0060 header should be set to one of the following:\n - \u0060image/*\u0060 to receive the image in the format specified by the \u0060output_format\u0060 parameter.\n - \u0060application/json\u0060 to receive the image encoded as base64 in a JSON response.\n\nThe body of the request should include:\n- \u0060image\u0060\n- \u0060prompt\u0060\n\nThe body may optionally include:\n- \u0060negative_prompt\u0060\n- \u0060aspect_ratio\u0060\n- \u0060fidelity\u0060\n- \u0060seed\u0060\n- \u0060output_format\u0060\n- \u0060style_preset\u0060\n\n\u003E **Note:** for more details about these parameters please see the request schema below.\n\n### Output\nThe resolution of the generated image will be 1MP. The default resolution is 1024x1024.\n\n### Credits\nFlat rate of 5 credits per successful generation. You will not be charged for failed generations.", "Language": "http", - "Code": "### Style Guide\nPOST {{host}}/v2beta/stable-image/control/style\nAuthorization: Bearer {{token}}\ncontent-type: {{content-type}}\naccept: image/*\nstability-client-id: {{stability-client-id}}\nstability-client-user-id: {{stability-client-user-id}}\nstability-client-version: {{stability-client-version}}\nContent-Type: multipart/form-data\nAccept: application/json, application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n\n## Responses\n# 200\n# Description: Generation was successful.\n# Content-Type: application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n# 400\n# Description: Invalid parameter(s), see the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 403\n# Description: Your request was flagged by our content moderation system.\n# Content-Type: application/json\n# 413\n# Description: Your request was larger than 10MiB.\n# Content-Type: application/json\n# 422\n# Description: Your request was well-formed, but rejected. See the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 429\n# Description: You have made more than 150 requests in 10 seconds.\n# Content-Type: application/json\n# 500\n# Description: An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).\n# Content-Type: application/json", + "Code": "### Style Guide\nPOST {{host}}/v2beta/stable-image/control/style\nAuthorization: Bearer {{token}}\ncontent-type: {{content-type}}\naccept: image/*\nstability-client-id: {{stability-client-id}}\nstability-client-user-id: {{stability-client-user-id}}\nstability-client-version: {{stability-client-version}}\nContent-Type: multipart/form-data; boundary=AutoSDKBoundary\nAccept: application/json, application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022prompt\u0022\n\nstring\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022image\u0022; filename=\u0022image.bin\u0022\nContent-Type: application/octet-stream\n\n\u003C ./image.bin\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022negative_prompt\u0022\n\nstring\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022aspect_ratio\u0022\n\n1:1\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022fidelity\u0022\n\n0.5\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022seed\u0022\n\n0\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022output_format\u0022\n\npng\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022style_preset\u0022\n\nenhance\n--AutoSDKBoundary--\n\n## Responses\n# 200\n# Description: Generation was successful.\n# Content-Type: application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n# 400\n# Description: Invalid parameter(s), see the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 403\n# Description: Your request was flagged by our content moderation system.\n# Content-Type: application/json\n# 413\n# Description: Your request was larger than 10MiB.\n# Content-Type: application/json\n# 422\n# Description: Your request was well-formed, but rejected. See the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 429\n# Description: You have made more than 150 requests in 10 seconds.\n# Content-Type: application/json\n# 500\n# Description: An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).\n# Content-Type: application/json", "Format": "http", "OperationId": "createStableImageControlStyle", "Setup": null @@ -61,7 +61,7 @@ "Slug": "style-transfer", "Description": "Style Transfer applies visual characteristics from reference style images to target images.\nWhile Style Guide extracts stylistic elements from an input image (control image) and uses it\nto guide the creation of an output image based on the prompt, Style Transfer specifically\ntransforms existing content while preserving the original composition.\nThis tool helps create consistent content across multiple assets.\n\n### Try it out\nGrab your [API key](https://platform.stability.ai/account/keys) and head over to\n[![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=YCrxdv5LzqJ9)\n\n### How to use\nPlease invoke this endpoint with a \u0060POST\u0060 request.\n\nThe headers of the request must include an API key in the \u0060authorization\u0060 field. The body of the request must be\n\u0060multipart/form-data\u0060, and the \u0060accept\u0060 header should be set to one of the following:\n - \u0060image/*\u0060 to receive the image in the format specified by the \u0060output_format\u0060 parameter.\n - \u0060application/json\u0060 to receive the image encoded as base64 in a JSON response.\n\nThe body of the request should include:\n- \u0060init_image\u0060\n- \u0060style_image\u0060\n\nThe body may optionally include:\n- \u0060prompt\u0060\n- \u0060negative_prompt\u0060\n- \u0060style_strength\u0060\n- \u0060composition_fidelity\u0060\n- \u0060change_strength\u0060\n- \u0060seed\u0060\n- \u0060output_format\u0060\n\n\u003E **Note:** for more details about these parameters please see the request schema below.\n\n### Output\nThe resolution of the generated image will be 1MP, with the same aspect ratio as the \u0060init_image\u0060.\n\n### Credits\nFlat rate of 8 credits per successful generation. You will not be charged for failed generations.", "Language": "http", - "Code": "### Style Transfer\nPOST {{host}}/v2beta/stable-image/control/style-transfer\nAuthorization: Bearer {{token}}\ncontent-type: {{content-type}}\naccept: image/*\nstability-client-id: {{stability-client-id}}\nstability-client-user-id: {{stability-client-user-id}}\nstability-client-version: {{stability-client-version}}\nContent-Type: multipart/form-data\nAccept: application/json, application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n\n## Responses\n# 200\n# Description: Generation was successful.\n# Content-Type: application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n# 400\n# Description: Invalid parameter(s), see the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 403\n# Description: Your request was flagged by our content moderation system.\n# Content-Type: application/json\n# 413\n# Description: Your request was larger than 10MiB.\n# Content-Type: application/json\n# 422\n# Description: Your request was well-formed, but rejected. See the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 429\n# Description: You have made more than 150 requests in 10 seconds.\n# Content-Type: application/json\n# 500\n# Description: An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).\n# Content-Type: application/json", + "Code": "### Style Transfer\nPOST {{host}}/v2beta/stable-image/control/style-transfer\nAuthorization: Bearer {{token}}\ncontent-type: {{content-type}}\naccept: image/*\nstability-client-id: {{stability-client-id}}\nstability-client-user-id: {{stability-client-user-id}}\nstability-client-version: {{stability-client-version}}\nContent-Type: multipart/form-data; boundary=AutoSDKBoundary\nAccept: application/json, application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022init_image\u0022; filename=\u0022init_image.bin\u0022\nContent-Type: application/octet-stream\n\n\u003C ./init_image.bin\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022style_image\u0022; filename=\u0022style_image.bin\u0022\nContent-Type: application/octet-stream\n\n\u003C ./style_image.bin\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022prompt\u0022\n\nstring\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022negative_prompt\u0022\n\nstring\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022seed\u0022\n\n0\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022style_strength\u0022\n\n1\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022composition_fidelity\u0022\n\n0.9\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022change_strength\u0022\n\n0.9\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022output_format\u0022\n\npng\n--AutoSDKBoundary--\n\n## Responses\n# 200\n# Description: Generation was successful.\n# Content-Type: application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n# 400\n# Description: Invalid parameter(s), see the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 403\n# Description: Your request was flagged by our content moderation system.\n# Content-Type: application/json\n# 413\n# Description: Your request was larger than 10MiB.\n# Content-Type: application/json\n# 422\n# Description: Your request was well-formed, but rejected. See the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 429\n# Description: You have made more than 150 requests in 10 seconds.\n# Content-Type: application/json\n# 500\n# Description: An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).\n# Content-Type: application/json", "Format": "http", "OperationId": "createStableImageControlStyleTransfer", "Setup": null @@ -72,7 +72,7 @@ "Slug": "erase", "Description": "The Erase service removes unwanted objects, such as blemishes on portraits or items on desks, using image masks.\n\nThe mask is provided in one of two ways:\n 1. Explicitly passing in a separate image via the \u0060mask\u0060 parameter\n 2. Derived from the alpha channel of the \u0060image\u0060 parameter.\n\n### Try it out\nGrab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)\n\n### How to use\n\nPlease invoke this endpoint with a \u0060POST\u0060 request.\n\nThe headers of the request must include an API key in the \u0060authorization\u0060 field. The body of the request must be\n\u0060multipart/form-data\u0060, and the \u0060accept\u0060 header should be set to one of the following:\n - \u0060image/*\u0060 to receive the image in the format specified by the \u0060output_format\u0060 parameter.\n - \u0060application/json\u0060 to receive the image encoded as base64 in a JSON response.\n\nThe body of the request must include:\n- \u0060image\u0060\n\nOptionally, the body of the request may also include:\n- \u0060mask\u0060\n- \u0060seed\u0060\n- \u0060output_format\u0060\n\n\u003E **Note:** for more details about these parameters please see the request schema below.\n\n### Output\nThe resolution of the generated image will be 4 megapixels.\n\n### Credits\nFlat rate of 5 credits per successful generation. You will not be charged for failed generations.", "Language": "http", - "Code": "### Erase\nPOST {{host}}/v2beta/stable-image/edit/erase\nAuthorization: Bearer {{token}}\ncontent-type: {{content-type}}\naccept: image/*\nstability-client-id: {{stability-client-id}}\nstability-client-user-id: {{stability-client-user-id}}\nstability-client-version: {{stability-client-version}}\nContent-Type: multipart/form-data\nAccept: application/json, application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n\n## Responses\n# 200\n# Description: Erase was successful.\n# Content-Type: application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n# 400\n# Description: Invalid parameter(s), see the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 403\n# Description: Your request was flagged by our content moderation system.\n# Content-Type: application/json\n# 413\n# Description: Your request was larger than 10MiB.\n# Content-Type: application/json\n# 429\n# Description: You have made more than 150 requests in 10 seconds.\n# Content-Type: application/json\n# 500\n# Description: An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).\n# Content-Type: application/json", + "Code": "### Erase\nPOST {{host}}/v2beta/stable-image/edit/erase\nAuthorization: Bearer {{token}}\ncontent-type: {{content-type}}\naccept: image/*\nstability-client-id: {{stability-client-id}}\nstability-client-user-id: {{stability-client-user-id}}\nstability-client-version: {{stability-client-version}}\nContent-Type: multipart/form-data; boundary=AutoSDKBoundary\nAccept: application/json, application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022image\u0022; filename=\u0022image.bin\u0022\nContent-Type: application/octet-stream\n\n\u003C ./image.bin\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022mask\u0022; filename=\u0022mask.bin\u0022\nContent-Type: application/octet-stream\n\n\u003C ./mask.bin\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022grow_mask\u0022\n\n5\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022seed\u0022\n\n0\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022output_format\u0022\n\npng\n--AutoSDKBoundary--\n\n## Responses\n# 200\n# Description: Erase was successful.\n# Content-Type: application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n# 400\n# Description: Invalid parameter(s), see the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 403\n# Description: Your request was flagged by our content moderation system.\n# Content-Type: application/json\n# 413\n# Description: Your request was larger than 10MiB.\n# Content-Type: application/json\n# 429\n# Description: You have made more than 150 requests in 10 seconds.\n# Content-Type: application/json\n# 500\n# Description: An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).\n# Content-Type: application/json", "Format": "http", "OperationId": "createStableImageEditErase", "Setup": null @@ -83,7 +83,7 @@ "Slug": "inpaint", "Description": "Intelligently modify images by filling in or replacing specified areas with new content based\non the content of a \u0022mask\u0022 image.\n\nThe \u0022mask\u0022 is provided in one of two ways:\n 1. Explicitly passing in a separate image via the \u0060mask\u0060 parameter\n 2. Derived from the alpha channel of the \u0060image\u0060 parameter.\n\n### Try it out\nGrab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)\n\n### How to use\n\nPlease invoke this endpoint with a \u0060POST\u0060 request.\n\nThe headers of the request must include an API key in the \u0060authorization\u0060 field. The body of the request must be\n\u0060multipart/form-data\u0060, and the \u0060accept\u0060 header should be set to one of the following:\n - \u0060image/*\u0060 to receive the image in the format specified by the \u0060output_format\u0060 parameter.\n - \u0060application/json\u0060 to receive the image encoded as base64 in a JSON response.\n\nThe body of the request must include:\n- \u0060image\u0060\n- \u0060prompt\u0060\n\nOptionally, the body of the request may also include:\n- \u0060mask\u0060\n- \u0060negative_prompt\u0060\n- \u0060seed\u0060\n- \u0060output_format\u0060\n- \u0060style_preset\u0060\n\n\u003E **Note:** for more details about these parameters please see the request schema below.\n\n### Output\nThe resolution of the generated image will be 4 megapixels.\n\n### Credits\nFlat rate of 5 credits per successful generation. You will not be charged for failed generations.", "Language": "http", - "Code": "### Inpaint\nPOST {{host}}/v2beta/stable-image/edit/inpaint\nAuthorization: Bearer {{token}}\ncontent-type: {{content-type}}\naccept: image/*\nstability-client-id: {{stability-client-id}}\nstability-client-user-id: {{stability-client-user-id}}\nstability-client-version: {{stability-client-version}}\nContent-Type: multipart/form-data\nAccept: application/json, application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n\n## Responses\n# 200\n# Description: Inpainting was successful.\n# Content-Type: application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n# 400\n# Description: Invalid parameter(s), see the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 403\n# Description: Your request was flagged by our content moderation system.\n# Content-Type: application/json\n# 413\n# Description: Your request was larger than 10MiB.\n# Content-Type: application/json\n# 422\n# Description: Your request was well-formed, but rejected. See the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 429\n# Description: You have made more than 150 requests in 10 seconds.\n# Content-Type: application/json\n# 500\n# Description: An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).\n# Content-Type: application/json", + "Code": "### Inpaint\nPOST {{host}}/v2beta/stable-image/edit/inpaint\nAuthorization: Bearer {{token}}\ncontent-type: {{content-type}}\naccept: image/*\nstability-client-id: {{stability-client-id}}\nstability-client-user-id: {{stability-client-user-id}}\nstability-client-version: {{stability-client-version}}\nContent-Type: multipart/form-data; boundary=AutoSDKBoundary\nAccept: application/json, application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022image\u0022; filename=\u0022image.bin\u0022\nContent-Type: application/octet-stream\n\n\u003C ./image.bin\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022prompt\u0022\n\nstring\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022negative_prompt\u0022\n\nstring\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022mask\u0022; filename=\u0022mask.bin\u0022\nContent-Type: application/octet-stream\n\n\u003C ./mask.bin\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022grow_mask\u0022\n\n5\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022seed\u0022\n\n0\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022output_format\u0022\n\npng\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022style_preset\u0022\n\nenhance\n--AutoSDKBoundary--\n\n## Responses\n# 200\n# Description: Inpainting was successful.\n# Content-Type: application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n# 400\n# Description: Invalid parameter(s), see the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 403\n# Description: Your request was flagged by our content moderation system.\n# Content-Type: application/json\n# 413\n# Description: Your request was larger than 10MiB.\n# Content-Type: application/json\n# 422\n# Description: Your request was well-formed, but rejected. See the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 429\n# Description: You have made more than 150 requests in 10 seconds.\n# Content-Type: application/json\n# 500\n# Description: An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).\n# Content-Type: application/json", "Format": "http", "OperationId": "createStableImageEditInpaint", "Setup": null @@ -94,7 +94,7 @@ "Slug": "outpaint", "Description": "The Outpaint service inserts additional content in an image to fill in the space in any direction.\nCompared to other automated or manual attempts to expand the content in an image, the Outpaint service\nshould minimize artifacts and signs that the original image has been edited.\n\n### Try it out\nGrab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=bZ2yK7VQSgLw)\n\n### How to use\n\nPlease invoke this endpoint with a POST request.\n\nThe headers of the request must include an API key in the \u0060authorization\u0060 field. The body of the request must be\n\u0060multipart/form-data\u0060, and the \u0060accept\u0060 header should be set to one of the following:\n - \u0060image/*\u0060 to receive the image in the format specified by the \u0060output_format\u0060 parameter.\n - \u0060application/json\u0060 to receive the image encoded as base64 in a JSON response.\n\nThe body of the request must include:\n- \u0060image\u0060\n\nAlong with _at least one_ outpaint direction:\n- \u0060left\u0060\n- \u0060right\u0060\n- \u0060up\u0060\n- \u0060down\u0060\n\n\u003E **Note:** for best quality use outpaint direction values smaller or equal to your source image dimensions.\n\nEach of these parameters should be set to a number between 0 and 2000, representing the number of pixels to outpaint in that direction.\n\nOptionally, the body of the request may also include:\n- \u0060prompt\u0060\n- \u0060seed\u0060\n- \u0060output_format\u0060\n- \u0060creativity\u0060\n- \u0060style_preset\u0060\n\n\u003E **Note:** for more details about these parameters please see the request schema below.\n\n### Credits\nFlat rate of 4 credits per successful generation. You will not be charged for failed generations.", "Language": "http", - "Code": "### Outpaint\nPOST {{host}}/v2beta/stable-image/edit/outpaint\nAuthorization: Bearer {{token}}\ncontent-type: {{content-type}}\naccept: image/*\nstability-client-id: {{stability-client-id}}\nstability-client-user-id: {{stability-client-user-id}}\nstability-client-version: {{stability-client-version}}\nContent-Type: multipart/form-data\nAccept: application/json, application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n\n## Responses\n# 200\n# Description: Outpainting was successful.\n# Content-Type: application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n# 400\n# Description: Invalid parameter(s), see the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 403\n# Description: Your request was flagged by our content moderation system.\n# Content-Type: application/json\n# 413\n# Description: Your request was larger than 10MiB.\n# Content-Type: application/json\n# 422\n# Description: Your request was well-formed, but rejected. See the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 429\n# Description: You have made more than 150 requests in 10 seconds.\n# Content-Type: application/json\n# 500\n# Description: An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).\n# Content-Type: application/json", + "Code": "### Outpaint\nPOST {{host}}/v2beta/stable-image/edit/outpaint\nAuthorization: Bearer {{token}}\ncontent-type: {{content-type}}\naccept: image/*\nstability-client-id: {{stability-client-id}}\nstability-client-user-id: {{stability-client-user-id}}\nstability-client-version: {{stability-client-version}}\nContent-Type: multipart/form-data; boundary=AutoSDKBoundary\nAccept: application/json, application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022image\u0022; filename=\u0022image.bin\u0022\nContent-Type: application/octet-stream\n\n\u003C ./image.bin\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022left\u0022\n\n0\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022right\u0022\n\n0\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022up\u0022\n\n0\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022down\u0022\n\n0\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022creativity\u0022\n\nstring\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022prompt\u0022\n\nstring\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022seed\u0022\n\n0\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022output_format\u0022\n\npng\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022style_preset\u0022\n\nenhance\n--AutoSDKBoundary--\n\n## Responses\n# 200\n# Description: Outpainting was successful.\n# Content-Type: application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n# 400\n# Description: Invalid parameter(s), see the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 403\n# Description: Your request was flagged by our content moderation system.\n# Content-Type: application/json\n# 413\n# Description: Your request was larger than 10MiB.\n# Content-Type: application/json\n# 422\n# Description: Your request was well-formed, but rejected. See the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 429\n# Description: You have made more than 150 requests in 10 seconds.\n# Content-Type: application/json\n# 500\n# Description: An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).\n# Content-Type: application/json", "Format": "http", "OperationId": "createStableImageEditOutpaint", "Setup": null @@ -105,7 +105,7 @@ "Slug": "remove-background", "Description": "The Remove Background service accurately segments the foreground from an image and implements \nand removes the background.\n\n### Try it out\nGrab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=VHofb3LAVmqi)\n\n\n### How to use\n\nPlease invoke this endpoint with a \u0060POST\u0060 request.\n\nThe headers of the request must include an API key in the \u0060authorization\u0060 field. The body of the request must be\n\u0060multipart/form-data\u0060, and the \u0060accept\u0060 header should be set to one of the following:\n - \u0060image/*\u0060 to receive the image in the format specified by the \u0060output_format\u0060 parameter.\n - \u0060application/json\u0060 to receive the image encoded as base64 in a JSON response.\n \nThe body of the request must include:\n- \u0060image\u0060\n\nOptionally, the body of the request may also include:\n- \u0060output_format\u0060\n\n\u003E **Note:** for more details about these parameters please see the request schema below.\n\n### Credits\nFlat rate of 5 credits per successful generation. You will not be charged for failed generations.", "Language": "http", - "Code": "### Remove Background\nPOST {{host}}/v2beta/stable-image/edit/remove-background\nAuthorization: Bearer {{token}}\ncontent-type: {{content-type}}\naccept: image/*\nstability-client-id: {{stability-client-id}}\nstability-client-user-id: {{stability-client-user-id}}\nstability-client-version: {{stability-client-version}}\nContent-Type: multipart/form-data\nAccept: application/json, application/json; type=image/png, application/json; type=image/webp, image/png, image/webp\n\n## Responses\n# 200\n# Description: Background successfully removed.\n# Content-Type: application/json; type=image/png, application/json; type=image/webp, image/png, image/webp\n# 400\n# Description: Invalid parameter(s), see the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 403\n# Description: Your request was flagged by our content moderation system.\n# Content-Type: application/json\n# 413\n# Description: Your request was larger than 10MiB.\n# Content-Type: application/json\n# 429\n# Description: You have made more than 150 requests in 10 seconds.\n# Content-Type: application/json\n# 500\n# Description: An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).\n# Content-Type: application/json", + "Code": "### Remove Background\nPOST {{host}}/v2beta/stable-image/edit/remove-background\nAuthorization: Bearer {{token}}\ncontent-type: {{content-type}}\naccept: image/*\nstability-client-id: {{stability-client-id}}\nstability-client-user-id: {{stability-client-user-id}}\nstability-client-version: {{stability-client-version}}\nContent-Type: multipart/form-data; boundary=AutoSDKBoundary\nAccept: application/json, application/json; type=image/png, application/json; type=image/webp, image/png, image/webp\n\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022image\u0022; filename=\u0022image.bin\u0022\nContent-Type: application/octet-stream\n\n\u003C ./image.bin\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022output_format\u0022\n\npng\n--AutoSDKBoundary--\n\n## Responses\n# 200\n# Description: Background successfully removed.\n# Content-Type: application/json; type=image/png, application/json; type=image/webp, image/png, image/webp\n# 400\n# Description: Invalid parameter(s), see the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 403\n# Description: Your request was flagged by our content moderation system.\n# Content-Type: application/json\n# 413\n# Description: Your request was larger than 10MiB.\n# Content-Type: application/json\n# 429\n# Description: You have made more than 150 requests in 10 seconds.\n# Content-Type: application/json\n# 500\n# Description: An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).\n# Content-Type: application/json", "Format": "http", "OperationId": "createStableImageEditRemoveBackground", "Setup": null @@ -116,7 +116,7 @@ "Slug": "replace-background-and-relight-async", "Description": "The Replace Background and Relight edit service lets users swap backgrounds with\nAI-generated or uploaded images while adjusting lighting to match the subject. This\nnew API provides a streamlined image editing solution and can serve e-commerce, real\nestate, photography, and creative projects.\n\nSome of the things you can do include:\n - Background Replacement: Remove existing background and add new ones.\n - AI Background Generation: Create new backgrounds using AI generated images based on prompts.\n - Relighting: Adjust lighting in images that are under or overexposed.\n - Flexible Inputs: Use your own background image or generate one.\n - Lighting Adjustments: Modify light reference, direction, and strength.\n\n### Try it out\nGrab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=mtgSh4Stj3l)\n\n### How to use\nPlease invoke this endpoint with a \u0060POST\u0060 request.\n\nThe headers of the request must include an API key in the \u0060authorization\u0060 field. The body of the request must be\n\u0060multipart/form-data\u0060.\n\nThe body of the request should include:\n- \u0060subject_image\u0060\n- \u0060background_prompt\u0060 and/or \u0060background_reference\u0060\n\nThe body may optionally include:\n- \u0060light_reference\u0060 or \u0060light_source_direction\u0060\n- \u0060light_source_strength\u0060 (requires \u0060light_reference\u0060 or \u0060light_source_direction\u0060)\n- \u0060foreground_prompt\u0060\n- \u0060negative_prompt\u0060\n- \u0060preserve_original_subject\u0060\n- \u0060original_background_depth\u0060\n- \u0060keep_original_background\u0060\n- \u0060light_source_strength\u0060\n- \u0060seed\u0060\n- \u0060output_format\u0060\n\n\u003E **Note:** for more details about these parameters please see the request schema below.\n\n### Results\nAfter invoking this endpoint with the required parameters, use the \u0060id\u0060 in the response to poll for results at the\n[results/{id} endpoint](#tag/Results/paths/~1v2beta~1results~1%7Bid%7D/get). Rate-limiting or other errors may occur if you poll more than once every 10 seconds.\n\n### Credits\nFlat rate of 8 credits per successful generation. You will not be charged for failed generations.", "Language": "http", - "Code": "### Replace Background and Relight (async)\nPOST {{host}}/v2beta/stable-image/edit/replace-background-and-relight\nAuthorization: Bearer {{token}}\ncontent-type: {{content-type}}\nstability-client-id: {{stability-client-id}}\nstability-client-user-id: {{stability-client-user-id}}\nstability-client-version: {{stability-client-version}}\nContent-Type: multipart/form-data\nAccept: application/json\n\n## Responses\n# 200\n# Description: Replace Background and Relight was started.\n# Content-Type: application/json\n# 400\n# Description: Invalid parameter(s), see the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 403\n# Description: Your request was flagged by our content moderation system.\n# Content-Type: application/json\n# 413\n# Description: Your request was larger than 10MiB.\n# Content-Type: application/json\n# 422\n# Description: Your request was well-formed, but rejected. See the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 429\n# Description: You have made more than 150 requests in 10 seconds.\n# Content-Type: application/json\n# 500\n# Description: An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).\n# Content-Type: application/json", + "Code": "### Replace Background and Relight (async)\nPOST {{host}}/v2beta/stable-image/edit/replace-background-and-relight\nAuthorization: Bearer {{token}}\ncontent-type: {{content-type}}\nstability-client-id: {{stability-client-id}}\nstability-client-user-id: {{stability-client-user-id}}\nstability-client-version: {{stability-client-version}}\nContent-Type: multipart/form-data; boundary=AutoSDKBoundary\nAccept: application/json\n\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022subject_image\u0022; filename=\u0022subject_image.bin\u0022\nContent-Type: application/octet-stream\n\n\u003C ./subject_image.bin\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022background_reference\u0022; filename=\u0022background_reference.bin\u0022\nContent-Type: application/octet-stream\n\n\u003C ./background_reference.bin\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022background_prompt\u0022\n\nstring\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022foreground_prompt\u0022\n\nstring\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022negative_prompt\u0022\n\nstring\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022preserve_original_subject\u0022\n\n0.6\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022original_background_depth\u0022\n\n0.5\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022keep_original_background\u0022\n\nfalse\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022light_source_direction\u0022\n\nleft\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022light_reference\u0022; filename=\u0022light_reference.bin\u0022\nContent-Type: application/octet-stream\n\n\u003C ./light_reference.bin\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022light_source_strength\u0022\n\n0.3\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022seed\u0022\n\n0\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022output_format\u0022\n\npng\n--AutoSDKBoundary--\n\n## Responses\n# 200\n# Description: Replace Background and Relight was started.\n# Content-Type: application/json\n# 400\n# Description: Invalid parameter(s), see the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 403\n# Description: Your request was flagged by our content moderation system.\n# Content-Type: application/json\n# 413\n# Description: Your request was larger than 10MiB.\n# Content-Type: application/json\n# 422\n# Description: Your request was well-formed, but rejected. See the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 429\n# Description: You have made more than 150 requests in 10 seconds.\n# Content-Type: application/json\n# 500\n# Description: An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).\n# Content-Type: application/json", "Format": "http", "OperationId": "createStableImageEditReplaceBackgroundAndRelight", "Setup": null @@ -127,7 +127,7 @@ "Slug": "search-and-recolor", "Description": "The Search and Recolor service provides the ability to change the color of a specific object in an image using a prompt.\nThis service is a specific version of inpainting that does not require a mask. The Search and Recolor\nservice will automatically segment the object and recolor it using the colors requested in the prompt.\n\n### Try it out\nGrab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=mtgSh4Stj3l)\n\n### How to use\nPlease invoke this endpoint with a \u0060POST\u0060 request.\n\nThe headers of the request must include an API key in the \u0060authorization\u0060 field. The body of the request must be\n\u0060multipart/form-data\u0060, and the \u0060accept\u0060 header should be set to one of the following:\n - \u0060image/*\u0060 to receive the image in the format specified by the \u0060output_format\u0060 parameter.\n - \u0060application/json\u0060 to receive the image encoded as base64 in a JSON response.\n\nThe body of the request should include:\n- \u0060image\u0060\n- \u0060prompt\u0060\n- \u0060select_prompt\u0060\n\nThe body may optionally include:\n- \u0060grow_mask\u0060\n- \u0060seed\u0060\n- \u0060negative_prompt\u0060\n- \u0060output_format\u0060\n- \u0060style_preset\u0060\n\n\u003E **Note:** for more details about these parameters please see the request schema below.\n\n### Output\nThe resolution of the generated image will match the resolution of the input image.\n\n### Credits\nFlat rate of 5 credits per successful generation. You will not be charged for failed generations.", "Language": "http", - "Code": "### Search and Recolor\nPOST {{host}}/v2beta/stable-image/edit/search-and-recolor\nAuthorization: Bearer {{token}}\ncontent-type: {{content-type}}\naccept: image/*\nstability-client-id: {{stability-client-id}}\nstability-client-user-id: {{stability-client-user-id}}\nstability-client-version: {{stability-client-version}}\nContent-Type: multipart/form-data\nAccept: application/json, application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n\n## Responses\n# 200\n# Description: Search-and-Recolor was successful.\n# Content-Type: application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n# 400\n# Description: Invalid parameter(s), see the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 403\n# Description: Your request was flagged by our content moderation system.\n# Content-Type: application/json\n# 413\n# Description: Your request was larger than 10MiB.\n# Content-Type: application/json\n# 422\n# Description: Your request was well-formed, but rejected. See the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 429\n# Description: You have made more than 150 requests in 10 seconds.\n# Content-Type: application/json\n# 500\n# Description: An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).\n# Content-Type: application/json", + "Code": "### Search and Recolor\nPOST {{host}}/v2beta/stable-image/edit/search-and-recolor\nAuthorization: Bearer {{token}}\ncontent-type: {{content-type}}\naccept: image/*\nstability-client-id: {{stability-client-id}}\nstability-client-user-id: {{stability-client-user-id}}\nstability-client-version: {{stability-client-version}}\nContent-Type: multipart/form-data; boundary=AutoSDKBoundary\nAccept: application/json, application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022image\u0022; filename=\u0022image.bin\u0022\nContent-Type: application/octet-stream\n\n\u003C ./image.bin\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022prompt\u0022\n\nstring\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022select_prompt\u0022\n\nglasses\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022negative_prompt\u0022\n\nstring\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022grow_mask\u0022\n\n3\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022seed\u0022\n\n0\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022output_format\u0022\n\npng\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022style_preset\u0022\n\nenhance\n--AutoSDKBoundary--\n\n## Responses\n# 200\n# Description: Search-and-Recolor was successful.\n# Content-Type: application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n# 400\n# Description: Invalid parameter(s), see the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 403\n# Description: Your request was flagged by our content moderation system.\n# Content-Type: application/json\n# 413\n# Description: Your request was larger than 10MiB.\n# Content-Type: application/json\n# 422\n# Description: Your request was well-formed, but rejected. See the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 429\n# Description: You have made more than 150 requests in 10 seconds.\n# Content-Type: application/json\n# 500\n# Description: An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).\n# Content-Type: application/json", "Format": "http", "OperationId": "createStableImageEditSearchAndRecolor", "Setup": null @@ -138,7 +138,7 @@ "Slug": "search-and-replace", "Description": "The Search and Replace service is a specific version of inpainting that does not require a mask.\nInstead, users can leverage a \u0060search_prompt\u0060 to identify an object in simple language to be replaced.\nThe service will automatically segment the object and replace it with the object requested in the prompt.\n\n### Try it out\nGrab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=0lDpGa2jAmAs)\n\n### How to use\nPlease invoke this endpoint with a \u0060POST\u0060 request.\n\nThe headers of the request must include an API key in the \u0060authorization\u0060 field. The body of the request must be\n\u0060multipart/form-data\u0060, and the \u0060accept\u0060 header should be set to one of the following:\n - \u0060image/*\u0060 to receive the image in the format specified by the \u0060output_format\u0060 parameter.\n - \u0060application/json\u0060 to receive the image encoded as base64 in a JSON response.\n\nThe body of the request should include:\n- \u0060image\u0060\n- \u0060prompt\u0060\n- \u0060search_prompt\u0060\n\nThe body may optionally include:\n- \u0060seed\u0060\n- \u0060negative_prompt\u0060\n- \u0060output_format\u0060\n- \u0060style_preset\u0060\n\n\u003E **Note:** for more details about these parameters please see the request schema below.\n\n### Output\nThe resolution of the generated image will be 4 megapixels.\n\n### Credits\nFlat rate of 5 credits per successful generation. You will not be charged for failed generations.", "Language": "http", - "Code": "### Search and Replace\nPOST {{host}}/v2beta/stable-image/edit/search-and-replace\nAuthorization: Bearer {{token}}\ncontent-type: {{content-type}}\naccept: image/*\nstability-client-id: {{stability-client-id}}\nstability-client-user-id: {{stability-client-user-id}}\nstability-client-version: {{stability-client-version}}\nContent-Type: multipart/form-data\nAccept: application/json, application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n\n## Responses\n# 200\n# Description: Search-and-Replace was successful.\n# Content-Type: application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n# 400\n# Description: Invalid parameter(s), see the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 403\n# Description: Your request was flagged by our content moderation system.\n# Content-Type: application/json\n# 413\n# Description: Your request was larger than 10MiB.\n# Content-Type: application/json\n# 422\n# Description: Your request was well-formed, but rejected. See the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 429\n# Description: You have made more than 150 requests in 10 seconds.\n# Content-Type: application/json\n# 500\n# Description: An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).\n# Content-Type: application/json", + "Code": "### Search and Replace\nPOST {{host}}/v2beta/stable-image/edit/search-and-replace\nAuthorization: Bearer {{token}}\ncontent-type: {{content-type}}\naccept: image/*\nstability-client-id: {{stability-client-id}}\nstability-client-user-id: {{stability-client-user-id}}\nstability-client-version: {{stability-client-version}}\nContent-Type: multipart/form-data; boundary=AutoSDKBoundary\nAccept: application/json, application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022image\u0022; filename=\u0022image.bin\u0022\nContent-Type: application/octet-stream\n\n\u003C ./image.bin\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022prompt\u0022\n\nstring\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022search_prompt\u0022\n\nglasses\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022negative_prompt\u0022\n\nstring\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022grow_mask\u0022\n\n3\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022seed\u0022\n\n0\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022output_format\u0022\n\npng\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022style_preset\u0022\n\nenhance\n--AutoSDKBoundary--\n\n## Responses\n# 200\n# Description: Search-and-Replace was successful.\n# Content-Type: application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n# 400\n# Description: Invalid parameter(s), see the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 403\n# Description: Your request was flagged by our content moderation system.\n# Content-Type: application/json\n# 413\n# Description: Your request was larger than 10MiB.\n# Content-Type: application/json\n# 422\n# Description: Your request was well-formed, but rejected. See the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 429\n# Description: You have made more than 150 requests in 10 seconds.\n# Content-Type: application/json\n# 500\n# Description: An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).\n# Content-Type: application/json", "Format": "http", "OperationId": "createStableImageEditSearchAndReplace", "Setup": null @@ -149,7 +149,7 @@ "Slug": "stable-image-core", "Description": "Our primary service for text-to-image generation, Stable Image Core represents the best quality achievable at high\nspeed. No prompt engineering is required! Try asking for a style, a scene, or a character, and see what you get.\n\n### Try it out\nGrab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=yXhs626oZdr1)\n\n### How to use\nPlease invoke this endpoint with a \u0060POST\u0060 request.\n\nThe headers of the request must include an API key in the \u0060authorization\u0060 field. The body of the request must be\n\u0060multipart/form-data\u0060, and the \u0060accept\u0060 header should be set to one of the following:\n - \u0060image/*\u0060 to receive the image in the format specified by the \u0060output_format\u0060 parameter.\n - \u0060application/json\u0060 to receive the image encoded as base64 in a JSON response.\n\nThe body of the request should include:\n- \u0060prompt\u0060\n\nThe body may optionally include:\n- \u0060aspect_ratio\u0060\n- \u0060negative_prompt\u0060\n- \u0060seed\u0060\n- \u0060style_preset\u0060\n- \u0060output_format\u0060\n\n\u003E **Note:** for more details about these parameters please see the request schema below.\n\n### Output\nThe resolution of the generated image will be 1.5 megapixels.\n\n### Credits\nFlat rate of 3 credits per successful generation. You will not be charged for failed generations.", "Language": "http", - "Code": "### Stable Image Core\nPOST {{host}}/v2beta/stable-image/generate/core\nAuthorization: Bearer {{token}}\ncontent-type: {{content-type}}\naccept: image/*\nstability-client-id: {{stability-client-id}}\nstability-client-user-id: {{stability-client-user-id}}\nstability-client-version: {{stability-client-version}}\nContent-Type: multipart/form-data\nAccept: application/json, application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n\n## Responses\n# 200\n# Description: Generation was successful.\n# Content-Type: application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n# 400\n# Description: Invalid parameter(s), see the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 403\n# Description: Your request was flagged by our content moderation system.\n# Content-Type: application/json\n# 422\n# Description: Your request was well-formed, but rejected. See the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 429\n# Description: You have made more than 150 requests in 10 seconds.\n# Content-Type: application/json\n# 500\n# Description: An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).\n# Content-Type: application/json", + "Code": "### Stable Image Core\nPOST {{host}}/v2beta/stable-image/generate/core\nAuthorization: Bearer {{token}}\ncontent-type: {{content-type}}\naccept: image/*\nstability-client-id: {{stability-client-id}}\nstability-client-user-id: {{stability-client-user-id}}\nstability-client-version: {{stability-client-version}}\nContent-Type: multipart/form-data; boundary=AutoSDKBoundary\nAccept: application/json, application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022prompt\u0022\n\nstring\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022aspect_ratio\u0022\n\n1:1\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022negative_prompt\u0022\n\nstring\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022seed\u0022\n\n0\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022style_preset\u0022\n\nenhance\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022output_format\u0022\n\npng\n--AutoSDKBoundary--\n\n## Responses\n# 200\n# Description: Generation was successful.\n# Content-Type: application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n# 400\n# Description: Invalid parameter(s), see the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 403\n# Description: Your request was flagged by our content moderation system.\n# Content-Type: application/json\n# 422\n# Description: Your request was well-formed, but rejected. See the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 429\n# Description: You have made more than 150 requests in 10 seconds.\n# Content-Type: application/json\n# 500\n# Description: An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).\n# Content-Type: application/json", "Format": "http", "OperationId": "createStableImageGenerateCore", "Setup": null @@ -160,7 +160,7 @@ "Slug": "stable-diffusion-3-5", "Description": "Generate using Stable Diffusion 3.5 models, Stability AI latest base model:\n\n- **Stable Diffusion 3.5 Large**: At 8 billion parameters, with superior quality and\n prompt adherence, this base model is the most powerful in the Stable Diffusion\n family. This model is ideal for professional use cases at 1 megapixel resolution.\n\n- **Stable Diffusion 3.5 Large Turbo**: A distilled version of Stable Diffusion 3.5 Large.\n SD3.5 Large Turbo generates high-quality images with exceptional prompt adherence\n in just 4 steps, making it considerably faster than Stable Diffusion 3.5 Large.\n\n- **Stable Diffusion 3.5 Medium**: With 2.5 billion parameters, the model delivers an\n optimal balance between prompt accuracy and image quality, making it an efficient\n choice for fast high-performance image generation.\n\n- **Stable Diffusion 3.5 Flash**: A distilled version of Stable Diffusion 3.5 Medium. \n SD3.5 Flash generates high-quality images with a 4 step process instead of 40, making \n it faster than Stable Diffusion 3.5 Medium.\n\nRead more about the model capabilities [here](https://stability.ai/news/introducing-stable-diffusion-3-5).\n\nAs of April 17, 2025, we have deprecated the Stable Diffusion 3.0 APIs and will be automatically\nre-routing calls to Stable Diffusion 3.0 models to Stable Diffusion 3.5 APIs at no extra cost.\nYou can read more in the [release notes](/docs/release-notes#api-deprecation-notice).\n\n### Try it out\nGrab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/SD3_API.ipynb)\n\n### How to use\nPlease invoke this endpoint with a \u0060POST\u0060 request.\n\nThe headers of the request must include an API key in the \u0060authorization\u0060 field. The body of the request must be\n\u0060multipart/form-data\u0060. The accept header should be set to one of the following:\n- \u0060image/*\u0060 to receive the image in the format specified by the \u0060output_format\u0060 parameter.\n- \u0060application/json\u0060 to receive the image encoded as base64 in a JSON response.\n\n#### **Generating with a prompt**\nCommonly referred to as **text-to-image**, this mode generates an image from text alone. While the only required\nparameter is the \u0060prompt\u0060, it also supports an \u0060aspect_ratio\u0060 parameter which can be used to control the\naspect ratio of the generated image.\n\n#### **Generating with a prompt *and* an image**\nCommonly referred to as **image-to-image**, this mode also generates an image from text but uses an existing image as the\nstarting point. The required parameters are:\n- \u0060prompt\u0060 - text to generate the image from\n- \u0060image\u0060 - the image to use as the starting point for the generation\n- \u0060strength\u0060 - controls how much influence the \u0060image\u0060 parameter has on the output image\n- \u0060mode\u0060 - must be set to \u0060image-to-image\u0060\n\n\u003E **Note:** maximum request size is 10MiB.\n\n#### **Optional Parameters:**\nBoth modes support the following optional parameters:\n- \u0060model\u0060 - the model to use (SD 3.5 Large, SD 3.5 Large Turbo, SD 3.5 Medium, SD 3.5 Flash)\n- \u0060output_format\u0060 - the format of the output image\n- \u0060seed\u0060 - the randomness seed to use for the generation\n- \u0060negative_prompt\u0060 - keywords of what you **do not** wish to see in the output image\n- \u0060cfg_scale\u0060 - controls how strictly the diffusion process adheres to the prompt text\n- \u0060style_preset\u0060 - guides the image model towards a particular style\n\n\u003E **Note:** for more details about these parameters please see the request schema below.\n\n### Output\nThe resolution of the generated image will be 1MP. The default resolution is 1024x1024.\n\n### Credits\n- **SD 3.5 Large**: Flat rate of 6.5 credits per successful generation.\n- **SD 3.5 Large Turbo**: Flat rate of 4 credits per successful generation.\n- **SD 3.5 Medium**: Flat rate of 3.5 credits per successful generation.\n- **SD 3.5 Flash**: Flat rate of 2.5 credits per successful generation.\n\nAs always, you will not be charged for failed generations.", "Language": "http", - "Code": "### Stable Diffusion 3.5\nPOST {{host}}/v2beta/stable-image/generate/sd3\nAuthorization: Bearer {{token}}\ncontent-type: {{content-type}}\naccept: image/*\nstability-client-id: {{stability-client-id}}\nstability-client-user-id: {{stability-client-user-id}}\nstability-client-version: {{stability-client-version}}\nContent-Type: multipart/form-data\nAccept: application/json, application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n\n## Responses\n# 200\n# Description: Generation was successful.\n# Content-Type: application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n# 400\n# Description: Invalid parameter(s), see the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 403\n# Description: Your request was flagged by our content moderation system.\n# Content-Type: application/json\n# 413\n# Description: Your request was larger than 10MiB.\n# Content-Type: application/json\n# 422\n# Description: Your request was well-formed, but rejected. See the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 429\n# Description: You have made more than 150 requests in 10 seconds.\n# Content-Type: application/json\n# 500\n# Description: An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).\n# Content-Type: application/json", + "Code": "### Stable Diffusion 3.5\nPOST {{host}}/v2beta/stable-image/generate/sd3\nAuthorization: Bearer {{token}}\ncontent-type: {{content-type}}\naccept: image/*\nstability-client-id: {{stability-client-id}}\nstability-client-user-id: {{stability-client-user-id}}\nstability-client-version: {{stability-client-version}}\nContent-Type: multipart/form-data; boundary=AutoSDKBoundary\nAccept: application/json, application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022prompt\u0022\n\nstring\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022mode\u0022\n\ntext-to-image\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022image\u0022; filename=\u0022image.bin\u0022\nContent-Type: application/octet-stream\n\n\u003C ./image.bin\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022strength\u0022\n\n0.0\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022aspect_ratio\u0022\n\n1:1\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022model\u0022\n\nsd3.5-large\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022seed\u0022\n\n0\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022output_format\u0022\n\npng\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022style_preset\u0022\n\nenhance\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022negative_prompt\u0022\n\nstring\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022cfg_scale\u0022\n\n0.0\n--AutoSDKBoundary--\n\n## Responses\n# 200\n# Description: Generation was successful.\n# Content-Type: application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n# 400\n# Description: Invalid parameter(s), see the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 403\n# Description: Your request was flagged by our content moderation system.\n# Content-Type: application/json\n# 413\n# Description: Your request was larger than 10MiB.\n# Content-Type: application/json\n# 422\n# Description: Your request was well-formed, but rejected. See the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 429\n# Description: You have made more than 150 requests in 10 seconds.\n# Content-Type: application/json\n# 500\n# Description: An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).\n# Content-Type: application/json", "Format": "http", "OperationId": "createStableImageGenerateSd3", "Setup": null @@ -171,7 +171,7 @@ "Slug": "stable-image-ultra", "Description": "Our most advanced text to image generation service, Stable Image Ultra creates the highest quality images\nwith unprecedented prompt understanding. Ultra excels in typography, complex compositions, dynamic lighting,\nvibrant hues, and overall cohesion and structure of an art piece. Made from the most advanced models,\nincluding Stable Diffusion 3.5, Ultra offers the best of the Stable Diffusion ecosystem.\n\n### Try it out\nGrab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=yXhs626oZdr1)\n\n### How to use\nPlease invoke this endpoint with a \u0060POST\u0060 request.\n\nThe headers of the request must include an API key in the \u0060authorization\u0060 field. The body of the request must be\n\u0060multipart/form-data\u0060. The accept header should be set to one of the following:\n- \u0060image/*\u0060 to receive the image in the format specified by the \u0060output_format\u0060 parameter.\n- \u0060application/json\u0060 to receive the image in the format specified by the \u0060output_format\u0060 parameter, but encoded to base64 in a JSON response.\n\nThe only required parameter is the \u0060prompt\u0060 field, which should contain the text prompt for the image generation.\n\nThe body of the request should include:\n- \u0060prompt\u0060 - text to generate the image from\n\nThe body may optionally include:\n- \u0060image\u0060 - the image to use as the starting point for the generation\n- \u0060strength\u0060 - controls how much influence the \u0060image\u0060 parameter has on the output image\n- \u0060aspect_ratio\u0060 - the aspect ratio of the output image\n- \u0060negative_prompt\u0060 - keywords of what you **do not** wish to see in the output image\n- \u0060seed\u0060 - the randomness seed to use for the generation\n- \u0060output_format\u0060 - the format of the output image\n\n\u003E **Note:** for the full list of optional parameters, please see the request schema below.\n\n### Output\nThe resolution of the generated image will be 1 megapixel. The default resolution is 1024x1024.\n\n### Credits\nThe Ultra service uses 8 credits per successful result. You will not be charged for failed results.", "Language": "http", - "Code": "### Stable Image Ultra\nPOST {{host}}/v2beta/stable-image/generate/ultra\nAuthorization: Bearer {{token}}\ncontent-type: {{content-type}}\naccept: image/*\nstability-client-id: {{stability-client-id}}\nstability-client-user-id: {{stability-client-user-id}}\nstability-client-version: {{stability-client-version}}\nContent-Type: multipart/form-data\nAccept: application/json, application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n\n## Responses\n# 200\n# Description: Generation was successful.\n# Content-Type: application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n# 400\n# Description: Invalid parameter(s), see the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 403\n# Description: Your request was flagged by our content moderation system.\n# Content-Type: application/json\n# 413\n# Description: Your request was larger than 10MiB.\n# Content-Type: application/json\n# 422\n# Description: Your request was well-formed, but rejected. See the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 429\n# Description: You have made more than 150 requests in 10 seconds.\n# Content-Type: application/json\n# 500\n# Description: An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).\n# Content-Type: application/json", + "Code": "### Stable Image Ultra\nPOST {{host}}/v2beta/stable-image/generate/ultra\nAuthorization: Bearer {{token}}\ncontent-type: {{content-type}}\naccept: image/*\nstability-client-id: {{stability-client-id}}\nstability-client-user-id: {{stability-client-user-id}}\nstability-client-version: {{stability-client-version}}\nContent-Type: multipart/form-data; boundary=AutoSDKBoundary\nAccept: application/json, application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022prompt\u0022\n\nstring\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022negative_prompt\u0022\n\nstring\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022aspect_ratio\u0022\n\n1:1\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022seed\u0022\n\n0\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022output_format\u0022\n\npng\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022image\u0022; filename=\u0022image.bin\u0022\nContent-Type: application/octet-stream\n\n\u003C ./image.bin\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022style_preset\u0022\n\nenhance\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022strength\u0022\n\n0.0\n--AutoSDKBoundary--\n\n## Responses\n# 200\n# Description: Generation was successful.\n# Content-Type: application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n# 400\n# Description: Invalid parameter(s), see the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 403\n# Description: Your request was flagged by our content moderation system.\n# Content-Type: application/json\n# 413\n# Description: Your request was larger than 10MiB.\n# Content-Type: application/json\n# 422\n# Description: Your request was well-formed, but rejected. See the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 429\n# Description: You have made more than 150 requests in 10 seconds.\n# Content-Type: application/json\n# 500\n# Description: An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).\n# Content-Type: application/json", "Format": "http", "OperationId": "createStableImageGenerateUltra", "Setup": null @@ -193,7 +193,7 @@ "Slug": "audio-to-audio", "Description": "Stable Audio transforms existing audio samples into new high-quality compositions up to six minutes\nlong at 44.1kHz stereo using text instructions. Discover techniques for sample transformation in our\n[Audio to Audio Guide](https://www.stableaudio.com/user-guide/audio-to-audio) to maximize creative control.\nRead more about the model capabilities [here](https://stability.ai/news-updates).\n\n### Try it out\nGrab your [API key](https://platform.stability.ai/account/keys) and head over to\n[![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Audio_API.ipynb)\nor try Stable Audio for free at [stableaudio.com](https://stableaudio.com).\n\nThis endpoint is asynchronous \u2014 it returns a generation \u0060id\u0060 immediately (HTTP 202).\nPoll \u0060GET /v2beta/audio/results/{id}\u0060 to retrieve the result.\n\n\u003E **Note:**\n\u003E - We do not allow copyrighted content to be uploaded to our platform.\n\u003E - Maximum request size is 100Mb.\n\n### Credits\n\n**Stable Audio 3.0**\n\nFlat rate of 26 credits per successful generation.\n\nAs always, you will not be charged for failed generations.", "Language": "http", - "Code": "### Audio-to-Audio\nPOST {{host}}/v2beta/audio/stable-audio/audio-to-audio\nAuthorization: Bearer {{token}}\ncontent-type: {{content-type}}\naccept: audio/*\nstability-client-id: {{stability-client-id}}\nstability-client-user-id: {{stability-client-user-id}}\nstability-client-version: {{stability-client-version}}\nContent-Type: multipart/form-data\nAccept: application/json\n\n## Responses\n# 202\n# Description: Generation started. Use the returned id to poll for the result.\n# Content-Type: application/json\n# 400\n# Description: Invalid parameter(s), see the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 403\n# Description: Your request was flagged by our content moderation system.\n# Content-Type: application/json\n# 422\n# Description: Your request was well-formed, but rejected. See the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 429\n# Description: You have made more than 150 requests in 10 seconds.\n# Content-Type: application/json\n# 500\n# Description: An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).\n# Content-Type: application/json", + "Code": "### Audio-to-Audio\nPOST {{host}}/v2beta/audio/stable-audio/audio-to-audio\nAuthorization: Bearer {{token}}\ncontent-type: {{content-type}}\naccept: audio/*\nstability-client-id: {{stability-client-id}}\nstability-client-user-id: {{stability-client-user-id}}\nstability-client-version: {{stability-client-version}}\nContent-Type: multipart/form-data; boundary=AutoSDKBoundary\nAccept: application/json\n\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022prompt\u0022\n\nstring\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022model\u0022\n\nstable-audio-3\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022duration\u0022\n\n190\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022seed\u0022\n\n0\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022steps\u0022\n\n8\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022cfg_scale\u0022\n\n1\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022output_format\u0022\n\nmp3\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022strength\u0022\n\n1\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022audio\u0022; filename=\u0022audio.bin\u0022\nContent-Type: application/octet-stream\n\n\u003C ./audio.bin\n--AutoSDKBoundary--\n\n## Responses\n# 202\n# Description: Generation started. Use the returned id to poll for the result.\n# Content-Type: application/json\n# 400\n# Description: Invalid parameter(s), see the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 403\n# Description: Your request was flagged by our content moderation system.\n# Content-Type: application/json\n# 422\n# Description: Your request was well-formed, but rejected. See the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 429\n# Description: You have made more than 150 requests in 10 seconds.\n# Content-Type: application/json\n# 500\n# Description: An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).\n# Content-Type: application/json", "Format": "http", "OperationId": "createAudioStableAudioAudioToAudio", "Setup": null @@ -204,7 +204,7 @@ "Slug": "inpaint", "Description": "Stable Audio transforms existing audio samples into new high-quality compositions up to six minutes\nlong at 44.1kHz stereo using text instructions.\n\n### Try it out\nGrab your [API key](https://platform.stability.ai/account/keys) and head over to\n[![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Audio_API.ipynb)\nor try Stable Audio for free at [stableaudio.com](https://stableaudio.com).\n\nThis endpoint is asynchronous \u2014 it returns a generation \u0060id\u0060 immediately (HTTP 202).\nPoll \u0060GET /v2beta/audio/results/{id}\u0060 to retrieve the result.\n\n\u003E **Note:**\n\u003E - We do not allow copyrighted content to be uploaded to our platform.\n\u003E - Maximum request size is 100Mb.\n\n### Credits\n**Stable Audio 3.0**\n\nFlat rate of 26 credits per successful generation.\n\nAs always, you will not be charged for failed generations.", "Language": "http", - "Code": "### Inpaint\nPOST {{host}}/v2beta/audio/stable-audio/inpaint\nAuthorization: Bearer {{token}}\ncontent-type: {{content-type}}\naccept: audio/*\nstability-client-id: {{stability-client-id}}\nstability-client-user-id: {{stability-client-user-id}}\nstability-client-version: {{stability-client-version}}\nContent-Type: multipart/form-data\nAccept: application/json\n\n## Responses\n# 202\n# Description: Generation started. Use the returned id to poll for the result.\n# Content-Type: application/json\n# 400\n# Description: Invalid parameter(s), see the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 403\n# Description: Your request was flagged by our content moderation system.\n# Content-Type: application/json\n# 422\n# Description: Your request was well-formed, but rejected. See the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 429\n# Description: You have made more than 150 requests in 10 seconds.\n# Content-Type: application/json\n# 500\n# Description: An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).\n# Content-Type: application/json", + "Code": "### Inpaint\nPOST {{host}}/v2beta/audio/stable-audio/inpaint\nAuthorization: Bearer {{token}}\ncontent-type: {{content-type}}\naccept: audio/*\nstability-client-id: {{stability-client-id}}\nstability-client-user-id: {{stability-client-user-id}}\nstability-client-version: {{stability-client-version}}\nContent-Type: multipart/form-data; boundary=AutoSDKBoundary\nAccept: application/json\n\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022prompt\u0022\n\nstring\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022model\u0022\n\nstable-audio-3\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022duration\u0022\n\n190\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022seed\u0022\n\n0\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022steps\u0022\n\n8\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022cfg_scale\u0022\n\n1\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022output_format\u0022\n\nmp3\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022mask_start\u0022\n\n30\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022mask_end\u0022\n\n380\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022audio\u0022; filename=\u0022audio.bin\u0022\nContent-Type: application/octet-stream\n\n\u003C ./audio.bin\n--AutoSDKBoundary--\n\n## Responses\n# 202\n# Description: Generation started. Use the returned id to poll for the result.\n# Content-Type: application/json\n# 400\n# Description: Invalid parameter(s), see the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 403\n# Description: Your request was flagged by our content moderation system.\n# Content-Type: application/json\n# 422\n# Description: Your request was well-formed, but rejected. See the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 429\n# Description: You have made more than 150 requests in 10 seconds.\n# Content-Type: application/json\n# 500\n# Description: An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).\n# Content-Type: application/json", "Format": "http", "OperationId": "createAudioStableAudioInpaint", "Setup": null @@ -215,7 +215,7 @@ "Slug": "text-to-audio", "Description": "Stable Audio transforms existing audio samples into new high-quality compositions up to six minutes\nlong at 44.1kHz stereo using text instructions.\n\n### Try it out\nGrab your [API key](https://platform.stability.ai/account/keys) and head over to\n[![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Audio_API.ipynb)\nor try Stable Audio for free at [stableaudio.com](https://stableaudio.com).\n\nThis endpoint is asynchronous \u2014 it returns a generation \u0060id\u0060 immediately (HTTP 202).\nPoll \u0060GET /v2beta/audio/results/{id}\u0060 to retrieve the result.\n\n### Credits\n\n**Stable Audio 3.0**\n\nFlat rate of 26 credits per successful generation.\n\nAs always, you will not be charged for failed generations.", "Language": "http", - "Code": "### Text-to-Audio\nPOST {{host}}/v2beta/audio/stable-audio/text-to-audio\nAuthorization: Bearer {{token}}\ncontent-type: {{content-type}}\naccept: audio/*\nstability-client-id: {{stability-client-id}}\nstability-client-user-id: {{stability-client-user-id}}\nstability-client-version: {{stability-client-version}}\nContent-Type: multipart/form-data\nAccept: application/json\n\n## Responses\n# 202\n# Description: Generation started. Use the returned id to poll for the result.\n# Content-Type: application/json\n# 400\n# Description: Invalid parameter(s), see the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 403\n# Description: Your request was flagged by our content moderation system.\n# Content-Type: application/json\n# 422\n# Description: Your request was well-formed, but rejected. See the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 429\n# Description: You have made more than 150 requests in 10 seconds.\n# Content-Type: application/json\n# 500\n# Description: An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).\n# Content-Type: application/json", + "Code": "### Text-to-Audio\nPOST {{host}}/v2beta/audio/stable-audio/text-to-audio\nAuthorization: Bearer {{token}}\ncontent-type: {{content-type}}\naccept: audio/*\nstability-client-id: {{stability-client-id}}\nstability-client-user-id: {{stability-client-user-id}}\nstability-client-version: {{stability-client-version}}\nContent-Type: multipart/form-data; boundary=AutoSDKBoundary\nAccept: application/json\n\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022prompt\u0022\n\nstring\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022model\u0022\n\nstable-audio-3\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022duration\u0022\n\n190\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022seed\u0022\n\n0\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022steps\u0022\n\n8\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022cfg_scale\u0022\n\n1\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022output_format\u0022\n\nmp3\n--AutoSDKBoundary--\n\n## Responses\n# 202\n# Description: Generation started. Use the returned id to poll for the result.\n# Content-Type: application/json\n# 400\n# Description: Invalid parameter(s), see the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 403\n# Description: Your request was flagged by our content moderation system.\n# Content-Type: application/json\n# 422\n# Description: Your request was well-formed, but rejected. See the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 429\n# Description: You have made more than 150 requests in 10 seconds.\n# Content-Type: application/json\n# 500\n# Description: An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).\n# Content-Type: application/json", "Format": "http", "OperationId": "createAudioStableAudioTextToAudio", "Setup": null @@ -226,7 +226,7 @@ "Slug": "audio-to-audio", "Description": "Stable Audio transforms existing audio samples into new high-quality compositions up to three minutes\nlong at 44.1kHz stereo using text instructions. Discover techniques for sample transformation in our\n[Audio to Audio Guide](https://www.stableaudio.com/user-guide/audio-to-audio) to maximize creative control.\nRead more about the model capabilities [here](https://stability.ai/news/stable-audio-2-0).\n\n### Try it out\nGrab your [API key](https://platform.stability.ai/account/keys) and head over to\n[![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Audio_API.ipynb)\nor try Stable Audio 2.0 for free at [stableaudio.com](https://stableaudio.com).\n\n### How to use\nPlease invoke this endpoint with a \u0060POST\u0060 request.\n\nThe headers of the request must include an API key in the \u0060authorization\u0060 field. The body of the request must be\n\u0060multipart/form-data\u0060. The \u0060accept\u0060 header should be set to one of the following:\n- \u0060audio/*\u0060 to receive the audio in the format specified by the \u0060output_format\u0060 parameter.\n- \u0060application/json\u0060 to receive the audio encoded as base64 in a JSON response.\n\nThe body of the request should include:\n- \u0060prompt\u0060 - text to generate the audio from. Check our\n[prompt guide](https://www.stableaudio.com/user-guide/audio-to-audio) for tips\n- \u0060audio\u0060 - the audio to use as the starting point for the generation\n\n\u003E **Notes:**\n\u003E - We do not allow copyrighted content to be uploaded to our platform.\n\u003E - Maximum request size is 50Mb.\n\n#### **Optional Parameters:**\nThe body may optionally include:\n- \u0060output_format\u0060 - the format of the output audio\n- \u0060seed\u0060 - the randomness seed to use for the generation\n- \u0060steps\u0060 - the number of sampling steps\n- \u0060duration\u0060 - the number of seconds of the generated audio\n- \u0060cfg_scale\u0060 - controls how strictly the diffusion process adheres to the prompt text (only for \u0060stable-audio-2\u0060)\n- \u0060model\u0060 - the model to use [\u0060stable-audio-2\u0060, \u0060stable-audio-2.5\u0060]\n- \u0060strength\u0060 - controls how much influence the \u0060audio\u0060 parameter has on the output audio\n\n\u003E **Note:** for more details about these parameters please see the request schema below.\n\n### Credits\n\n**Stable Audio 2.0**\n\nBy default, 20 credits per successful generation. The number of credits is determined\nby the following formula: \u0060credits = 17 \u002B 0.06 * steps\u0060.\nExamples:\n- 50 steps = 20 credits [default]\n- 100 steps = 23 credits\n\n**Stable Audio 2.5**\n\nRequests made using the Stable Audio 2.5 model have a flat rate of 20 credits per successful result.\n\nAs always, you will not be charged for failed generations.", "Language": "http", - "Code": "### Audio-to-Audio\nPOST {{host}}/v2beta/audio/stable-audio-2/audio-to-audio\nAuthorization: Bearer {{token}}\ncontent-type: {{content-type}}\naccept: audio/*\nstability-client-id: {{stability-client-id}}\nstability-client-user-id: {{stability-client-user-id}}\nstability-client-version: {{stability-client-version}}\nContent-Type: multipart/form-data\nAccept: application/json, application/json; type=audio/mpeg, application/json; type=audio/wav, audio/mpeg, audio/wav\n\n## Responses\n# 200\n# Description: Generation was successful.\n# Content-Type: application/json; type=audio/mpeg, application/json; type=audio/wav, audio/mpeg, audio/wav\n# 400\n# Description: Invalid parameter(s), see the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 403\n# Description: Your request was flagged by our content moderation system.\n# Content-Type: application/json\n# 422\n# Description: Your request was well-formed, but rejected. See the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 429\n# Description: You have made more than 150 requests in 10 seconds.\n# Content-Type: application/json\n# 500\n# Description: An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).\n# Content-Type: application/json", + "Code": "### Audio-to-Audio\nPOST {{host}}/v2beta/audio/stable-audio-2/audio-to-audio\nAuthorization: Bearer {{token}}\ncontent-type: {{content-type}}\naccept: audio/*\nstability-client-id: {{stability-client-id}}\nstability-client-user-id: {{stability-client-user-id}}\nstability-client-version: {{stability-client-version}}\nContent-Type: multipart/form-data; boundary=AutoSDKBoundary\nAccept: application/json, application/json; type=audio/mpeg, application/json; type=audio/wav, audio/mpeg, audio/wav\n\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022prompt\u0022\n\nstring\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022duration\u0022\n\n190\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022seed\u0022\n\n0\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022steps\u0022\n\n0\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022cfg_scale\u0022\n\n0.0\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022model\u0022\n\nstable-audio-2\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022output_format\u0022\n\nmp3\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022audio\u0022; filename=\u0022audio.bin\u0022\nContent-Type: application/octet-stream\n\n\u003C ./audio.bin\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022strength\u0022\n\n1\n--AutoSDKBoundary--\n\n## Responses\n# 200\n# Description: Generation was successful.\n# Content-Type: application/json; type=audio/mpeg, application/json; type=audio/wav, audio/mpeg, audio/wav\n# 400\n# Description: Invalid parameter(s), see the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 403\n# Description: Your request was flagged by our content moderation system.\n# Content-Type: application/json\n# 422\n# Description: Your request was well-formed, but rejected. See the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 429\n# Description: You have made more than 150 requests in 10 seconds.\n# Content-Type: application/json\n# 500\n# Description: An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).\n# Content-Type: application/json", "Format": "http", "OperationId": "createAudioStableAudio2AudioToAudio", "Setup": null @@ -237,7 +237,7 @@ "Slug": "inpaint", "Description": "Stable Audio 2.5 transforms existing audio samples into new high-quality compositions up to three minutes\nlong at 44.1kHz stereo using text instructions.\n\n### Try it out\nGrab your [API key](https://platform.stability.ai/account/keys) and head over to\n[![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Audio_API.ipynb).\n\n### How to use\nPlease invoke this endpoint with a \u0060POST\u0060 request.\n\nThe headers of the request must include an API key in the \u0060authorization\u0060 field. The body of the request must be\n\u0060multipart/form-data\u0060. The \u0060accept\u0060 header should be set to one of the following:\n- \u0060audio/*\u0060 to receive the audio in the format specified by the \u0060output_format\u0060 parameter.\n- \u0060application/json\u0060 to receive the audio encoded as base64 in a JSON response.\n\nThe body of the request should include:\n- \u0060prompt\u0060 - text to generate the audio from\n- \u0060audio\u0060 - the audio to use as the starting point for the generation\n\n\u003E **Notes:**\n\u003E - We do not allow copyrighted content to be uploaded to our platform.\n\u003E - Maximum request size is 50Mb.\n\n#### **Optional Parameters:**\nThe body may optionally include:\n- \u0060output_format\u0060 - the format of the output audio\n- \u0060seed\u0060 - the randomness seed to use for the generation\n- \u0060duration\u0060 - the number of seconds of the generated audio\n- \u0060steps\u0060 - the number of sampling steps\n- \u0060mask_start\u0060 - start time in seconds for the audio segment to be inpainted (e.g., 30.0 for 30.0 seconds)\n- \u0060mask_end\u0060 - end time in seconds for the audio segment to be inpainted (e.g., 190.0 for 190.0 seconds)\n\n\u003E **Note:** for more details about these parameters please see the request schema below.\n\n### Credits\n**Stable Audio 2.5**\n\nFlat rate of 20 credits per successful generation.\n\nAs always, you will not be charged for failed generations.", "Language": "http", - "Code": "### Inpaint\nPOST {{host}}/v2beta/audio/stable-audio-2/inpaint\nAuthorization: Bearer {{token}}\ncontent-type: {{content-type}}\naccept: audio/*\nstability-client-id: {{stability-client-id}}\nstability-client-user-id: {{stability-client-user-id}}\nstability-client-version: {{stability-client-version}}\nContent-Type: multipart/form-data\nAccept: application/json, application/json; type=audio/mpeg, application/json; type=audio/wav, audio/mpeg, audio/wav\n\n## Responses\n# 200\n# Description: Generation was successful.\n# Content-Type: application/json; type=audio/mpeg, application/json; type=audio/wav, audio/mpeg, audio/wav\n# 400\n# Description: Invalid parameter(s), see the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 403\n# Description: Your request was flagged by our content moderation system.\n# Content-Type: application/json\n# 422\n# Description: Your request was well-formed, but rejected. See the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 429\n# Description: You have made more than 150 requests in 10 seconds.\n# Content-Type: application/json\n# 500\n# Description: An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).\n# Content-Type: application/json", + "Code": "### Inpaint\nPOST {{host}}/v2beta/audio/stable-audio-2/inpaint\nAuthorization: Bearer {{token}}\ncontent-type: {{content-type}}\naccept: audio/*\nstability-client-id: {{stability-client-id}}\nstability-client-user-id: {{stability-client-user-id}}\nstability-client-version: {{stability-client-version}}\nContent-Type: multipart/form-data; boundary=AutoSDKBoundary\nAccept: application/json, application/json; type=audio/mpeg, application/json; type=audio/wav, audio/mpeg, audio/wav\n\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022prompt\u0022\n\nstring\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022duration\u0022\n\n190\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022seed\u0022\n\n0\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022steps\u0022\n\n8\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022output_format\u0022\n\nmp3\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022audio\u0022; filename=\u0022audio.bin\u0022\nContent-Type: application/octet-stream\n\n\u003C ./audio.bin\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022mask_start\u0022\n\n30\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022mask_end\u0022\n\n190\n--AutoSDKBoundary--\n\n## Responses\n# 200\n# Description: Generation was successful.\n# Content-Type: application/json; type=audio/mpeg, application/json; type=audio/wav, audio/mpeg, audio/wav\n# 400\n# Description: Invalid parameter(s), see the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 403\n# Description: Your request was flagged by our content moderation system.\n# Content-Type: application/json\n# 422\n# Description: Your request was well-formed, but rejected. See the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 429\n# Description: You have made more than 150 requests in 10 seconds.\n# Content-Type: application/json\n# 500\n# Description: An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).\n# Content-Type: application/json", "Format": "http", "OperationId": "createAudioStableAudio2Inpaint", "Setup": null @@ -248,7 +248,7 @@ "Slug": "text-to-audio", "Description": "Stable Audio generates high-quality music and sound effects up to three minutes long at\n44.1kHz stereo from text descriptions. Learn how to craft effective prompts in our\n[Prompt Guide](https://www.stableaudio.com/user-guide/text-to-audio) to get the best results\nfrom your generations.\n\n### Try it out\nGrab your [API key](https://platform.stability.ai/account/keys) and head over to\n[![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Audio_API.ipynb)\nor try Stable Audio 2.0 for free at [stableaudio.com](https://stableaudio.com).\n\n### How to use\nPlease invoke this endpoint with a \u0060POST\u0060 request.\n\nThe headers of the request must include an API key in the \u0060authorization\u0060 field. The body of the request must be\n\u0060multipart/form-data\u0060. The \u0060accept\u0060 header should be set to one of the following:\n- \u0060audio/*\u0060 to receive the audio in the format specified by the \u0060output_format\u0060 parameter.\n- \u0060application/json\u0060 to receive the audio encoded as base64 in a JSON response.\n\nThe body of the request should include:\n- \u0060prompt\u0060 - text to generate the audio from. Check our\n[prompt guide](https://www.stableaudio.com/user-guide/text-to-audio) for tips\n\n#### **Optional Parameters:**\nThe body may optionally include:\n- \u0060output_format\u0060 - the format of the output audio\n- \u0060seed\u0060 - the randomness seed to use for the generation\n- \u0060steps\u0060 - the number of sampling steps\n- \u0060duration\u0060 - the number of seconds of the generated audio\n- \u0060cfg_scale\u0060 - controls how strictly the diffusion process adheres to the prompt text (only for \u0060stable-audio-2\u0060)\n- \u0060model\u0060 - the model to use [\u0060stable-audio-2\u0060, \u0060stable-audio-2.5\u0060]\n\n\u003E **Note:** for more details about these parameters please see the request schema below.\n\n### Credits\n\n**Stable Audio 2.0**\n\nBy default, 20 credits per successful generation. The number of credits is determined\nby the following formula: \u0060credits = 17 \u002B 0.06 * steps\u0060.\n\nExamples:\n- 50 steps = 20 credits [default]\n- 100 steps = 23 credits\n\n**Stable Audio 2.5**\n\nRequests made using the Stable Audio 2.5 model have a flat rate of 20 credits per successful result.\n\nAs always, you will not be charged for failed generations.", "Language": "http", - "Code": "### Text-to-Audio\nPOST {{host}}/v2beta/audio/stable-audio-2/text-to-audio\nAuthorization: Bearer {{token}}\ncontent-type: {{content-type}}\naccept: audio/*\nstability-client-id: {{stability-client-id}}\nstability-client-user-id: {{stability-client-user-id}}\nstability-client-version: {{stability-client-version}}\nContent-Type: multipart/form-data\nAccept: application/json, application/json; type=audio/mpeg, application/json; type=audio/wav, audio/mpeg, audio/wav\n\n## Responses\n# 200\n# Description: Generation was successful.\n# Content-Type: application/json; type=audio/mpeg, application/json; type=audio/wav, audio/mpeg, audio/wav\n# 400\n# Description: Invalid parameter(s), see the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 403\n# Description: Your request was flagged by our content moderation system.\n# Content-Type: application/json\n# 422\n# Description: Your request was well-formed, but rejected. See the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 429\n# Description: You have made more than 150 requests in 10 seconds.\n# Content-Type: application/json\n# 500\n# Description: An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).\n# Content-Type: application/json", + "Code": "### Text-to-Audio\nPOST {{host}}/v2beta/audio/stable-audio-2/text-to-audio\nAuthorization: Bearer {{token}}\ncontent-type: {{content-type}}\naccept: audio/*\nstability-client-id: {{stability-client-id}}\nstability-client-user-id: {{stability-client-user-id}}\nstability-client-version: {{stability-client-version}}\nContent-Type: multipart/form-data; boundary=AutoSDKBoundary\nAccept: application/json, application/json; type=audio/mpeg, application/json; type=audio/wav, audio/mpeg, audio/wav\n\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022prompt\u0022\n\nstring\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022duration\u0022\n\n190\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022seed\u0022\n\n0\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022steps\u0022\n\n0\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022cfg_scale\u0022\n\n0.0\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022model\u0022\n\nstable-audio-2\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022output_format\u0022\n\nmp3\n--AutoSDKBoundary--\n\n## Responses\n# 200\n# Description: Generation was successful.\n# Content-Type: application/json; type=audio/mpeg, application/json; type=audio/wav, audio/mpeg, audio/wav\n# 400\n# Description: Invalid parameter(s), see the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 403\n# Description: Your request was flagged by our content moderation system.\n# Content-Type: application/json\n# 422\n# Description: Your request was well-formed, but rejected. See the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 429\n# Description: You have made more than 150 requests in 10 seconds.\n# Content-Type: application/json\n# 500\n# Description: An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).\n# Content-Type: application/json", "Format": "http", "OperationId": "createAudioStableAudio2TextToAudio", "Setup": null @@ -259,7 +259,7 @@ "Slug": "conservative", "Description": "Takes images between 64x64 and 1 megapixel and upscales them all the way to 4K resolution. Put more generally, it can upscale images ~20-40x times while preserving all aspects. Conservative Upscale minimizes alterations to the image and should not be used to reimagine an image.\n\n### Try it out\nGrab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)\n\n### How to use\n\nPlease invoke this endpoint with a \u0060POST\u0060 request.\n\nThe headers of the request must include an API key in the \u0060authorization\u0060 field. The body of the request must be\n\u0060multipart/form-data\u0060, and the \u0060accept\u0060 header should be set to one of the following:\n - \u0060image/*\u0060 to receive the image in the format specified by the \u0060output_format\u0060 parameter.\n - \u0060application/json\u0060 to receive the image encoded as base64 in a JSON response.\n\nThe body of the request must include:\n- \u0060image\u0060\n- \u0060prompt\u0060\n\nOptionally, the body of the request may also include:\n- \u0060negative_prompt\u0060\n- \u0060seed\u0060\n- \u0060output_format\u0060\n- \u0060creativity\u0060\n\n\u003E **Note:** for more details about these parameters please see the request schema below.\n\n### Output\nThe resolution of the generated image will be 4 megapixels.\n\n### Credits\nFlat rate of 40 credits per successful generation. You will not be charged for failed generations.", "Language": "http", - "Code": "### Conservative\nPOST {{host}}/v2beta/stable-image/upscale/conservative\nAuthorization: Bearer {{token}}\ncontent-type: {{content-type}}\naccept: image/*\nstability-client-id: {{stability-client-id}}\nstability-client-user-id: {{stability-client-user-id}}\nstability-client-version: {{stability-client-version}}\nContent-Type: multipart/form-data\nAccept: application/json, application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n\n## Responses\n# 200\n# Description: Upscale was successful.\n# Content-Type: application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n# 400\n# Description: Invalid parameter(s), see the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 403\n# Description: Your request was flagged by our content moderation system.\n# Content-Type: application/json\n# 413\n# Description: Your request was larger than 10MiB.\n# Content-Type: application/json\n# 422\n# Description: Your request was well-formed, but rejected. See the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 429\n# Description: You have made more than 150 requests in 10 seconds.\n# Content-Type: application/json\n# 500\n# Description: An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).\n# Content-Type: application/json", + "Code": "### Conservative\nPOST {{host}}/v2beta/stable-image/upscale/conservative\nAuthorization: Bearer {{token}}\ncontent-type: {{content-type}}\naccept: image/*\nstability-client-id: {{stability-client-id}}\nstability-client-user-id: {{stability-client-user-id}}\nstability-client-version: {{stability-client-version}}\nContent-Type: multipart/form-data; boundary=AutoSDKBoundary\nAccept: application/json, application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022image\u0022; filename=\u0022image.bin\u0022\nContent-Type: application/octet-stream\n\n\u003C ./image.bin\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022prompt\u0022\n\nstring\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022negative_prompt\u0022\n\nstring\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022seed\u0022\n\n0\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022output_format\u0022\n\npng\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022creativity\u0022\n\n0.35\n--AutoSDKBoundary--\n\n## Responses\n# 200\n# Description: Upscale was successful.\n# Content-Type: application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n# 400\n# Description: Invalid parameter(s), see the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 403\n# Description: Your request was flagged by our content moderation system.\n# Content-Type: application/json\n# 413\n# Description: Your request was larger than 10MiB.\n# Content-Type: application/json\n# 422\n# Description: Your request was well-formed, but rejected. See the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 429\n# Description: You have made more than 150 requests in 10 seconds.\n# Content-Type: application/json\n# 500\n# Description: An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).\n# Content-Type: application/json", "Format": "http", "OperationId": "createStableImageUpscaleConservative", "Setup": null @@ -270,7 +270,7 @@ "Slug": "creative-upscale-async", "Description": "Takes images between 64x64 and 1 megapixel and upscales them all the way to **4K** resolution. Put more\ngenerally, it can upscale images ~20-40x times while preserving, and often enhancing, quality.\nCreative Upscale **works best on highly degraded images and is not for photos of 1mp or above** as it performs\nheavy reimagining (controlled by creativity scale).\n\n### Try it out\nGrab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=QXxi9tfI425t)\n\n\n### How to use\nPlease invoke this endpoint with a \u0060POST\u0060 request.\n\nThe headers of the request must include an API key in the \u0060authorization\u0060 field. The body of the request must be\n\u0060multipart/form-data\u0060.\n\nThe body of the request should include:\n- \u0060image\u0060\n- \u0060prompt\u0060\n\nThe body may optionally include:\n- \u0060seed\u0060\n- \u0060negative_prompt\u0060\n- \u0060output_format\u0060\n- \u0060creativity\u0060\n- \u0060style_preset\u0060\n\n\u003E **Note:** for more details about these parameters please see the request schema below.\n\n### Results\nAfter invoking this endpoint with the required parameters, use the \u0060id\u0060 in the response to poll for results at the\n[results/{id} endpoint](#tag/Results/paths/~1v2beta~1results~1%7Bid%7D/get). Rate-limiting or other errors may occur if you poll more than once every 10 seconds.\n\n### Credits\nFlat rate of 60 credits per successful generation. You will not be charged for failed generations.", "Language": "http", - "Code": "### Creative Upscale (async)\nPOST {{host}}/v2beta/stable-image/upscale/creative\nAuthorization: Bearer {{token}}\ncontent-type: {{content-type}}\nstability-client-id: {{stability-client-id}}\nstability-client-user-id: {{stability-client-user-id}}\nstability-client-version: {{stability-client-version}}\nContent-Type: multipart/form-data\nAccept: application/json\n\n## Responses\n# 200\n# Description: Upscale was started.\n# Content-Type: application/json\n# 400\n# Description: Invalid parameter(s), see the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 403\n# Description: Your request was flagged by our content moderation system.\n# Content-Type: application/json\n# 413\n# Description: Your request was larger than 10MiB.\n# Content-Type: application/json\n# 422\n# Description: Your request was well-formed, but rejected. See the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 429\n# Description: You have made more than 150 requests in 10 seconds.\n# Content-Type: application/json\n# 500\n# Description: An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).\n# Content-Type: application/json", + "Code": "### Creative Upscale (async)\nPOST {{host}}/v2beta/stable-image/upscale/creative\nAuthorization: Bearer {{token}}\ncontent-type: {{content-type}}\nstability-client-id: {{stability-client-id}}\nstability-client-user-id: {{stability-client-user-id}}\nstability-client-version: {{stability-client-version}}\nContent-Type: multipart/form-data; boundary=AutoSDKBoundary\nAccept: application/json\n\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022image\u0022; filename=\u0022image.bin\u0022\nContent-Type: application/octet-stream\n\n\u003C ./image.bin\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022prompt\u0022\n\nstring\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022negative_prompt\u0022\n\nstring\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022output_format\u0022\n\npng\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022seed\u0022\n\n0\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022creativity\u0022\n\n0.3\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022style_preset\u0022\n\nenhance\n--AutoSDKBoundary--\n\n## Responses\n# 200\n# Description: Upscale was started.\n# Content-Type: application/json\n# 400\n# Description: Invalid parameter(s), see the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 403\n# Description: Your request was flagged by our content moderation system.\n# Content-Type: application/json\n# 413\n# Description: Your request was larger than 10MiB.\n# Content-Type: application/json\n# 422\n# Description: Your request was well-formed, but rejected. See the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 429\n# Description: You have made more than 150 requests in 10 seconds.\n# Content-Type: application/json\n# 500\n# Description: An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).\n# Content-Type: application/json", "Format": "http", "OperationId": "createStableImageUpscaleCreative", "Setup": null @@ -281,7 +281,7 @@ "Slug": "fast", "Description": "Our Fast Upscaler service enhances image resolution by 4x using predictive and generative AI. This lightweight and fast service (processing in ~1 second) is ideal for enhancing the quality of compressed images, making it suitable for social media posts and other applications.\n\n### Try it out\nGrab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)\n\n### How to use\n\nPlease invoke this endpoint with a \u0060POST\u0060 request.\n\nThe headers of the request must include an API key in the \u0060authorization\u0060 field. The body of the request must be\n\u0060multipart/form-data\u0060, and the \u0060accept\u0060 header should be set to one of the following:\n - \u0060image/*\u0060 to receive the image in the format specified by the \u0060output_format\u0060 parameter.\n - \u0060application/json\u0060 to receive the image encoded as base64 in a JSON response.\n\nThe body of the request must include:\n- \u0060image\u0060\n\nOptionally, the body of the request may also include:\n- \u0060output_format\u0060\n\n\u003E **Note:** for more details about these parameters please see the request schema below.\n\n### Output\nThe resolution of the generated image is 4 times that of the input image with a maximum size of 16 megapixels.\n\n### Credits\nFlat rate of 2 credit per successful generation. You will not be charged for failed generations.", "Language": "http", - "Code": "### Fast\nPOST {{host}}/v2beta/stable-image/upscale/fast\nAuthorization: Bearer {{token}}\ncontent-type: {{content-type}}\naccept: image/*\nstability-client-id: {{stability-client-id}}\nstability-client-user-id: {{stability-client-user-id}}\nstability-client-version: {{stability-client-version}}\nContent-Type: multipart/form-data\nAccept: application/json, application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n\n## Responses\n# 200\n# Description: Upscale was successful.\n# Content-Type: application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n# 400\n# Description: Invalid parameter(s), see the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 403\n# Description: Your request was flagged by our content moderation system.\n# Content-Type: application/json\n# 413\n# Description: Your request was larger than 10MiB.\n# Content-Type: application/json\n# 422\n# Description: Your request was well-formed, but rejected. See the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 429\n# Description: You have made more than 150 requests in 10 seconds.\n# Content-Type: application/json\n# 500\n# Description: An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).\n# Content-Type: application/json", + "Code": "### Fast\nPOST {{host}}/v2beta/stable-image/upscale/fast\nAuthorization: Bearer {{token}}\ncontent-type: {{content-type}}\naccept: image/*\nstability-client-id: {{stability-client-id}}\nstability-client-user-id: {{stability-client-user-id}}\nstability-client-version: {{stability-client-version}}\nContent-Type: multipart/form-data; boundary=AutoSDKBoundary\nAccept: application/json, application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022image\u0022; filename=\u0022image.bin\u0022\nContent-Type: application/octet-stream\n\n\u003C ./image.bin\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022output_format\u0022\n\npng\n--AutoSDKBoundary--\n\n## Responses\n# 200\n# Description: Upscale was successful.\n# Content-Type: application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n# 400\n# Description: Invalid parameter(s), see the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 403\n# Description: Your request was flagged by our content moderation system.\n# Content-Type: application/json\n# 413\n# Description: Your request was larger than 10MiB.\n# Content-Type: application/json\n# 422\n# Description: Your request was well-formed, but rejected. See the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 429\n# Description: You have made more than 150 requests in 10 seconds.\n# Content-Type: application/json\n# 500\n# Description: An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).\n# Content-Type: application/json", "Format": "http", "OperationId": "createStableImageUpscaleFast", "Setup": null @@ -303,7 +303,7 @@ "Slug": "imagetoimage", "Description": "Modify an image based on a text prompt", "Language": "http", - "Code": "### image-to-image\n# @name imageToImage\nPOST {{host}}/v1/generation/{{engine_id}}/image-to-image\nAuthorization: Bearer {{token}}\nAccept: application/json\nOrganization: org-123456\nContent-Type: multipart/form-data\nAccept: application/json, image/png\n\n{\u0022image_strength\u0022:0.35,\u0022init_image_mode\u0022:\u0022IMAGE_STRENGTH\u0022,\u0022init_image\u0022:\u0022\\u003Cimage binary\\u003E\u0022,\u0022text_prompts[0][text]\u0022:\u0022A dog space commander\u0022,\u0022text_prompts[0][weight]\u0022:1,\u0022cfg_scale\u0022:7,\u0022clip_guidance_preset\u0022:\u0022FAST_BLUE\u0022,\u0022sampler\u0022:\u0022K_DPM_2_ANCESTRAL\u0022,\u0022samples\u0022:3,\u0022steps\u0022:20}\n\n## Responses\n# 200\n# Description: OK response.\n# Content-Type: application/json, image/png\n# 400\n# Description: bad_request: general error for invalid parameters \u003Cbr/\u003E\u003Cbr/\u003E\n\n\u003Cp style=\u0022display: flex; margin-top: -20px; margin-bottom: 0\u0022\u003EMore specific errors:\u003C/p\u003E\n\n - invalid_samples: Sample count may only be greater than 1 when the accept header is set to \u0060application/json\u0060\n - invalid_height_or_width: Height and width must be specified in increments of 64\n - invalid_file_size: The file size of one or more of the provided files is invalid\n - invalid_mime_type: The mime type of one or more of the provided files is invalid\n - invalid_image_dimensions: The dimensions of the provided \u0060init_image\u0060 and \u0060mask_image\u0060 do not match\n - invalid_mask_image: The parameter \u0060mask_source\u0060 was set to \u0060MASK_IMAGE_WHITE\u0060 or \u0060MASK_IMAGE_BLACK\u0060 but no \u0060mask_image\u0060 was provided\n - invalid_prompts: One or more of the prompts contains filtered words\n - invalid_pixel_count: Incorrect number of pixels specified. Requirements:\n - For 768 engines : \u003Cspan style=\u0027display: inline-flex; justify-content: flex-start; gap:8px\u0027\u003E589,824 \u003Cspan\u003E\u2264\u003C/span\u003E \u0060height * width\u0060 \u003Cspan\u003E\u2264\u003C/span\u003E 1,048,576\u003C/span\u003E\n - All other engines: \u003Cspan style=\u0027display: inline-flex; justify-content: flex-start; gap:8px\u0027\u003E262,144 \u003Cspan\u003E\u2264\u003C/span\u003E \u0060height * width\u0060 \u003Cspan\u003E\u2264\u003C/span\u003E 1,048,576\u003C/span\u003E\n# Content-Type: application/json\n# 401\n# Description: unauthorized: API key missing or invalid\n# Content-Type: application/json\n# 403\n# Description: permission_denied: You lack the necessary permissions to perform this action\n# Content-Type: application/json\n# 404\n# Description: not_found: The requested resource was not found (e.g. specifing a model that does not exist)\n# Content-Type: application/json\n# 500\n# Description: server_error: Some unexpected server error occurred\n# Content-Type: application/json", + "Code": "### image-to-image\n# @name imageToImage\nPOST {{host}}/v1/generation/{{engine_id}}/image-to-image\nAuthorization: Bearer {{token}}\nAccept: application/json\nOrganization: org-123456\nContent-Type: multipart/form-data; boundary=AutoSDKBoundary\nAccept: application/json, image/png\n\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022text_prompts\u0022\n\nstring\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022init_image\u0022; filename=\u0022init_image.bin\u0022\nContent-Type: application/octet-stream\n\n\u003C ./init_image.bin\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022init_image_mode\u0022\n\nIMAGE_STRENGTH\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022image_strength\u0022\n\n0.4\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022step_schedule_start\u0022\n\n0.4\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022step_schedule_end\u0022\n\n0.01\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022cfg_scale\u0022\n\n7\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022clip_guidance_preset\u0022\n\nFAST_BLUE\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022sampler\u0022\n\nK_DPM_2_ANCESTRAL\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022samples\u0022\n\n1\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022seed\u0022\n\n0\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022steps\u0022\n\n75\n--AutoSDKBoundary--\n\n## Responses\n# 200\n# Description: OK response.\n# Content-Type: application/json, image/png\n# 400\n# Description: bad_request: general error for invalid parameters \u003Cbr/\u003E\u003Cbr/\u003E\n\n\u003Cp style=\u0022display: flex; margin-top: -20px; margin-bottom: 0\u0022\u003EMore specific errors:\u003C/p\u003E\n\n - invalid_samples: Sample count may only be greater than 1 when the accept header is set to \u0060application/json\u0060\n - invalid_height_or_width: Height and width must be specified in increments of 64\n - invalid_file_size: The file size of one or more of the provided files is invalid\n - invalid_mime_type: The mime type of one or more of the provided files is invalid\n - invalid_image_dimensions: The dimensions of the provided \u0060init_image\u0060 and \u0060mask_image\u0060 do not match\n - invalid_mask_image: The parameter \u0060mask_source\u0060 was set to \u0060MASK_IMAGE_WHITE\u0060 or \u0060MASK_IMAGE_BLACK\u0060 but no \u0060mask_image\u0060 was provided\n - invalid_prompts: One or more of the prompts contains filtered words\n - invalid_pixel_count: Incorrect number of pixels specified. Requirements:\n - For 768 engines : \u003Cspan style=\u0027display: inline-flex; justify-content: flex-start; gap:8px\u0027\u003E589,824 \u003Cspan\u003E\u2264\u003C/span\u003E \u0060height * width\u0060 \u003Cspan\u003E\u2264\u003C/span\u003E 1,048,576\u003C/span\u003E\n - All other engines: \u003Cspan style=\u0027display: inline-flex; justify-content: flex-start; gap:8px\u0027\u003E262,144 \u003Cspan\u003E\u2264\u003C/span\u003E \u0060height * width\u0060 \u003Cspan\u003E\u2264\u003C/span\u003E 1,048,576\u003C/span\u003E\n# Content-Type: application/json\n# 401\n# Description: unauthorized: API key missing or invalid\n# Content-Type: application/json\n# 403\n# Description: permission_denied: You lack the necessary permissions to perform this action\n# Content-Type: application/json\n# 404\n# Description: not_found: The requested resource was not found (e.g. specifing a model that does not exist)\n# Content-Type: application/json\n# 500\n# Description: server_error: Some unexpected server error occurred\n# Content-Type: application/json", "Format": "http", "OperationId": "imageToImage", "Setup": null @@ -314,7 +314,7 @@ "Slug": "masking", "Description": "Selectively modify portions of an image using a mask", "Language": "http", - "Code": "### image-to-image/masking\n# @name masking\nPOST {{host}}/v1/generation/{{engine_id}}/image-to-image/masking\nAuthorization: Bearer {{token}}\nAccept: application/json\nOrganization: org-123456\nContent-Type: multipart/form-data\nAccept: application/json, image/png\n\n{\u0022mask_source\u0022:\u0022INIT_IMAGE_ALPHA\u0022,\u0022init_image\u0022:\u0022\\u003Cimage binary\\u003E\u0022,\u0022text_prompts[0][text]\u0022:\u0022A dog space commander\u0022,\u0022text_prompts[0][weight]\u0022:1,\u0022cfg_scale\u0022:7,\u0022clip_guidance_preset\u0022:\u0022FAST_BLUE\u0022,\u0022sampler\u0022:\u0022K_DPM_2_ANCESTRAL\u0022,\u0022samples\u0022:3,\u0022steps\u0022:20}\n\n## Responses\n# 200\n# Description: OK response.\n# Content-Type: application/json, image/png\n# 400\n# Description: bad_request: general error for invalid parameters \u003Cbr/\u003E\u003Cbr/\u003E\n\n\u003Cp style=\u0022display: flex; margin-top: -20px; margin-bottom: 0\u0022\u003EMore specific errors:\u003C/p\u003E\n\n - invalid_samples: Sample count may only be greater than 1 when the accept header is set to \u0060application/json\u0060\n - invalid_height_or_width: Height and width must be specified in increments of 64\n - invalid_file_size: The file size of one or more of the provided files is invalid\n - invalid_mime_type: The mime type of one or more of the provided files is invalid\n - invalid_image_dimensions: The dimensions of the provided \u0060init_image\u0060 and \u0060mask_image\u0060 do not match\n - invalid_mask_image: The parameter \u0060mask_source\u0060 was set to \u0060MASK_IMAGE_WHITE\u0060 or \u0060MASK_IMAGE_BLACK\u0060 but no \u0060mask_image\u0060 was provided\n - invalid_prompts: One or more of the prompts contains filtered words\n - invalid_pixel_count: Incorrect number of pixels specified. Requirements:\n - For 768 engines : \u003Cspan style=\u0027display: inline-flex; justify-content: flex-start; gap:8px\u0027\u003E589,824 \u003Cspan\u003E\u2264\u003C/span\u003E \u0060height * width\u0060 \u003Cspan\u003E\u2264\u003C/span\u003E 1,048,576\u003C/span\u003E\n - All other engines: \u003Cspan style=\u0027display: inline-flex; justify-content: flex-start; gap:8px\u0027\u003E262,144 \u003Cspan\u003E\u2264\u003C/span\u003E \u0060height * width\u0060 \u003Cspan\u003E\u2264\u003C/span\u003E 1,048,576\u003C/span\u003E\n# Content-Type: application/json\n# 401\n# Description: unauthorized: API key missing or invalid\n# Content-Type: application/json\n# 403\n# Description: permission_denied: You lack the necessary permissions to perform this action\n# Content-Type: application/json\n# 404\n# Description: not_found: The requested resource was not found (e.g. specifing a model that does not exist)\n# Content-Type: application/json\n# 500\n# Description: server_error: Some unexpected server error occurred\n# Content-Type: application/json", + "Code": "### image-to-image/masking\n# @name masking\nPOST {{host}}/v1/generation/{{engine_id}}/image-to-image/masking\nAuthorization: Bearer {{token}}\nAccept: application/json\nOrganization: org-123456\nContent-Type: multipart/form-data; boundary=AutoSDKBoundary\nAccept: application/json, image/png\n\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022init_image\u0022; filename=\u0022init_image.bin\u0022\nContent-Type: application/octet-stream\n\n\u003C ./init_image.bin\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022mask_source\u0022\n\nstring\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022mask_image\u0022; filename=\u0022mask_image.bin\u0022\nContent-Type: application/octet-stream\n\n\u003C ./mask_image.bin\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022text_prompts\u0022\n\nstring\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022cfg_scale\u0022\n\n7\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022clip_guidance_preset\u0022\n\nFAST_BLUE\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022sampler\u0022\n\nK_DPM_2_ANCESTRAL\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022samples\u0022\n\n1\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022seed\u0022\n\n0\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022steps\u0022\n\n75\n--AutoSDKBoundary--\n\n## Responses\n# 200\n# Description: OK response.\n# Content-Type: application/json, image/png\n# 400\n# Description: bad_request: general error for invalid parameters \u003Cbr/\u003E\u003Cbr/\u003E\n\n\u003Cp style=\u0022display: flex; margin-top: -20px; margin-bottom: 0\u0022\u003EMore specific errors:\u003C/p\u003E\n\n - invalid_samples: Sample count may only be greater than 1 when the accept header is set to \u0060application/json\u0060\n - invalid_height_or_width: Height and width must be specified in increments of 64\n - invalid_file_size: The file size of one or more of the provided files is invalid\n - invalid_mime_type: The mime type of one or more of the provided files is invalid\n - invalid_image_dimensions: The dimensions of the provided \u0060init_image\u0060 and \u0060mask_image\u0060 do not match\n - invalid_mask_image: The parameter \u0060mask_source\u0060 was set to \u0060MASK_IMAGE_WHITE\u0060 or \u0060MASK_IMAGE_BLACK\u0060 but no \u0060mask_image\u0060 was provided\n - invalid_prompts: One or more of the prompts contains filtered words\n - invalid_pixel_count: Incorrect number of pixels specified. Requirements:\n - For 768 engines : \u003Cspan style=\u0027display: inline-flex; justify-content: flex-start; gap:8px\u0027\u003E589,824 \u003Cspan\u003E\u2264\u003C/span\u003E \u0060height * width\u0060 \u003Cspan\u003E\u2264\u003C/span\u003E 1,048,576\u003C/span\u003E\n - All other engines: \u003Cspan style=\u0027display: inline-flex; justify-content: flex-start; gap:8px\u0027\u003E262,144 \u003Cspan\u003E\u2264\u003C/span\u003E \u0060height * width\u0060 \u003Cspan\u003E\u2264\u003C/span\u003E 1,048,576\u003C/span\u003E\n# Content-Type: application/json\n# 401\n# Description: unauthorized: API key missing or invalid\n# Content-Type: application/json\n# 403\n# Description: permission_denied: You lack the necessary permissions to perform this action\n# Content-Type: application/json\n# 404\n# Description: not_found: The requested resource was not found (e.g. specifing a model that does not exist)\n# Content-Type: application/json\n# 500\n# Description: server_error: Some unexpected server error occurred\n# Content-Type: application/json", "Format": "http", "OperationId": "masking", "Setup": null @@ -336,7 +336,7 @@ "Slug": "upscaleimage", "Description": "Create a higher resolution version of an input image.\n\nThis operation outputs an image with a maximum pixel count of **4,194,304**. This is equivalent to dimensions such as \u00602048x2048\u0060 and \u00604096x1024\u0060.\n\nBy default, the input image will be upscaled by a factor of 2. For additional control over the output dimensions, a \u0060width\u0060 or \u0060height\u0060 parameter may be specified.", "Language": "http", - "Code": "### image-to-image/upscale\n# @name upscaleImage\nPOST {{host}}/v1/generation/{{engine_id}}/image-to-image/upscale\nAuthorization: Bearer {{token}}\nAccept: application/json\nOrganization: org-123456\nContent-Type: multipart/form-data\nAccept: application/json, image/png\n\n{\u0022image\u0022:\u0022\\u003Cimage binary\\u003E\u0022}\n\n## Responses\n# 200\n# Description: OK response.\n# Content-Type: application/json, image/png\n# 400\n# Description: bad_request: general error for invalid parameters \u003Cbr/\u003E\u003Cbr/\u003E\n\n\u003Cp style=\u0022display: flex; margin-top: -20px; margin-bottom: 0\u0022\u003EMore specific errors:\u003C/p\u003E\n\n - invalid_file_size: The file size of one or more of the provided files is invalid\n - invalid_mime_type: The mime type of one or more of the provided files is invalid\n - invalid_pixel_count: The requested image would exceed the maximum pixel count of 4,194,304\n# Content-Type: application/json\n# 401\n# Description: unauthorized: API key missing or invalid\n# Content-Type: application/json\n# 403\n# Description: permission_denied: You lack the necessary permissions to perform this action\n# Content-Type: application/json\n# 404\n# Description: not_found: The requested resource was not found (e.g. specifing a model that does not exist)\n# Content-Type: application/json\n# 500\n# Description: server_error: Some unexpected server error occurred\n# Content-Type: application/json", + "Code": "### image-to-image/upscale\n# @name upscaleImage\nPOST {{host}}/v1/generation/{{engine_id}}/image-to-image/upscale\nAuthorization: Bearer {{token}}\nAccept: application/json\nOrganization: org-123456\nContent-Type: multipart/form-data; boundary=AutoSDKBoundary\nAccept: application/json, image/png\n\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022image\u0022; filename=\u0022image.bin\u0022\nContent-Type: application/octet-stream\n\n\u003C ./image.bin\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022width\u0022\n\n0\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022height\u0022\n\n0\n--AutoSDKBoundary--\n\n## Responses\n# 200\n# Description: OK response.\n# Content-Type: application/json, image/png\n# 400\n# Description: bad_request: general error for invalid parameters \u003Cbr/\u003E\u003Cbr/\u003E\n\n\u003Cp style=\u0022display: flex; margin-top: -20px; margin-bottom: 0\u0022\u003EMore specific errors:\u003C/p\u003E\n\n - invalid_file_size: The file size of one or more of the provided files is invalid\n - invalid_mime_type: The mime type of one or more of the provided files is invalid\n - invalid_pixel_count: The requested image would exceed the maximum pixel count of 4,194,304\n# Content-Type: application/json\n# 401\n# Description: unauthorized: API key missing or invalid\n# Content-Type: application/json\n# 403\n# Description: permission_denied: You lack the necessary permissions to perform this action\n# Content-Type: application/json\n# 404\n# Description: not_found: The requested resource was not found (e.g. specifing a model that does not exist)\n# Content-Type: application/json\n# 500\n# Description: server_error: Some unexpected server error occurred\n# Content-Type: application/json", "Format": "http", "OperationId": "upscaleImage", "Setup": null @@ -369,7 +369,7 @@ "Slug": "stable-image-inpaint", "Description": "Inpaint an existing image, with or without a mask, using our latest-and-greatest inpainting model.\n\n### Search-and-Replace Mode\nThis mode is ideal for individuals of all levels of skill in design. It can be used for straightforward\nadjustments to images. The service will automatically mask the most appropriate object based on the contents\nof the \u0060search_prompt\u0060, and replace it with a generated result based on the \u0060prompt\u0060.\n\n**How to use:** set the \u0060mode\u0060 parameter to \u0060search\u0060 and provide a short description of what to\nsearch-and-replace in the \u0060search_prompt\u0060 parameter.\n\n### Mask Mode\nThis mode allows for precise control of generative fill tasks on an image, down to the level of\nindividual pixels. Design professionals can provide a \u0060mask\u0060 for the section of the image to be replaced,\nand use standard image prompting to describe the full image as it should appear after the editing.\nThe resulting image will incorporate all of the elements described in the \u0060prompt\u0060.\n\n**How to use:** set the \u0060mode\u0060 parameter to \u0060mask\u0060 and either pass in an \u0060image\u0060 with an alpha channel\nor provide an explicit mask image to the \u0060mask\u0060 parameter. If both are present the \u0060mask\u0060 parameter will\ntake precedence.\n\n### Price\n- Requests with \u0060mode\u0060 set to \u0060search\u0060 cost 4 cents.\n- Requests with \u0060mode\u0060 set to \u0060mask\u0060 cost 3 cents.", "Language": "http", - "Code": "### stable-image/inpaint\nPOST {{host}}/v2alpha/generation/stable-image/inpaint\nAuthorization: Bearer {{token}}\ncontent-type: {{content-type}}\naccept: image/*\nContent-Type: multipart/form-data\nAccept: application/json, application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n\n## Responses\n# 200\n# Description: Inpainting was successful.\n# Content-Type: application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n# 400\n# Description: Invalid parameter(s), see the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 403\n# Description: Your request was flagged by our content moderation system.\n# Content-Type: application/json\n# 500\n# Description: An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).\n# Content-Type: application/json", + "Code": "### stable-image/inpaint\nPOST {{host}}/v2alpha/generation/stable-image/inpaint\nAuthorization: Bearer {{token}}\ncontent-type: {{content-type}}\naccept: image/*\nContent-Type: multipart/form-data; boundary=AutoSDKBoundary\nAccept: application/json, application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n\n## Responses\n# 200\n# Description: Inpainting was successful.\n# Content-Type: application/json; type=image/jpeg, application/json; type=image/png, application/json; type=image/webp, image/jpeg, image/png, image/webp\n# 400\n# Description: Invalid parameter(s), see the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 403\n# Description: Your request was flagged by our content moderation system.\n# Content-Type: application/json\n# 500\n# Description: An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).\n# Content-Type: application/json", "Format": "http", "OperationId": "createV2alphaGenerationStableImageInpaint", "Setup": null @@ -380,7 +380,7 @@ "Slug": "stable-image-upscale", "Description": "Takes images between 64x64 and 1 megapixel and upscales them all the way to **4K** resolution. Put more\ngenerally, it can upscale images ~20-40x times while preserving, and often enhancing, quality.\n\n### How to use\n - Invoke this endpoint with the required parameters to start a generation\n - Use that \u0060id\u0060 in the response to poll for results at the [upscale/result/{id}](#tag/v2alphageneration/paths/~1v2alpha~1generation~1stable-image~1upscale~1result~1%7Bid%7D/get) endpoint\n - Rate-limiting or other errors may occur if you poll more than once every 10 seconds\n\n### Price\nFlat rate of 25 cents per generation.", "Language": "http", - "Code": "### stable-image/upscale\nPOST {{host}}/v2alpha/generation/stable-image/upscale\nAuthorization: Bearer {{token}}\ncontent-type: {{content-type}}\nContent-Type: multipart/form-data\nAccept: application/json\n\n## Responses\n# 200\n# Description: Upscaling was successful!\n# Content-Type: application/json\n# 400\n# Description: Invalid parameter(s), see the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 403\n# Description: Your request was flagged by our content moderation system.\n# Content-Type: application/json\n# 500\n# Description: An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).\n# Content-Type: application/json", + "Code": "### stable-image/upscale\nPOST {{host}}/v2alpha/generation/stable-image/upscale\nAuthorization: Bearer {{token}}\ncontent-type: {{content-type}}\nContent-Type: multipart/form-data; boundary=AutoSDKBoundary\nAccept: application/json\n\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022image\u0022; filename=\u0022image.bin\u0022\nContent-Type: application/octet-stream\n\n\u003C ./image.bin\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022prompt\u0022\n\nstring\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022negative_prompt\u0022\n\nstring\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022output_format\u0022\n\npng\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022seed\u0022\n\n0\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022creativity\u0022\n\n0.3\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022style_preset\u0022\n\nenhance\n--AutoSDKBoundary--\n\n## Responses\n# 200\n# Description: Upscaling was successful!\n# Content-Type: application/json\n# 400\n# Description: Invalid parameter(s), see the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 403\n# Description: Your request was flagged by our content moderation system.\n# Content-Type: application/json\n# 500\n# Description: An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).\n# Content-Type: application/json", "Format": "http", "OperationId": "createV2alphaGenerationStableImageUpscale", "Setup": null @@ -402,7 +402,7 @@ "Slug": "stable-fast-3d", "Description": "Stable Fast 3D generates high-quality 3D assets from a single 2D input image.\n\n### Try it out\nGrab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_3D_API.ipynb)\n\n### How to use\nPlease invoke this endpoint with a \u0060POST\u0060 request.\n\nThe headers of the request must include an API key in the \u0060authorization\u0060 field. The body of the request must be\n\u0060multipart/form-data\u0060.\n\nThe body of the request should include:\n- \u0060image\u0060\n\nThe body may optionally include:\n- \u0060texture_resolution\u0060\n- \u0060foreground_ratio\u0060\n\n\u003E **Note:** for more details about these parameters please see the request schema below.\n\n### Output\nThe output is a binary blob that includes a glTF asset, including JSON, buffers, and images.\nSee the [GLB File Format Specification](https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#glb-file-format-specification) for more details.\n\n### Credits\nFlat rate of 10 credits per successful generation. You will not be charged for failed generations.", "Language": "http", - "Code": "### Stable Fast 3D\nPOST {{host}}/v2beta/3d/stable-fast-3d\nAuthorization: Bearer {{token}}\ncontent-type: {{content-type}}\nstability-client-id: {{stability-client-id}}\nstability-client-user-id: {{stability-client-user-id}}\nstability-client-version: {{stability-client-version}}\nContent-Type: multipart/form-data\nAccept: application/json, model/gltf-binary\n\n## Responses\n# 200\n# Description: Generation was successful.\n# Content-Type: model/gltf-binary\n# 400\n# Description: Invalid parameter(s), see the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 403\n# Description: Your request was flagged by our content moderation system.\n# Content-Type: application/json\n# 413\n# Description: Your request was larger than 10MiB.\n# Content-Type: application/json\n# 429\n# Description: You have made more than 150 requests in 10 seconds.\n# Content-Type: application/json\n# 500\n# Description: An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).\n# Content-Type: application/json", + "Code": "### Stable Fast 3D\nPOST {{host}}/v2beta/3d/stable-fast-3d\nAuthorization: Bearer {{token}}\ncontent-type: {{content-type}}\nstability-client-id: {{stability-client-id}}\nstability-client-user-id: {{stability-client-user-id}}\nstability-client-version: {{stability-client-version}}\nContent-Type: multipart/form-data; boundary=AutoSDKBoundary\nAccept: application/json, model/gltf-binary\n\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022image\u0022; filename=\u0022image.bin\u0022\nContent-Type: application/octet-stream\n\n\u003C ./image.bin\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022texture_resolution\u0022\n\n1024\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022foreground_ratio\u0022\n\n0.85\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022remesh\u0022\n\nnone\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022vertex_count\u0022\n\n-1\n--AutoSDKBoundary--\n\n## Responses\n# 200\n# Description: Generation was successful.\n# Content-Type: model/gltf-binary\n# 400\n# Description: Invalid parameter(s), see the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 403\n# Description: Your request was flagged by our content moderation system.\n# Content-Type: application/json\n# 413\n# Description: Your request was larger than 10MiB.\n# Content-Type: application/json\n# 429\n# Description: You have made more than 150 requests in 10 seconds.\n# Content-Type: application/json\n# 500\n# Description: An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).\n# Content-Type: application/json", "Format": "http", "OperationId": "create3dStableFast3d", "Setup": null @@ -413,7 +413,7 @@ "Slug": "stable-point-aware-3d", "Description": "Stable Point Aware 3D (SPAR3D) can make real-time edits and create the complete structure\nof a 3D object from a single image in a few seconds. SPAR3D combines the strengths of\npoint-cloud diffusion (probabilistic) and mesh regression (deterministic) to have improved\ndetails on the unseen back regions in the input image.\n\nCompared to our previous model [Stable Fast 3D](#tag/3D/paths/~1v2beta~13d~1stable-fast-3d/post), this new\none allows editing of backside information using the point cloud representation and also\nleverages a larger Diffusion model to generally improve the depth and backside\npredictions.\n\nRead more about the model capabilities [here](https://bit.ly/4h7cpgF).\n\nThis API is currently in\npreview. Please don\u2019t hesitate to [contact us](https://stability.ai/contact) with any questions.\n\n### Try it out\nGrab your [API key](https://platform.stability.ai/account/keys) and head over to [![Open Google Colab](https://platform.stability.ai/svg/google-colab.svg)](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_3D_API.ipynb)\n\n### How to use\nPlease invoke this endpoint with a \u0060POST\u0060 request.\n\nThe headers of the request must include an API key in the \u0060authorization\u0060 field. The body of the request must be\n\u0060multipart/form-data\u0060.\n\nThe body of the request should include:\n- \u0060image\u0060\n\nThe body may optionally include:\n- \u0060texture_resolution\u0060\n- \u0060foreground_ratio\u0060\n- \u0060remesh\u0060\n- \u0060target_type\u0060\n- \u0060target_count\u0060\n- \u0060guidance_scale\u0060\n- \u0060seed\u0060\n\n\u003E **Note:** for more details about these parameters please see the request schema below.\n\n### Output\nThe output is a binary blob that includes a glTF asset, including JSON, buffers, and images.\nSee the [GLB File Format Specification](https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#glb-file-format-specification) for more details.\n\n### Credits\nFlat rate of 4 credits per successful generation. You will not be charged for failed generations.", "Language": "http", - "Code": "### Stable Point Aware 3D\nPOST {{host}}/v2beta/3d/stable-point-aware-3d\nAuthorization: Bearer {{token}}\ncontent-type: {{content-type}}\nstability-client-id: {{stability-client-id}}\nstability-client-user-id: {{stability-client-user-id}}\nstability-client-version: {{stability-client-version}}\nContent-Type: multipart/form-data\nAccept: application/json, model/gltf-binary\n\n## Responses\n# 200\n# Description: Generation was successful.\n# Content-Type: model/gltf-binary\n# 400\n# Description: Invalid parameter(s), see the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 403\n# Description: Your request was flagged by our content moderation system.\n# Content-Type: application/json\n# 413\n# Description: Your request was larger than 10MiB.\n# Content-Type: application/json\n# 429\n# Description: You have made more than 150 requests in 10 seconds.\n# Content-Type: application/json\n# 500\n# Description: An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).\n# Content-Type: application/json", + "Code": "### Stable Point Aware 3D\nPOST {{host}}/v2beta/3d/stable-point-aware-3d\nAuthorization: Bearer {{token}}\ncontent-type: {{content-type}}\nstability-client-id: {{stability-client-id}}\nstability-client-user-id: {{stability-client-user-id}}\nstability-client-version: {{stability-client-version}}\nContent-Type: multipart/form-data; boundary=AutoSDKBoundary\nAccept: application/json, model/gltf-binary\n\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022image\u0022; filename=\u0022image.bin\u0022\nContent-Type: application/octet-stream\n\n\u003C ./image.bin\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022texture_resolution\u0022\n\n1024\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022foreground_ratio\u0022\n\n1.3\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022remesh\u0022\n\nnone\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022target_type\u0022\n\nnone\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022target_count\u0022\n\n1000\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022guidance_scale\u0022\n\n3\n--AutoSDKBoundary\nContent-Disposition: form-data; name=\u0022seed\u0022\n\n0\n--AutoSDKBoundary--\n\n## Responses\n# 200\n# Description: Generation was successful.\n# Content-Type: model/gltf-binary\n# 400\n# Description: Invalid parameter(s), see the \u0060errors\u0060 field for details.\n# Content-Type: application/json\n# 403\n# Description: Your request was flagged by our content moderation system.\n# Content-Type: application/json\n# 413\n# Description: Your request was larger than 10MiB.\n# Content-Type: application/json\n# 429\n# Description: You have made more than 150 requests in 10 seconds.\n# Content-Type: application/json\n# 500\n# Description: An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).\n# Content-Type: application/json", "Format": "http", "OperationId": "create3dStablePointAware3d", "Setup": null