|
| 1 | +/// Copyright (c) 2024 Xiaomi Corporation (authors: Fangjun Kuang) |
| 2 | + |
| 3 | +using System.Linq; |
| 4 | +using System.Collections.Generic; |
| 5 | +using System.Runtime.InteropServices; |
| 6 | +using System.Text; |
| 7 | +using System; |
| 8 | + |
| 9 | +namespace SherpaOnnx |
| 10 | +{ |
| 11 | + public class OfflinePunctuation : IDisposable |
| 12 | + { |
| 13 | + public OfflinePunctuation(OfflinePunctuationConfig config) |
| 14 | + { |
| 15 | + IntPtr h = SherpaOnnxCreateOfflinePunctuation(ref config); |
| 16 | + _handle = new HandleRef(this, h); |
| 17 | + } |
| 18 | + |
| 19 | + public String AddPunct(String text) |
| 20 | + { |
| 21 | + IntPtr p = SherpaOfflinePunctuationAddPunct(_handle.Handle, text); |
| 22 | + |
| 23 | + string s = ""; |
| 24 | + int length = 0; |
| 25 | + |
| 26 | + unsafe |
| 27 | + { |
| 28 | + byte* b = (byte*)p; |
| 29 | + if (b != null) |
| 30 | + { |
| 31 | + while (*b != 0) |
| 32 | + { |
| 33 | + ++b; |
| 34 | + length += 1; |
| 35 | + } |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + if (length > 0) |
| 40 | + { |
| 41 | + byte[] stringBuffer = new byte[length]; |
| 42 | + Marshal.Copy(p, stringBuffer, 0, length); |
| 43 | + s = Encoding.UTF8.GetString(stringBuffer); |
| 44 | + } |
| 45 | + |
| 46 | + SherpaOfflinePunctuationFreeText(p); |
| 47 | + |
| 48 | + return s; |
| 49 | + } |
| 50 | + |
| 51 | + public void Dispose() |
| 52 | + { |
| 53 | + Cleanup(); |
| 54 | + // Prevent the object from being placed on the |
| 55 | + // finalization queue |
| 56 | + System.GC.SuppressFinalize(this); |
| 57 | + } |
| 58 | + |
| 59 | + ~OfflinePunctuation() |
| 60 | + { |
| 61 | + Cleanup(); |
| 62 | + } |
| 63 | + |
| 64 | + private void Cleanup() |
| 65 | + { |
| 66 | + SherpaOnnxDestroyOfflinePunctuation(_handle.Handle); |
| 67 | + |
| 68 | + // Don't permit the handle to be used again. |
| 69 | + _handle = new HandleRef(this, IntPtr.Zero); |
| 70 | + } |
| 71 | + |
| 72 | + private HandleRef _handle; |
| 73 | + |
| 74 | + |
| 75 | + [DllImport(Dll.Filename)] |
| 76 | + private static extern IntPtr SherpaOnnxCreateOfflinePunctuation(ref OfflinePunctuationConfig config); |
| 77 | + |
| 78 | + [DllImport(Dll.Filename)] |
| 79 | + private static extern void SherpaOnnxDestroyOfflinePunctuation(IntPtr handle); |
| 80 | + |
| 81 | + [DllImport(Dll.Filename)] |
| 82 | + private static extern IntPtr SherpaOfflinePunctuationAddPunct(IntPtr handle, [MarshalAs(UnmanagedType.LPStr)] string text); |
| 83 | + |
| 84 | + [DllImport(Dll.Filename)] |
| 85 | + private static extern void SherpaOfflinePunctuationFreeText(IntPtr p); |
| 86 | + } |
| 87 | +} |
| 88 | + |
0 commit comments