Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

com.rest.blockadelabs 1.0.0-preview.5 #6

Merged
merged 3 commits into from
Jun 26, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
com.rest.blockadelabs 1.0.0-preview.5
  • Loading branch information
StephenHodgson committed Jun 26, 2023
commit 38368f24d1842f1fa9500df75e778823fab015b2
2 changes: 1 addition & 1 deletion BlockadeLabs/Assets/Demo/SkyboxDemo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,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,110 @@
// 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.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>
/// <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></returns>
public async Task<SkyboxInfo> GenerateSkyboxAsync(SkyboxRequest skyboxRequest, CancellationToken cancellationToken = default)
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);
response.Validate();
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());
}

var response = await Rest.PostAsync(GetUrl("skybox"), formData, parameters: new RestParameters(client.DefaultRequestHeaders), cancellationToken);
response.Validate(true);
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 +127,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;
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
using Newtonsoft.Json;

namespace BlockadeLabs.Skyboxes
{
public sealed class SkyboxRequest
Expand All @@ -20,22 +18,16 @@ public sealed class SkyboxRequest
Depth = depth;
}

[JsonProperty("prompt")]
public string Prompt { get; }

[JsonProperty("negative_text")]
public string NegativeText { get; }

[JsonProperty("seed")]
public int? Seed { get; }

[JsonProperty("skybox_style_id")]
public int? SkyboxStyleId { get; }

[JsonProperty("remix_imagine_id")]
public int? RemixImagineId { get; }

[JsonProperty("return_depth")]
public bool Depth { get; }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,5 +39,7 @@ public sealed class SkyboxStyle

[JsonProperty("sort_order")]
public int SortOrder { get; }

public static implicit operator int(SkyboxStyle style) => style.Id;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,25 +27,15 @@ public async Task Test_02_GenerateSkybox()
var api = new BlockadeLabsClient();
Assert.IsNotNull(api.SkyboxEndpoint);

var request = new SkyboxRequest("underwater", depth: true);
var request = new SkyboxRequest("mars", depth: true);
var skyboxInfo = await api.SkyboxEndpoint.GenerateSkyboxAsync(request);
Assert.IsNotNull(skyboxInfo);
Debug.Log($"Successfully created skybox: {skyboxInfo.Id}");
Debug.Log(skyboxInfo.MainTextureUrl);
Assert.IsNotNull(skyboxInfo.MainTexture);
Debug.Log(skyboxInfo.DepthTextureUrl);
Assert.IsNotNull(skyboxInfo.DepthTexture);
}

[Test]
public async Task Test_03_GetSkyboxInfo()
{
var api = new BlockadeLabsClient();
Assert.IsNotNull(api.SkyboxEndpoint);

var result = await api.SkyboxEndpoint.GetSkyboxInfoAsync(5719637);
Assert.IsNotNull(result);
Debug.Log($"Skybox: {result.Id} | {result.MainTextureUrl}");
Debug.Log(skyboxInfo.ToString());
}
}
}
4 changes: 2 additions & 2 deletions BlockadeLabs/Packages/com.rest.blockadelabs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"displayName": "BlockadeLabs",
"description": "A Non-Official Blockade Labs Rest Client for Unity (UPM)",
"keywords": [],
"version": "1.0.0-preview.4",
"version": "1.0.0-preview.5",
"unity": "2021.3",
"documentationUrl": "https://github.com/RageAgainstThePixel/com.rest.blockadelabs#documentation",
"changelogUrl": "https://github.com/RageAgainstThePixel/com.rest.blockadelabs/releases",
Expand All @@ -17,7 +17,7 @@
"url": "https://github.com/StephenHodgson"
},
"dependencies": {
"com.utilities.rest": "2.0.6"
"com.utilities.rest": "2.0.7"
},
"publishConfig": {
"registry": "https://package.openupm.com"
Expand Down
Loading