| using System; |
| using System.IO; |
| using Unity.InferenceEngine; |
| using UnityEngine; |
| using UnityEngine.Networking; |
|
|
| namespace OnDeviceAgent.Inference |
| { |
| public static class StreamingAssetsModelLoader |
| { |
| public static Model LoadModel(string relativePath, string logPrefix) |
| { |
| var path = GetStreamingAssetPath(relativePath); |
| if (CanReadStreamingAssetsWithFileApi() && File.Exists(path)) |
| return ModelLoader.Load(path); |
|
|
| var bytes = LoadBytesFromStreamingAssets(path, logPrefix); |
| using (var stream = new MemoryStream(bytes)) |
| return ModelLoader.Load(stream); |
| } |
|
|
| public static string LoadText(string relativePath, string logPrefix) |
| { |
| var path = GetStreamingAssetPath(relativePath); |
| if (CanReadStreamingAssetsWithFileApi() && File.Exists(path)) |
| return File.ReadAllText(path); |
|
|
| return System.Text.Encoding.UTF8.GetString(LoadBytesFromStreamingAssets(path, logPrefix)); |
| } |
|
|
| public static byte[] LoadBytes(string relativePath, string logPrefix) |
| { |
| var path = GetStreamingAssetPath(relativePath); |
| if (CanReadStreamingAssetsWithFileApi() && File.Exists(path)) |
| return File.ReadAllBytes(path); |
|
|
| return LoadBytesFromStreamingAssets(path, logPrefix); |
| } |
|
|
| static string GetStreamingAssetPath(string relativePath) |
| { |
| return ModelPathResolver.GetModelFilePath(relativePath); |
| } |
|
|
| static bool CanReadStreamingAssetsWithFileApi() |
| { |
| return Application.platform != RuntimePlatform.Android && |
| Application.platform != RuntimePlatform.WebGLPlayer; |
| } |
|
|
| static byte[] LoadBytesFromStreamingAssets(string path, string logPrefix) |
| { |
| using (var request = UnityWebRequest.Get(ToStreamingAssetUri(path))) |
| { |
| var operation = request.SendWebRequest(); |
| |
| while (!operation.isDone) |
| System.Threading.Thread.Sleep(1); |
|
|
| if (request.result != UnityWebRequest.Result.Success) |
| throw new FileNotFoundException($"{logPrefix} Missing StreamingAssets file: {path} ({request.error})", path); |
|
|
| return request.downloadHandler.data; |
| } |
| } |
|
|
| static string ToStreamingAssetUri(string path) |
| { |
| if (path.StartsWith("jar:", StringComparison.OrdinalIgnoreCase) || |
| path.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || |
| path.StartsWith("https://", StringComparison.OrdinalIgnoreCase) || |
| path.StartsWith("file://", StringComparison.OrdinalIgnoreCase)) |
| return path; |
|
|
| return "file://" + path; |
| } |
| } |
| } |
|
|