| using System; |
| using System.Collections.Generic; |
| using System.Linq; |
| using Microsoft.ML.OnnxRuntime; |
| using Microsoft.ML.OnnxRuntime.Tensors; |
| using UnityEngine; |
|
|
| namespace Sky.OnnxRuntime.Samples |
| { |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| public sealed class ExtensionsSample : MonoBehaviour |
| { |
| |
| |
| |
| private const string ModelBase64 = |
| "CAk6bAoxCgd0ZXh0X2luEgh0ZXh0X291dCILU3RyaW5nVXBwZXI6D2FpLm9ubnguY29udHJpYhIMc3RyaW5nX3VwcGVyWhMKB3RleHRfaW4SCAoGCAgSAgoAYhQKCHRleHRfb3V0EggKBggIEgIKAEIECgAQDUITCg9haS5vbm54LmNvbnRyaWIQAQ=="; |
|
|
| [SerializeField] |
| private string[] _inputs = { "hello unity", "OnnxRuntime" }; |
|
|
| private void Start() |
| { |
| RunStringUpper(); |
| } |
|
|
| |
| public void RunStringUpper() |
| { |
| try |
| { |
| byte[] modelBytes = Convert.FromBase64String(ModelBase64); |
|
|
| using var options = new SessionOptions(); |
|
|
| |
| |
| options.RegisterOrtExtensions(); |
|
|
| using var session = new InferenceSession(modelBytes, options); |
|
|
| var inputTensor = new DenseTensor<string>(_inputs, new int[] { _inputs.Length }); |
| var inputs = new List<NamedOnnxValue> |
| { |
| NamedOnnxValue.CreateFromTensor("text_in", inputTensor) |
| }; |
|
|
| using var results = session.Run(inputs); |
| string[] output = results.First().AsTensor<string>().ToArray(); |
|
|
| Debug.Log($"[ORT Extensions] input = [{string.Join(", ", _inputs)}]"); |
| Debug.Log($"[ORT Extensions] output = [{string.Join(", ", output)}]"); |
|
|
| bool ok = output.Zip(_inputs, (o, i) => o == i.ToUpperInvariant()).All(x => x); |
| if (ok) |
| Debug.Log("[ORT Extensions] StringUpper custom op succeeded ✅"); |
| else |
| Debug.LogError("[ORT Extensions] Unexpected output ❌"); |
| } |
| catch (Exception e) |
| { |
| Debug.LogError( |
| "[ORT Extensions] Failed to run the extensions custom op. Make sure the " + |
| "ONNX Runtime Extensions native library is present for this platform.\n" + e); |
| } |
| } |
| } |
| } |
|
|