Skip to content

Commit

Permalink
com.rest.blockadelabs 1.0.0-preview.5 (#6)
Browse files Browse the repository at this point in the history
  • Loading branch information
StephenHodgson committed Jun 26, 2023
1 parent d447b4c commit fe43256
Show file tree
Hide file tree
Showing 12 changed files with 437 additions and 61 deletions.
4 changes: 3 additions & 1 deletion BlockadeLabs/Assets/Demo/SkyboxDemo.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// Licensed under the MIT License. See LICENSE in the project root for license information.

using BlockadeLabs.Skyboxes;
using System;
using System.Collections.Generic;
Expand Down Expand Up @@ -79,7 +81,7 @@ private async void GenerateSkybox(string prompt)
generateButton.interactable = false;
promptInputField.interactable = false;
var request = new SkyboxRequest(prompt, skyboxStyleId: skyboxOptions[skyboxStyleDropdown.value].Id);
var skyboxInfo = await api.SkyboxEndpoint.GenerateSkyboxAsync(request, lifetimeCancellationTokenSource.Token).ConfigureAwait(true);
var skyboxInfo = await api.SkyboxEndpoint.GenerateSkyboxAsync(request, cancellationToken: lifetimeCancellationTokenSource.Token).ConfigureAwait(true);
skyboxMaterial.mainTexture = skyboxInfo.MainTexture;
Debug.Log($"Successfully created skybox: {skyboxInfo.Id}");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ protected override void SetupDefaultRequestHeaders()
#if !UNITY_WEBGL
{"User-Agent", "com.rest.blockadelabs" },
#endif
{"X-API-Key", Authentication.Info.ApiKey }
{"x-api-key", Authentication.Info.ApiKey }
};
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ namespace BlockadeLabs
{
public sealed class BlockadeLabsSettingsInfo : ISettingsInfo
{
internal const string DefaultDomain = "blockade.cloudshell.run";
internal const string DefaultDomain = "backend.blockadelabs.com";
internal const string DefaultVersion = "v1";

public BlockadeLabsSettingsInfo()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,45 +1,124 @@
// Licensed under the MIT License. See LICENSE in the project root for license information.

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Scripting;
using Utilities.WebRequestRest;

namespace BlockadeLabs.Skyboxes
{
public sealed class SkyboxEndpoint : BlockadeLabsBaseEndpoint
{
[Preserve]
private class SkyboxInfoRequest
{
[Preserve]
[JsonConstructor]
public SkyboxInfoRequest([JsonProperty("request")] SkyboxInfo skyboxInfo)
{
SkyboxInfo = skyboxInfo;
}

[Preserve]
[JsonProperty("request")]
public SkyboxInfo SkyboxInfo { get; }
}

public SkyboxEndpoint(BlockadeLabsClient client) : base(client) { }

protected override string Root => "skybox";
protected override string Root => string.Empty;

/// <summary>
/// Returns the list of predefined styles that can influence the overall aesthetic of your skybox generation.
/// </summary>
/// <param name="cancellationToken"></param>
/// <param name="cancellationToken">Optional, <see cref="CancellationToken"/>.</param>
/// <returns>A list of <see cref="SkyboxStyle"/>s.</returns>
public async Task<IReadOnlyList<SkyboxStyle>> GetSkyboxStylesAsync(CancellationToken cancellationToken = default)
{
var endpoint = GetUrl("/styles");
var endpoint = GetUrl("skybox/styles");
var response = await Rest.GetAsync(endpoint, parameters: new RestParameters(client.DefaultRequestHeaders), cancellationToken);
response.Validate();
return JsonConvert.DeserializeObject<IReadOnlyList<SkyboxStyle>>(response.Body, client.JsonSerializationOptions);
}

/// <summary>
/// Generate a skybox image
/// Generate a skybox image.
/// </summary>
/// <param name="skyboxRequest"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<SkyboxInfo> GenerateSkyboxAsync(SkyboxRequest skyboxRequest, CancellationToken cancellationToken = default)
/// <param name="skyboxRequest"><see cref="SkyboxRequest"/>.</param>
/// <param name="pollingInterval">Optional, polling interval in seconds.</param>
/// <param name="cancellationToken">Optional, <see cref="CancellationToken"/>.</param>
/// <returns><see cref="SkyboxInfo"/>.</returns>
public async Task<SkyboxInfo> GenerateSkyboxAsync(SkyboxRequest skyboxRequest, int? pollingInterval = null, CancellationToken cancellationToken = default)
{
var jsonContent = JsonConvert.SerializeObject(skyboxRequest, client.JsonSerializationOptions);
var response = await Rest.PostAsync(GetUrl("/generate"), jsonContent, parameters: new RestParameters(client.DefaultRequestHeaders), cancellationToken);
var formData = new WWWForm();
formData.AddField("prompt", skyboxRequest.Prompt);

if (!string.IsNullOrWhiteSpace(skyboxRequest.NegativeText))
{
formData.AddField("negative_text", skyboxRequest.NegativeText);
}

if (skyboxRequest.Seed.HasValue)
{
formData.AddField("seed", skyboxRequest.Seed.Value);
}

if (skyboxRequest.SkyboxStyleId.HasValue)
{
formData.AddField("skybox_style_id", skyboxRequest.SkyboxStyleId.Value);
}

if (skyboxRequest.RemixImagineId.HasValue)
{
formData.AddField("remix_imagine_id", skyboxRequest.RemixImagineId.Value);
}

if (skyboxRequest.Depth)
{
formData.AddField("return_depth", skyboxRequest.Depth.ToString());
}

if (skyboxRequest.ControlImage != null)
{
if (!string.IsNullOrWhiteSpace(skyboxRequest.ControlModel))
{
formData.AddField("control_model", skyboxRequest.ControlModel);
}

using var imageData = new MemoryStream();
await skyboxRequest.ControlImage.CopyToAsync(imageData, cancellationToken);
formData.AddBinaryData("control_image", imageData.ToArray(), skyboxRequest.ControlImageFileName);
skyboxRequest.Dispose();
}

var response = await Rest.PostAsync(GetUrl("skybox"), formData, parameters: new RestParameters(client.DefaultRequestHeaders), cancellationToken);
response.Validate();
var skyboxInfo = JsonConvert.DeserializeObject<SkyboxInfo>(response.Body, client.JsonSerializationOptions);

while (!cancellationToken.IsCancellationRequested)
{
await Task.Delay(pollingInterval ?? 3 * 1000, cancellationToken)
.ConfigureAwait(true); // Configure await to make sure we're still in Unity context
skyboxInfo = await GetSkyboxInfoAsync(skyboxInfo, cancellationToken);

if (skyboxInfo.Status is "pending" or "processing")
{
continue;
}

break;
}

if (skyboxInfo.Status != "complete")
{
throw new Exception($"Failed to generate skybox! {skyboxInfo.Id} -> {skyboxInfo.Status}\nError: {skyboxInfo.ErrorMessage}\n{skyboxInfo}");
}

var downloadTasks = new List<Task>(2)
{
Task.Run(async () =>
Expand All @@ -62,14 +141,14 @@ public async Task<SkyboxInfo> GenerateSkyboxAsync(SkyboxRequest skyboxRequest, C
/// <summary>
/// Returns the skybox metadata for the given skybox id.
/// </summary>
/// <param name="id"></param>
/// <param name="cancellationToken"></param>
/// <param name="id">Skybox Id.</param>
/// <param name="cancellationToken">Optional, <see cref="CancellationToken"/>.</param>
/// <returns><see cref="SkyboxInfo"/>.</returns>
public async Task<SkyboxInfo> GetSkyboxInfoAsync(int id, CancellationToken cancellationToken = default)
{
var response = await Rest.GetAsync(GetUrl($"/info/{id}"), parameters: new RestParameters(client.DefaultRequestHeaders), cancellationToken);
var response = await Rest.GetAsync(GetUrl($"imagine/requests/{id}"), parameters: new RestParameters(client.DefaultRequestHeaders), cancellationToken);
response.Validate();
return JsonConvert.DeserializeObject<SkyboxInfo>(response.Body, client.JsonSerializationOptions);
return JsonConvert.DeserializeObject<SkyboxInfoRequest>(response.Body, client.JsonSerializationOptions).SkyboxInfo;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ public sealed class SkyboxInfo
[JsonProperty("title")] string title,
[JsonProperty("obfuscated_id")] string obfuscatedId,
[JsonProperty("created_at")] DateTime createdAt,
[JsonProperty("updated_at")] DateTime updatedAt)
[JsonProperty("updated_at")] DateTime updatedAt,
[JsonProperty("error_message")] string errorMessage = null)
{
Id = id;
SkyboxStyleId = skyboxStyleId;
Expand All @@ -33,6 +34,7 @@ public sealed class SkyboxInfo
ObfuscatedId = obfuscatedId;
CreatedAt = createdAt;
UpdatedAt = updatedAt;
ErrorMessage = errorMessage;
}

[JsonProperty("id")]
Expand Down Expand Up @@ -79,5 +81,12 @@ public sealed class SkyboxInfo

[JsonProperty("updated_at")]
public DateTime UpdatedAt { get; }

[JsonProperty("error_message")]
public string ErrorMessage { get; set; }

public override string ToString() => JsonConvert.SerializeObject(this, Formatting.Indented);

public static implicit operator int(SkyboxInfo skyboxInfo) => skyboxInfo.Id;
}
}

0 comments on commit fe43256

Please sign in to comment.