using System.IO;
using Unity.InferenceEngine;
using UnityEngine;
using UnityEngine.Networking;
namespace Audio2Face
{
///
/// Finds and loads the network with no setup step (same scheme as com.sky.sentis.neurosync):
/// - Editor: the ONNX in the package's Models folder, imported as a ModelAsset.
/// - Player: StreamingAssets/Audio2Face/audio2face3d_v3.sentis, written there by the package's build hook for the
/// duration of each build (Float16 weights by default, see A2FBuildSettings).
/// A .sentis you place in StreamingAssets/Audio2Face/ yourself wins in both.
///
public static class A2FModel
{
public const string PackageName = "com.sky.sentis.audio2face";
public const string StreamingAssetsFolder = "Audio2Face";
public const string BaseName = "audio2face3d_v3";
public static string StreamingAssetsPath => SentisPath(BaseName);
public static string PackagedOnnxAssetPath => OnnxAssetPath(BaseName);
static string SentisPath(string baseName) => Path.Combine(Application.streamingAssetsPath, StreamingAssetsFolder, baseName + ".sentis");
static string OnnxAssetPath(string baseName) => $"Packages/{PackageName}/Models/{baseName}.onnx";
#if UNITY_EDITOR
public static ModelAsset PackagedModelAsset => UnityEditor.AssetDatabase.LoadAssetAtPath(PackagedOnnxAssetPath);
#endif
/// The Audio2Face-3D network.
public static Awaitable LoadAsync() => LoadAsync(BaseName);
static async Awaitable LoadAsync(string baseName)
{
var path = SentisPath(baseName);
#if UNITY_EDITOR
if (!File.Exists(path))
{
var onnx = OnnxAssetPath(baseName);
var asset = UnityEditor.AssetDatabase.LoadAssetAtPath(onnx);
if (asset == null)
throw new FileNotFoundException(
$"Audio2Face model not found: {onnx}. If the package came from git, install git-lfs and re-resolve it.");
return ModelLoader.Load(asset);
}
#endif
if (path.Contains("://"))
{
// Android / WebGL keep StreamingAssets inside the app package or on a server.
using var req = UnityWebRequest.Get(path);
await req.SendWebRequest();
if (req.result != UnityWebRequest.Result.Success)
throw new FileNotFoundException($"Audio2Face model not loaded from {path}: {req.error}");
using var ms = new MemoryStream(req.downloadHandler.data);
return ModelLoader.Load(ms);
}
if (!File.Exists(path))
throw new FileNotFoundException($"Audio2Face model not found: {path}");
return ModelLoader.Load(path);
}
}
}