File size: 2,330 Bytes
bd48fd1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// Copyright (c) 2026, CIIL Anuvani-LID. Apache-2.0.
// Binding test (see tests/bindings/python_ref.py): the C# API (.NET MAUI, Unity), against the Linux build of
// libsherpa-onnx-c-api.so.
using System;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using SherpaOnnx;

class Program
{
    [StructLayout(LayoutKind.Sequential)]
    struct Wave
    {
        public IntPtr Samples;
        public int SampleRate;
        public int NumSamples;
    }

    [DllImport("sherpa-onnx-c-api")]
    static extern IntPtr SherpaOnnxReadWave([MarshalAs(UnmanagedType.LPStr)] string filename);

    [DllImport("sherpa-onnx-c-api")]
    static extern void SherpaOnnxFreeWave(IntPtr wave);

    static (float[], int) ReadWave(string path)
    {
        IntPtr p = SherpaOnnxReadWave(path);
        Wave w = Marshal.PtrToStructure<Wave>(p);
        float[] samples = new float[w.NumSamples];
        Marshal.Copy(w.Samples, samples, 0, w.NumSamples);
        SherpaOnnxFreeWave(p);
        return (samples, w.SampleRate);
    }

    static void Main(string[] args)
    {
        string model = args[0], vad = args[1], longWav = args[2];

        var modelConfig = new AudioTaggingModelConfig();
        modelConfig.Lid = model;
        modelConfig.NumThreads = 2;

        var config = new AudioTaggingConfig();
        config.Model = modelConfig;
        config.TopK = 23;
        var tagger = new AudioTagging(config);
        foreach (var path in args.Skip(3))
        {
            var (samples, sampleRate) = ReadWave(path);
            var stream = tagger.CreateStream();
            stream.AcceptWaveform(sampleRate, samples);
            var events = tagger.Compute(stream);
            var ev = string.Join(",", events.Select(e => $"[\"{e.Name}\",{e.Index},{e.Prob.ToString("R", System.Globalization.CultureInfo.InvariantCulture)}]"));
            Console.WriteLine($"{{\"file\":\"{Path.GetFileName(path)}\",\"events\":[{ev}]}}");
        }

        var pipelineConfig = new LidPipelineConfig();
        pipelineConfig.Model = modelConfig;
        pipelineConfig.VadModel = vad;
        var pipeline = new LidPipeline(pipelineConfig);
        var (s, sr) = ReadWave(longWav);
        Console.WriteLine($"{{\"pipeline_file\":\"{Path.GetFileName(longWav)}\",\"pipeline\":{pipeline.Process(s, sr)}}}");
    }
}