ai.muna.muna 0.0.46 → 0.0.47

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -15,12 +15,12 @@ namespace Muna.Editor.Build {
15
15
  using UnityEditor.Android;
16
16
  using UnityEditor.Build.Reporting;
17
17
  using API;
18
+ using Internal;
18
19
  using Services;
19
- using MunaSettings = Internal.MunaSettings;
20
20
 
21
21
  internal sealed class AndroidBuildHandler : BuildHandler, IPostGenerateGradleAndroidProject {
22
22
 
23
- private static List<CachedPrediction> cache;
23
+ private static List<PredictionCache.CachedPrediction> cache;
24
24
  private static Dictionary<AndroidArchitecture, string> ArchToClientId = new() {
25
25
  [AndroidArchitecture.ARMv7] = @"android-armeabi-v7a",
26
26
  [AndroidArchitecture.ARM64] = @"android-arm64-v8a",
@@ -49,7 +49,7 @@ namespace Muna.Editor.Build {
49
49
  clientId: target,
50
50
  configurationId: @""
51
51
  )).Result;
52
- return new CachedPrediction(prediction, target);
52
+ return prediction.AsCached(target);
53
53
  } catch (AggregateException ex) {
54
54
  Debug.LogWarning($"Muna: Failed to embed {tag} predictor with error: {ex.InnerException}. Predictions with this predictor will likely fail at runtime.");
55
55
  return null;
@@ -16,7 +16,7 @@ namespace Muna.Editor.Build {
16
16
  using UnityEditor.Build;
17
17
  using UnityEditor.Build.Reporting;
18
18
  using API;
19
- using MunaSettings = Internal.MunaSettings;
19
+ using Internal;
20
20
 
21
21
  #if UNITY_IOS || UNITY_VISIONOS
22
22
  using UnityEditor.iOS.Xcode;
@@ -25,7 +25,7 @@ namespace Muna.Editor.Build {
25
25
 
26
26
  internal sealed class iOSBuildHandler : BuildHandler, IPostprocessBuildWithReport {
27
27
 
28
- private List<CachedPrediction> cache;
28
+ private List<PredictionCache.CachedPrediction> cache;
29
29
  private static readonly Dictionary<BuildTarget, string> ClientIds = new () {
30
30
  [BuildTarget.iOS] = @"ios-arm64",
31
31
  [BuildTarget.VisionOS] = @"visionos-arm64"
@@ -37,7 +37,7 @@ namespace Muna.Editor.Build {
37
37
  var projectSettings = MunaProjectSettings.instance;
38
38
  var settings = MunaSettings.Create(projectSettings.accessKey);
39
39
  var embeds = GetEmbeds();
40
- var cache = new List<CachedPrediction>();
40
+ var cache = new List<PredictionCache.CachedPrediction>();
41
41
  var clientId = ClientIds[report.summary.platform];
42
42
  foreach (var embed in embeds) {
43
43
  var client = new DotNetClient(embed.url, embed.accessKey);
@@ -50,7 +50,7 @@ namespace Muna.Editor.Build {
50
50
  clientId: clientId,
51
51
  configurationId: @""
52
52
  )).Result;
53
- return new CachedPrediction(prediction, clientId);
53
+ return prediction.AsCached(clientId);
54
54
  } catch (AggregateException ex) {
55
55
  Debug.LogWarning($"Muna: Failed to embed {tag} predictor with error: {ex.InnerException}. Predictions with this predictor will likely fail at runtime.");
56
56
  return null;
@@ -15,17 +15,17 @@ namespace Muna.Editor.Build {
15
15
  using UnityEditor.Build;
16
16
  using UnityEditor.Build.Reporting;
17
17
  using API;
18
+ using Internal;
18
19
  using Services;
19
- using MunaSettings = Internal.MunaSettings;
20
20
 
21
- #if UNITY_STANDALONE_OSX
21
+ #if UNITY_STANDALONE_OSX
22
22
  using UnityEditor.iOS.Xcode;
23
23
  using UnityEditor.iOS.Xcode.Extensions;
24
- #endif
24
+ #endif
25
25
 
26
26
  internal sealed class macOSBuildHandler : BuildHandler, IPostprocessBuildWithReport {
27
27
 
28
- private List<CachedPrediction> cache;
28
+ private List<PredictionCache.CachedPrediction> cache;
29
29
  private static readonly string[] ClientIds = new[] {
30
30
  "macos-arm64",
31
31
  "macos-x86_64"
@@ -41,7 +41,7 @@ namespace Muna.Editor.Build {
41
41
  var settings = MunaSettings.Create(projectSettings.accessKey);
42
42
  // Embed predictors
43
43
  var embeds = GetEmbeds();
44
- var cache = new List<CachedPrediction>();
44
+ var cache = new List<PredictionCache.CachedPrediction>();
45
45
  foreach (var embed in embeds) {
46
46
  var client = new DotNetClient(embed.url, embed.accessKey);
47
47
  var muna = new Muna(client);
@@ -54,7 +54,7 @@ namespace Muna.Editor.Build {
54
54
  clientId: clientId,
55
55
  configurationId: @""
56
56
  )).Result;
57
- return new CachedPrediction(prediction, clientId);
57
+ return prediction.AsCached(clientId);
58
58
  }
59
59
  catch (AggregateException ex) {
60
60
  Debug.LogWarning($"Muna: Failed to embed {tag} predictor with error: {ex.InnerException}. Predictions with this predictor will likely fail at runtime.");
@@ -7,6 +7,7 @@ namespace Muna.Editor {
7
7
 
8
8
  using System.IO;
9
9
  using UnityEditor;
10
+ using Internal;
10
11
 
11
12
  internal static class MunaMenu {
12
13
 
@@ -32,10 +33,7 @@ namespace Muna.Editor {
32
33
 
33
34
  [MenuItem(@"Tools/Muna/Clear Predictor Cache", false, BasePriority + 5)]
34
35
  private static void ClearPredictorCache() {
35
- Directory.Delete(
36
- global::Muna.API.PredictionCacheClient.PredictorCachePath,
37
- true
38
- );
36
+ Directory.Delete(PredictionCache.PredictorCachePath, true);
39
37
  UnityEngine.Debug.Log("Muna: Cleared predictor cache.");
40
38
  }
41
39
  }
Binary file
package/README.md CHANGED
@@ -16,7 +16,7 @@ Add the following items to your Unity project's `Packages/manifest.json`:
16
16
  }
17
17
  ],
18
18
  "dependencies": {
19
- "ai.muna.muna": "0.0.46"
19
+ "ai.muna.muna": "0.0.47"
20
20
  }
21
21
  }
22
22
  ```
package/Runtime/Muna.cs CHANGED
@@ -94,7 +94,7 @@ namespace Muna {
94
94
 
95
95
  #region --Operations--
96
96
  public readonly MunaClient client;
97
- public const string Version = @"0.0.46";
97
+ public const string Version = @"0.0.47";
98
98
  internal const string URL = @"https://api.muna.ai/v1";
99
99
  #endregion
100
100
  }
@@ -7,13 +7,12 @@
7
7
 
8
8
  namespace Muna.API {
9
9
 
10
- using System;
11
10
  using System.Collections.Generic;
12
11
  using System.IO;
13
12
  using System.Linq;
14
13
  using System.Threading.Tasks;
15
14
  using UnityEngine;
16
- using Newtonsoft.Json;
15
+ using Internal;
17
16
  using Services;
18
17
 
19
18
  /// <summary>
@@ -32,9 +31,8 @@ namespace Muna.API {
32
31
  /// <param name="cache">Prediction cache.</param>
33
32
  public PredictionCacheClient(
34
33
  string url,
35
- string? accessKey,
36
- List<CachedPrediction>? cache = default
37
- ) : base(url, accessKey) => this.cache = cache ?? new();
34
+ string? accessKey
35
+ ) : base(url, accessKey) { }
38
36
 
39
37
  /// <summary>
40
38
  /// Perform a request to a Muna REST endpoint.
@@ -52,11 +50,9 @@ namespace Muna.API {
52
50
  Dictionary<string, string>? headers = default
53
51
  ) where T : class {
54
52
  // Check payload
55
- var tag = payload?.TryGetValue(@"tag", out var t) ?? false ? t as string : null;
56
- var clientId = payload?.TryGetValue(@"clientId", out var id) ?? false ? id as string : null;
57
- var configurationId = payload?.TryGetValue(@"configurationId", out var configuration) ?? false ?
58
- configuration as string :
59
- null;
53
+ var tag = GetValue<string>(payload, @"tag");
54
+ var clientId = GetValue<string>(payload, @"clientId");
55
+ var configurationId = GetValue<string>(payload, @"configurationId");
60
56
  if (
61
57
  method != @"POST" ||
62
58
  path != @"/predictions" ||
@@ -65,38 +61,35 @@ namespace Muna.API {
65
61
  string.IsNullOrEmpty(configurationId)
66
62
  )
67
63
  return await base.Request<T>(method, path, payload, headers);
68
- // Get cached prediction
69
- var sanitizedTag = tag.Substring(1).Replace("/", "_");
70
- var cachePath = Path.Combine(
71
- PredictorCachePath,
64
+ // Get embedded prediction if available
65
+ var cache = MunaSettings.Instance!.cache;
66
+ var embeddedPrediction = cache.FirstOrDefault(p =>
67
+ p.tag == tag &&
68
+ MatchClientIds(p.clientId!, clientId)
69
+ );
70
+ // Load from prediction cache
71
+ if (PredictionCache.Get(
72
+ tag,
72
73
  clientId,
73
74
  configurationId,
74
- $"{sanitizedTag}.json"
75
- );
76
- var cachedPrediction = TryLoadCachedPrediction(cachePath);
77
- if (cachedPrediction != null)
75
+ embeddedPrediction?.resources,
76
+ out var cachedPrediction
77
+ ))
78
78
  return cachedPrediction as T;
79
- // Create prediction
80
- var predictionId = cache.FirstOrDefault(p => p.tag == tag && p.clientId == clientId)?.id;
79
+ // Create prediction and cache
81
80
  var prediction = await base.Request<Prediction>(
82
81
  method: @"POST",
83
82
  path: @"/predictions",
84
- payload: new () {
83
+ payload: new() {
85
84
  [@"tag"] = tag,
86
85
  [@"clientId"] = clientId,
87
86
  [@"configurationId"] = configurationId,
88
- [@"predictionId"] = predictionId,
87
+ [@"predictionId"] = embeddedPrediction?.id,
89
88
  },
90
89
  headers
91
90
  );
92
91
  prediction!.resources = await Task.WhenAll(prediction.resources.Select(GetCachedResource));
93
- // Write
94
- var predictionJson = JsonConvert.SerializeObject(
95
- new CachedPrediction(prediction, clientId),
96
- Formatting.Indented
97
- );
98
- Directory.CreateDirectory(Path.GetDirectoryName(cachePath));
99
- File.WriteAllText(cachePath, predictionJson);
92
+ PredictionCache.Add(prediction.AsCached(clientId, configurationId));
100
93
  // Return
101
94
  return prediction as T;
102
95
  }
@@ -104,15 +97,9 @@ namespace Muna.API {
104
97
 
105
98
 
106
99
  #region --Operations--
107
- private readonly List<CachedPrediction> cache;
108
- private static string CacheRoot => Application.isEditor ?
109
- Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), @".fxn") :
110
- Path.Combine(Application.persistentDataPath, @"fxn");
111
- private static string ResourceCachePath => Path.Combine(CacheRoot, @"cache");
112
- internal static string PredictorCachePath => Path.Combine(CacheRoot, @"predictors");
113
100
 
114
101
  private async Task<PredictionResource> GetCachedResource(PredictionResource resource) {
115
- var path = PredictionService.GetResourcePath(resource, ResourceCachePath);
102
+ var path = PredictionService.GetResourcePath(resource, PredictionCache.ResourceCachePath);
116
103
  if (!File.Exists(path)) {
117
104
  Directory.CreateDirectory(Path.GetDirectoryName(path));
118
105
  using var dataStream = await Download(resource.url);
@@ -122,22 +109,28 @@ namespace Muna.API {
122
109
  return new PredictionResource { type = resource.type, url = $"file://{path}" };
123
110
  }
124
111
 
125
- private static Prediction? TryLoadCachedPrediction(string path) {
126
- if (!File.Exists(path))
127
- return null;
128
- var json = File.ReadAllText(path);
129
- var prediction = JsonConvert.DeserializeObject<Prediction>(json)!;
130
- var resources = prediction.resources.Select(res => new PredictionResource {
131
- type = res.type,
132
- url = $"file://{PredictionService.GetResourcePath(res, ResourceCachePath)}",
133
- name = res.name
134
- }).ToArray();
135
- if (!resources.All(res => File.Exists(new Uri(res.url).LocalPath))) {
136
- File.Delete(path);
137
- return null;
112
+ private static T? GetValue<T>(
113
+ Dictionary<string, object?>? payload,
114
+ string key
115
+ ) {
116
+ if (payload?.TryGetValue(key, out var value) ?? false)
117
+ return (T?)value;
118
+ else
119
+ return default;
120
+ }
121
+
122
+ private static bool MatchClientIds(string a, string b) {
123
+ if (a == b)
124
+ return true;
125
+ if (a.Contains("android") && b.Contains("android")) {
126
+ var ARM32 = new[] { "armeabi-v7a", "armv7l", "armv8l" };
127
+ var ARM64 = new[] { "arm64", "aarch64", "armv8" };
128
+ if (ARM32.Any(s => a.Contains(s)) && ARM32.Any(s => b.Contains(s)))
129
+ return true;
130
+ if (ARM64.Any(s => a.Contains(s)) && ARM64.Any(s => b.Contains(s)))
131
+ return true;
138
132
  }
139
- prediction.resources = resources;
140
- return prediction;
133
+ return false;
141
134
  }
142
135
  #endregion
143
136
  }
@@ -27,7 +27,7 @@ namespace Muna.Internal {
27
27
  /// Predictor cache.
28
28
  /// </summary>
29
29
  [field: SerializeField, HideInInspector]
30
- public List<CachedPrediction> cache { get; internal set; } = new();
30
+ public List<PredictionCache.CachedPrediction> cache { get; internal set; } = new();
31
31
 
32
32
  /// <summary>
33
33
  /// Settings instance for this project.
@@ -0,0 +1,160 @@
1
+ /*
2
+ * Muna
3
+ * Copyright © 2025 NatML Inc. All rights reserved.
4
+ */
5
+
6
+ #nullable enable
7
+
8
+ namespace Muna.Internal {
9
+
10
+ using System;
11
+ using System.IO;
12
+ using System.Security.Cryptography;
13
+ using System.Text;
14
+ using UnityEngine;
15
+ using Newtonsoft.Json;
16
+ using Services;
17
+
18
+ internal static class PredictionCache {
19
+
20
+ #region --Types--
21
+ /// <summary>
22
+ /// Cached prediction.
23
+ /// </summary>
24
+ [Preserve, Serializable]
25
+ internal class CachedPrediction : Prediction {
26
+ public string? clientId;
27
+ public string? configurationId;
28
+
29
+ [Preserve]
30
+ public CachedPrediction() { }
31
+ }
32
+ #endregion
33
+
34
+
35
+ #region --Client API--
36
+ /// <summary>
37
+ /// Add a prediction to the cache.
38
+ /// </summary>
39
+ public static void Add(CachedPrediction prediction) {
40
+ var path = GetCachedPath(prediction);
41
+ var json = JsonConvert.SerializeObject(prediction, Formatting.Indented);
42
+ File.WriteAllText(path, json);
43
+ }
44
+
45
+ /// <summary>
46
+ /// Get a prediction from the cache.
47
+ /// </summary>
48
+ public static bool Get(
49
+ string tag,
50
+ string clientId,
51
+ string configurationId,
52
+ PredictionResource[]? embeddedResources,
53
+ out CachedPrediction? prediction
54
+ ) {
55
+ prediction = null;
56
+ // Check filesystem
57
+ var path = GetCachedPath(tag, clientId, configurationId);
58
+ if (!File.Exists(path))
59
+ return false;
60
+ // Load prediction
61
+ var json = File.ReadAllText(path);
62
+ var result = JsonConvert.DeserializeObject<CachedPrediction>(json)!;
63
+ // Check that resources are valid
64
+ if (!ResourcesAreValid(result.resources!, embeddedResources)) {
65
+ File.Delete(path);
66
+ return false;
67
+ }
68
+ // Pass
69
+ prediction = result;
70
+ return true;
71
+ }
72
+
73
+ /// <summary>
74
+ /// Remove a prediction from the cache.
75
+ /// </summary>
76
+ /// <param name="prediction"></param>
77
+ public static void Remove(CachedPrediction prediction) {
78
+ var path = GetCachedPath(prediction);
79
+ if (File.Exists(path))
80
+ File.Delete(path);
81
+ }
82
+
83
+ /// <summary>
84
+ /// Create a cached prediction from a prediction.
85
+ /// </summary>
86
+ public static CachedPrediction AsCached(
87
+ this Prediction prediction,
88
+ string? clientId = null,
89
+ string? configurationId = null
90
+ ) => new() {
91
+ id = prediction.id,
92
+ tag = prediction.tag,
93
+ created = prediction.created,
94
+ results = prediction.results,
95
+ latency = prediction.latency,
96
+ error = prediction.error,
97
+ logs = prediction.logs,
98
+ resources = prediction.resources,
99
+ configuration = prediction.configuration,
100
+ clientId = clientId,
101
+ configurationId = configurationId
102
+ };
103
+ #endregion
104
+
105
+
106
+ #region --Operations--
107
+ private static string CacheRoot => Application.isEditor ?
108
+ Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), @".fxn") :
109
+ Path.Combine(Application.persistentDataPath, @"fxn");
110
+ internal static string ResourceCachePath => Path.Combine(CacheRoot, @"cache");
111
+ internal static string PredictorCachePath => Path.Combine(CacheRoot, @"predictors");
112
+
113
+ private static string GetCachedPath(CachedPrediction prediction) => GetCachedPath(
114
+ tag: prediction.tag,
115
+ clientId: prediction.clientId!,
116
+ configurationId: prediction.configurationId!
117
+ );
118
+
119
+ private static string GetCachedPath(
120
+ string tag,
121
+ string clientId,
122
+ string configurationId
123
+ ) {
124
+ if (!Directory.Exists(PredictorCachePath))
125
+ Directory.CreateDirectory(PredictorCachePath);
126
+ using var sha256 = new SHA256Managed();
127
+ var identifier = $"{tag}::{clientId}::{configurationId}";
128
+ var identifierData = Encoding.UTF8.GetBytes(identifier);
129
+ var hashData = sha256.ComputeHash(identifierData);
130
+ var hash = BitConverter.ToString(hashData).Replace("-", "").ToLower();
131
+ var path = Path.Combine(PredictorCachePath, $"{hash}.json");
132
+ return path;
133
+ }
134
+
135
+ private static bool ResourcesAreValid(
136
+ PredictionResource[] cachedResources,
137
+ PredictionResource[]? embeddedResources
138
+ ) {
139
+ if (embeddedResources != null && cachedResources.Length != embeddedResources.Length)
140
+ return false;
141
+ for (var idx = 0; idx < cachedResources.Length; ++idx) {
142
+ var cachedResource = cachedResources[idx];
143
+ var cachedPath = new Uri(cachedResource.url).LocalPath;
144
+ var embeddedPath = embeddedResources != null ?
145
+ PredictionService.GetResourcePath(embeddedResources[idx], ResourceCachePath) :
146
+ null;
147
+
148
+ Application.SetStackTraceLogType(LogType.Log, StackTraceLogType.None);
149
+ Debug.Log($"Cached path: {cachedPath} Embedded path: {embeddedPath}");
150
+
151
+ if (!File.Exists(cachedPath))
152
+ return false;
153
+ if (embeddedPath != null && cachedPath != embeddedPath)
154
+ return false;
155
+ }
156
+ return true;
157
+ }
158
+ #endregion
159
+ }
160
+ }
@@ -0,0 +1,2 @@
1
+ fileFormatVersion: 2
2
+ guid: d4e0b513297bf4d95935d63a7764c9ba
@@ -46,8 +46,7 @@ namespace Muna {
46
46
  var settings = MunaSettings.Instance!;
47
47
  var client = new PredictionCacheClient(
48
48
  url ?? Muna.URL,
49
- accessKey: accessKey ?? settings?.accessKey,
50
- cache: settings?.cache
49
+ accessKey: accessKey ?? settings?.accessKey
51
50
  );
52
51
  return new Muna(client);
53
52
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai.muna.muna",
3
- "version": "0.0.46",
3
+ "version": "0.0.47",
4
4
  "displayName": "Muna",
5
5
  "description": "Run AI inference in Unity Engine.",
6
6
  "unity": "2022.3",
@@ -1,36 +0,0 @@
1
- /*
2
- * Muna
3
- * Copyright © 2025 NatML Inc. All rights reserved.
4
- */
5
-
6
- #nullable enable
7
-
8
- namespace Muna {
9
-
10
- using System;
11
-
12
- /// <summary>
13
- /// Cached prediction.
14
- /// </summary>
15
- [Preserve, Serializable]
16
- internal class CachedPrediction : Prediction {
17
-
18
- public string? clientId;
19
-
20
- [Preserve]
21
- public CachedPrediction() { }
22
-
23
- public CachedPrediction(Prediction prediction, string clientId) {
24
- this.id = prediction.id;
25
- this.tag = prediction.tag;
26
- this.created = prediction.created;
27
- this.results = prediction.results;
28
- this.latency = prediction.latency;
29
- this.error = prediction.error;
30
- this.logs = prediction.logs;
31
- this.resources = prediction.resources;
32
- this.configuration = prediction.configuration;
33
- this.clientId = clientId;
34
- }
35
- }
36
- }
@@ -1,11 +0,0 @@
1
- fileFormatVersion: 2
2
- guid: 7b5e913e3117a442abc1345c156f136d
3
- MonoImporter:
4
- externalObjects: {}
5
- serializedVersion: 2
6
- defaultReferences: []
7
- executionOrder: 0
8
- icon: {instanceID: 0}
9
- userData:
10
- assetBundleName:
11
- assetBundleVariant:
package/Unity/Types.meta DELETED
@@ -1,8 +0,0 @@
1
- fileFormatVersion: 2
2
- guid: 0c449c8b8a355457aa40b183e847e588
3
- folderAsset: yes
4
- DefaultImporter:
5
- externalObjects: {}
6
- userData:
7
- assetBundleName:
8
- assetBundleVariant: