using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Drawing.Imaging; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Net.NetworkInformation; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using System.Web.Script.Serialization; using System.Windows.Forms; using System.Windows.Forms.Layout; using Microsoft.CodeAnalysis; using Microsoft.Win32; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: AssemblyCompany("BingBongHelper")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("0.1.0.0")] [assembly: AssemblyInformationalVersion("0.1.0")] [assembly: AssemblyProduct("BingBongHelper")] [assembly: AssemblyTitle("Bing Bong AI helpers")] [assembly: AssemblyVersion("0.1.0.0")] [module: RefSafetyRules(11)] [CompilerGenerated] internal sealed class <>z__ReadOnlyArray : IEnumerable, ICollection, IList, IEnumerable, IReadOnlyCollection, IReadOnlyList, ICollection, IList { int ICollection.Count => _items.Length; bool ICollection.IsSynchronized => false; object ICollection.SyncRoot => this; object IList.this[int index] { get { return _items[index]; } set { throw new NotSupportedException(); } } bool IList.IsFixedSize => true; bool IList.IsReadOnly => true; int IReadOnlyCollection.Count => _items.Length; T IReadOnlyList.this[int index] => _items[index]; int ICollection.Count => _items.Length; bool ICollection.IsReadOnly => true; T IList.this[int index] { get { return _items[index]; } set { throw new NotSupportedException(); } } public <>z__ReadOnlyArray(T[] items) { _items = items; } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)_items).GetEnumerator(); } void ICollection.CopyTo(Array array, int index) { ((ICollection)_items).CopyTo(array, index); } int IList.Add(object value) { throw new NotSupportedException(); } void IList.Clear() { throw new NotSupportedException(); } bool IList.Contains(object value) { return ((IList)_items).Contains(value); } int IList.IndexOf(object value) { return ((IList)_items).IndexOf(value); } void IList.Insert(int index, object value) { throw new NotSupportedException(); } void IList.Remove(object value) { throw new NotSupportedException(); } void IList.RemoveAt(int index) { throw new NotSupportedException(); } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)_items).GetEnumerator(); } void ICollection.Add(T item) { throw new NotSupportedException(); } void ICollection.Clear() { throw new NotSupportedException(); } bool ICollection.Contains(T item) { return ((ICollection)_items).Contains(item); } void ICollection.CopyTo(T[] array, int arrayIndex) { ((ICollection)_items).CopyTo(array, arrayIndex); } bool ICollection.Remove(T item) { throw new NotSupportedException(); } int IList.IndexOf(T item) { return ((IList)_items).IndexOf(item); } void IList.Insert(int index, T item) { throw new NotSupportedException(); } void IList.RemoveAt(int index) { throw new NotSupportedException(); } } namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace BingBongHelper { internal static class Text { private static readonly Dictionary> s_tables = new Dictionary>(); private static string SystemLanguage { get { CultureInfo currentUICulture = CultureInfo.CurrentUICulture; if (currentUICulture.TwoLetterISOLanguageName == "ru") { return "ru"; } if (currentUICulture.TwoLetterISOLanguageName != "zh") { return "en"; } string name = currentUICulture.Name; if (!name.Contains("Hant") && !name.EndsWith("-TW") && !name.EndsWith("-HK") && !name.EndsWith("-MO")) { return "zh-hans"; } return "zh-hant"; } } public static string Language { get; private set; } = SystemLanguage; public static string FontName { get { string language = Language; if (!(language == "zh-hans")) { if (language == "zh-hant") { return "Microsoft JhengHei UI"; } return "Segoe UI"; } return "Microsoft YaHei UI"; } } public static void Use(string language) { bool flag; switch (language) { case "ru": case "en": case "zh-hans": case "zh-hant": flag = true; break; default: flag = false; break; } Language = (flag ? language : SystemLanguage); } public static string T(string russian, string english) { string language = Language; if (!(language == "ru")) { if (language == "en") { return english; } string value; return Table(Language).TryGetValue(english, out value) ? value : english; } return russian; } private static Dictionary Table(string language) { //IL_0050: Unknown result type (might be due to invalid IL or missing references) if (s_tables.TryGetValue(language, out Dictionary value)) { return value; } value = new Dictionary(StringComparer.Ordinal); try { using Stream stream = typeof(Text).Assembly.GetManifestResourceStream("Lang." + language + ".json"); if (stream != null) { using StreamReader streamReader = new StreamReader(stream, Encoding.UTF8); value = new JavaScriptSerializer().Deserialize>(streamReader.ReadToEnd()) ?? value; } } catch (Exception) { } s_tables[language] = value; return value; } } internal enum ServerState { Off, Starting, Running, External, Failed, Missing } internal abstract class LocalService { private readonly Func _title; public string Name { get; } public string Title => _title(); public int Port { get; protected set; } public string LogPath { get; } public string Address => $"http://localhost:{Port}/v1"; public ServerState State { get; protected set; } public string Detail { get; protected set; } = ""; public abstract bool Owned { get; } public virtual bool StartsWithOthers => true; public double? LastSeconds { get; protected set; } public double? LastSpeechSeconds { get; protected set; } public DateTime? LastAt { get; protected set; } protected LocalService(string name, Func title, int port, string logFile) { Name = name; _title = title; Port = port; LogPath = Path.Combine(Services.Logs, logFile); } public abstract void Start(); public abstract void Stop(); public abstract void Refresh(bool detailed, ISet listening); public abstract (long Ram, long? Video) Memory(); protected static (long Ram, long? Video) MemoryOf(ICollection ids) { long num = 0L; foreach (int id in ids) { try { using Process process = Process.GetProcessById(id); num += process.WorkingSet64; } catch (ArgumentException) { } } return (Ram: num, Video: (ids.Count > 0) ? GpuMemory.Dedicated(ids) : ((long?)null)); } } internal sealed class Launch { public ProcessStartInfo? Start { get; } public string Detail { get; } public int Port { get; } public Launch(ProcessStartInfo? start, string detail, int port) { Start = start; Detail = detail; Port = port; } } internal sealed class ProcessService : LocalService { private readonly Func _prepare; private Process? _process; private JobObject? _job; private StreamWriter? _log; private bool _stopping; private string _lastLine = ""; private long _questionStarted; private double _questionSeconds; private static readonly Regex s_whisperStart = new Regex("processing '[^']*' \\(\\d+ samples, ([\\d.]+) sec\\)"); private static readonly Regex s_piperDone = new Regex(": \\d+ letters, ([\\d.]+) s of speech in ([\\d.]+) s"); public override bool Owned { get { if (_process != null) { return !_process.HasExited; } return false; } } public ProcessService(string name, Func title, int port, string logFile, Func prepare) : base(name, title, port, logFile) { _prepare = prepare; } public override void Start() { if (Owned || base.State == ServerState.External) { return; } Launch launch = _prepare(); base.Detail = launch.Detail; base.Port = launch.Port; ProcessStartInfo start = launch.Start; if (start == null) { base.State = ServerState.Missing; return; } start.UseShellExecute = false; start.CreateNoWindow = true; start.RedirectStandardOutput = true; start.RedirectStandardError = true; start.StandardOutputEncoding = Encoding.UTF8; start.StandardErrorEncoding = Encoding.UTF8; Directory.CreateDirectory(Path.GetDirectoryName(base.LogPath)); _log = new StreamWriter(base.LogPath, append: false, Encoding.UTF8) { AutoFlush = true }; _log.WriteLine($"[{DateTime.Now:HH:mm:ss}] {start.FileName} {start.Arguments}"); _stopping = false; _lastLine = ""; _process = new Process { StartInfo = start, EnableRaisingEvents = true }; _process.OutputDataReceived += delegate(object _, DataReceivedEventArgs e) { Write(e.Data); }; _process.ErrorDataReceived += delegate(object _, DataReceivedEventArgs e) { Write(e.Data); }; try { _process.Start(); } catch (Win32Exception ex) { Write(ex.Message); _process = null; base.State = ServerState.Missing; base.Detail = Text.T("не запускается: ", "does not start: ") + ex.Message; return; } _job = new JobObject(); _job.Add(_process); _process.BeginOutputReadLine(); _process.BeginErrorReadLine(); base.State = ServerState.Starting; } public override void Stop() { _stopping = true; try { _job?.Terminate(); if (Owned) { _process.WaitForExit(3000); } } catch (InvalidOperationException) { } _job?.Dispose(); _job = null; Write($"[{DateTime.Now:HH:mm:ss}] stopped"); _process = null; } public override void Refresh(bool detailed, ISet ports) { if (base.State == ServerState.Missing && !Owned) { return; } bool flag = ports.Contains(base.Port); if (Owned) { base.State = ((!flag) ? ServerState.Starting : ServerState.Running); } else if (_process != null && !_stopping) { if (base.State != ServerState.Failed) { base.Detail = Explain(_lastLine); } base.State = ServerState.Failed; } else { base.State = (flag ? ServerState.External : ServerState.Off); } } private static string Explain(string line) { if (line.Contains("vc_redist")) { return Text.T("нужна библиотека Microsoft Visual C++ (x64): aka.ms/vs/17/release/vc_redist.x64.exe – установи и запусти снова", "it needs Microsoft Visual C++ (x64): aka.ms/vs/17/release/vc_redist.x64.exe; install it and start again"); } if (line.StartsWith("Cannot listen on", StringComparison.Ordinal) || line.Contains("10048")) { return Text.T("порт занят другой программой", "another program holds the port"); } if (line.Length <= 200) { return line; } return line.Substring(0, 200) + "…"; } public override (long Ram, long? Video) Memory() { return LocalService.MemoryOf(_job?.ProcessIds() ?? new List()); } private void Write(string? line) { if (line == null) { return; } if (line.Trim().Length > 0 && !_stopping) { _lastLine = line.Trim(); } Measure(line); lock (this) { try { _log?.WriteLine(line); } catch (ObjectDisposedException) { } } } private void Measure(string line) { Match match = s_whisperStart.Match(line); if (match.Success) { _questionSeconds = double.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture); _questionStarted = Stopwatch.GetTimestamp(); return; } if (_questionStarted != 0L && line.Contains("progress = 100%")) { base.LastSeconds = (double)(Stopwatch.GetTimestamp() - _questionStarted) / (double)Stopwatch.Frequency; base.LastSpeechSeconds = _questionSeconds; base.LastAt = DateTime.Now; _questionStarted = 0L; return; } Match match2 = s_piperDone.Match(line); if (match2.Success) { base.LastSpeechSeconds = double.Parse(match2.Groups[1].Value, CultureInfo.InvariantCulture); base.LastSeconds = double.Parse(match2.Groups[2].Value, CultureInfo.InvariantCulture); base.LastAt = DateTime.Now; } } } internal static class Ports { public static HashSet Listening() { try { HashSet hashSet = new HashSet(); foreach (int item in from endpoint in IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners() select endpoint.Port) { hashSet.Add(item); } return hashSet; } catch (NetworkInformationException) { return new HashSet(); } } } internal static class Services { private static readonly bool s_portable = File.Exists(Path.Combine(Root, "helper.ini")); public static string Root => AppDomain.CurrentDomain.BaseDirectory; public static string Data { get { if (!s_portable) { return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "BingBongAI", "helper"); } return Root; } } public static string SettingsPath => Path.Combine(Data, "helper.ini"); public static string Logs => Path.Combine(Data, "logs"); public static string VoiceExe => Path.Combine(Root, "BingBongVoice.exe"); public static string LocalWhisperServer => Path.Combine(Root, "whisper", "bin", "whisper-server.exe"); public static string LocalWhisperModels => Path.Combine(Root, "whisper", "models"); public static string LocalVoices => Path.Combine(Root, "piper", "voices"); public static string LocalPython => Path.Combine(Root, "piper", "venv", "Scripts", "python.exe"); public static string DefaultVoices => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "BingBongAI", "voices"); public static string? OllamaPath { get { string text = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Programs", "Ollama", "ollama.exe"); if (!File.Exists(text)) { return null; } return text; } } public static List<(string Label, bool Complete)> PiperVoices(string folder) { if (!Directory.Exists(folder)) { return new List<(string, bool)>(); } return (from f in Directory.GetFiles(folder, "*.onnx") orderby f select f).Select(delegate(string file) { string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(file); string[] array = fileNameWithoutExtension.Split(new char[1] { '-' }); return ((array.Length == 3) ? (array[1] + " (" + array[0] + ", " + array[2] + ")") : fileNameWithoutExtension, File.Exists(file + ".json")); }).ToList(); } public static LocalService Whisper(HelperSettings settings) { return new ProcessService("whisper", () => Text.T("Распознавание речи (Whisper)", "Speech recognition (Whisper)"), 8080, "whisper.log", () => settings.CustomLaunch("whisper", 8080) ?? BuiltInWhisper(settings)); } public static LocalService Piper(HelperSettings settings) { return new ProcessService("piper", () => Text.T("Голос Бинг-Бонга (Piper)", "Bing Bong's voice (Piper)"), 8000, "piper.log", delegate { Launch launch = settings.CustomLaunch("piper", 8000); if (launch == null) { if (!(settings.VoiceEngine == "python")) { return BuiltInVoice(settings); } launch = PythonPiper(settings); } return launch; }); } public static LocalService? TextAi(HelperSettings settings) { return settings.LlmKind switch { "lmstudio" => new LmStudioService(settings), "ollama" => new ProcessService("ollama", () => Text.T("Текстовая нейросеть (Ollama)", "Text AI (Ollama)"), 11434, "ollama.log", Ollama), "custom" => new ProcessService("textai", () => Text.T("Текстовая нейросеть (своя программа)", "Text AI (own program)"), settings.Number("llm.port", 1234), "textai.log", () => settings.CustomLaunch("llm", 1234) ?? new Launch(null, Text.T("укажи программу в «Настройках»", "choose the program in Settings"), settings.Number("llm.port", 1234))), _ => null, }; } public static List WhisperModels(string folder) { if (!Directory.Exists(folder)) { return new List(); } return (from f in Directory.GetFiles(folder, "ggml-*.bin") orderby Path.GetFileName(f).Contains("large-v3-turbo") descending, f select f).ToList(); } private static Launch Missing(string what, int port) { return new Launch(null, what, port); } private static Launch BuiltInWhisper(HelperSettings settings) { string whisperServer = settings.WhisperServer; if (whisperServer.Length == 0) { return Missing(Text.T("укажи whisper-server.exe в «Настройках»", "choose whisper-server.exe in Settings"), 8080); } if (!File.Exists(whisperServer)) { return Missing(Text.T("не нашёл ", "not found: ") + whisperServer, 8080); } string whisperModelFile = settings.WhisperModelFile; if (whisperModelFile.Length == 0) { return Missing(Text.T("укажи модель (ggml-….bin) в «Настройках»", "choose a model (ggml-….bin) in Settings"), 8080); } if (!File.Exists(whisperModelFile)) { return Missing(Text.T("не нашёл модель ", "model not found: ") + whisperModelFile, 8080); } string directoryName = Path.GetDirectoryName(whisperServer); bool flag = settings.WhisperDevice != "cpu" && File.Exists(Path.Combine(directoryName, "cublas64_12.dll")); string arguments = "-m \"" + whisperModelFile + "\" --host 127.0.0.1 --port 8080 --inference-path /v1/audio/transcriptions -l auto -pp" + (flag ? "" : " -ng -t 12 -ac 768"); string text = Path.GetFileName(whisperModelFile).Replace("ggml-", "").Replace(".bin", ""); return new Launch(new ProcessStartInfo(whisperServer, arguments) { WorkingDirectory = directoryName }, (flag ? Text.T("видеокарта", "graphics card") : Text.T("процессор", "processor")) + " · " + text, 8080); } private static (string[] Voices, Launch? Missing) VoicesIn(string folder) { string[] array = (Directory.Exists(folder) ? (from f in Directory.GetFiles(folder, "*.onnx") where File.Exists(f + ".json") select f).ToArray() : Array.Empty()); if (array.Length == 0) { return (Voices: Array.Empty(), Missing: Missing(Text.T("в папке голосов пусто – добавь голос (в «Настройках»: «Голос»)", "the voices folder is empty: add a voice (Settings, Voice)"), 8000)); } return (Voices: array, Missing: null); } private static string VoiceNames(string[] onnx) { return Text.T("голоса: ", "voices: ") + string.Join(", ", onnx.Select((string f) => Path.GetFileNameWithoutExtension(f).Split(new char[1] { '-' }).ElementAtOrDefault(1) ?? Path.GetFileNameWithoutExtension(f))); } private static Launch BuiltInVoice(HelperSettings settings) { if (!File.Exists(VoiceExe)) { return Missing(Text.T("нет BingBongVoice.exe рядом с помощником – выбери в «Настройках» Piper через Python", "BingBongVoice.exe is not next to the helper: choose Piper through Python in Settings"), 8000); } string voicesFolder = settings.VoicesFolder; var (onnx, launch) = VoicesIn(voicesFolder); if (launch != null) { return launch; } return new Launch(new ProcessStartInfo(VoiceExe, "--voices \"" + voicesFolder.TrimEnd(new char[1] { '\\' }) + "\" --port 8000") { WorkingDirectory = Root }, VoiceNames(onnx), 8000); } private static Launch PythonPiper(HelperSettings settings) { string piperPython = settings.PiperPython; if (piperPython.Length == 0) { return Missing(Text.T("укажи python.exe (с piper-tts) в «Настройках»", "choose python.exe (with piper-tts) in Settings"), 8000); } if (!File.Exists(piperPython)) { return Missing(Text.T("не нашёл ", "not found: ") + piperPython, 8000); } string text = new string[3] { Path.Combine(Root, "piper_server.py"), Path.Combine(Root, "piper", "piper_server.py"), Path.GetFullPath(Path.Combine(Root, "..", "BingBongAI", "tools", "PiperServer", "piper_server.py")) }.FirstOrDefault(File.Exists); if (text == null) { return Missing(Text.T("нет piper_server.py рядом с помощником", "piper_server.py is not next to the helper"), 8000); } string voicesFolder = settings.VoicesFolder; var (onnx, launch) = VoicesIn(voicesFolder); if (launch != null) { return launch; } ProcessStartInfo processStartInfo = new ProcessStartInfo(piperPython, "-u \"" + text + "\" --voices \"" + voicesFolder.TrimEnd(new char[1] { '\\' }) + "\" --port 8000"); processStartInfo.WorkingDirectory = Path.GetDirectoryName(text); processStartInfo.EnvironmentVariables["PYTHONIOENCODING"] = "utf-8"; return new Launch(processStartInfo, "Python · " + VoiceNames(onnx), 8000); } private static Launch Ollama() { string ollamaPath = OllamaPath; if (ollamaPath == null) { return new Launch(null, Text.T("Ollama не установлен", "Ollama is not installed"), 11434); } ProcessStartInfo processStartInfo = new ProcessStartInfo(ollamaPath, "serve"); processStartInfo.EnvironmentVariables["OLLAMA_HOST"] = "127.0.0.1:11434"; return new Launch(processStartInfo, Text.T("модель загрузится с первым вопросом", "the model loads with the first question"), 11434); } } internal sealed class JobObject : IDisposable { private struct JOBOBJECT_BASIC_LIMIT_INFORMATION { public long PerProcessUserTimeLimit; public long PerJobUserTimeLimit; public uint LimitFlags; public UIntPtr MinimumWorkingSetSize; public UIntPtr MaximumWorkingSetSize; public uint ActiveProcessLimit; public UIntPtr Affinity; public uint PriorityClass; public uint SchedulingClass; } private struct IO_COUNTERS { public ulong ReadOperationCount; public ulong WriteOperationCount; public ulong OtherOperationCount; public ulong ReadTransferCount; public ulong WriteTransferCount; public ulong OtherTransferCount; } private struct JOBOBJECT_EXTENDED_LIMIT_INFORMATION { public JOBOBJECT_BASIC_LIMIT_INFORMATION BasicLimitInformation; public IO_COUNTERS IoInfo; public UIntPtr ProcessMemoryLimit; public UIntPtr JobMemoryLimit; public UIntPtr PeakProcessMemoryUsed; public UIntPtr PeakJobMemoryUsed; } private IntPtr _handle; public JobObject() { _handle = CreateJobObject(IntPtr.Zero, null); JOBOBJECT_EXTENDED_LIMIT_INFORMATION structure = new JOBOBJECT_EXTENDED_LIMIT_INFORMATION { BasicLimitInformation = { LimitFlags = 8192u } }; int num = Marshal.SizeOf(structure); IntPtr intPtr = Marshal.AllocHGlobal(num); try { Marshal.StructureToPtr(structure, intPtr, fDeleteOld: false); SetInformationJobObject(_handle, 9, intPtr, (uint)num); } finally { Marshal.FreeHGlobal(intPtr); } } public void Add(Process process) { if (_handle != IntPtr.Zero) { AssignProcessToJobObject(_handle, process.Handle); } } public List ProcessIds() { List list = new List(); if (_handle == IntPtr.Zero) { return list; } int num = 8 + 64 * IntPtr.Size; IntPtr intPtr = Marshal.AllocHGlobal(num); try { if (QueryInformationJobObject(_handle, 3, intPtr, (uint)num, IntPtr.Zero)) { int val = Marshal.ReadInt32(intPtr, 4); for (int i = 0; i < Math.Min(val, 64); i++) { list.Add((int)Marshal.ReadIntPtr(intPtr, 8 + i * IntPtr.Size).ToInt64()); } } } finally { Marshal.FreeHGlobal(intPtr); } return list; } public void Terminate() { if (_handle != IntPtr.Zero) { TerminateJobObject(_handle, 1u); } } public void Dispose() { if (_handle != IntPtr.Zero) { CloseHandle(_handle); } _handle = IntPtr.Zero; } [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] private static extern IntPtr CreateJobObject(IntPtr attributes, string? name); [DllImport("kernel32.dll")] private static extern bool SetInformationJobObject(IntPtr job, int infoClass, IntPtr info, uint length); [DllImport("kernel32.dll")] private static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process); [DllImport("kernel32.dll")] private static extern bool TerminateJobObject(IntPtr job, uint exitCode); [DllImport("kernel32.dll")] private static extern bool QueryInformationJobObject(IntPtr job, int infoClass, IntPtr info, uint length, IntPtr returnLength); [DllImport("kernel32.dll")] private static extern bool CloseHandle(IntPtr handle); } internal static class GpuMemory { private static bool? s_available; public static long? Dedicated(ICollection processIds) { //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Expected O, but got Unknown try { bool valueOrDefault = s_available == true; if (!s_available.HasValue) { valueOrDefault = PerformanceCounterCategory.Exists("GPU Process Memory"); s_available = valueOrDefault; } if (s_available != true) { return null; } InstanceDataCollection val = new PerformanceCounterCategory("GPU Process Memory").ReadCategory()["Dedicated Usage"]; if (val == null) { return null; } long num = 0L; foreach (InstanceData value in val.Values) { InstanceData val2 = value; string instanceName = val2.InstanceName; int num2 = instanceName.IndexOf('_', 4); if (instanceName.StartsWith("pid_", StringComparison.Ordinal) && num2 > 4 && int.TryParse(instanceName.Substring(4, num2 - 4), out var result) && processIds.Contains(result)) { num += val2.RawValue; } } return num; } catch (Exception ex) when (((ex is InvalidOperationException || ex is UnauthorizedAccessException || ex is Win32Exception) ? 1 : 0) != 0) { return null; } } } internal static class Program { [STAThread] private static int Main(string[] args) { //IL_0095: Unknown result type (might be due to invalid IL or missing references) HelperSettings helperSettings = new HelperSettings(Services.SettingsPath); Text.Use(helperSettings.Language); Theme.Use(helperSettings.Theme); if (args.Contains("--check")) { return Check(helperSettings); } if (args.Contains("--check-lms")) { return CheckLmStudio(helperSettings); } int num = Array.IndexOf(args, "--screenshot"); if (num >= 0 && num + 1 < args.Length) { return Screenshots(helperSettings, args[num + 1]); } bool createdNew; using (new Mutex(initiallyOwned: true, "BingBongAI.LocalHelper", out createdNew)) { if (!createdNew) { MessageBox.Show(Text.T("Помощник уже открыт: он в трее возле часов.", "The helper is already open: it is in the tray next to the clock."), "Bing Bong AI", (MessageBoxButtons)0, (MessageBoxIcon)64); return 0; } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run((Form)(object)new HelperForm(helperSettings)); return 0; } } private static int Check(HelperSettings settings) { StringBuilder stringBuilder = new StringBuilder(); bool flag = true; LocalService[] array = new LocalService[2] { Services.Whisper(settings), Services.Piper(settings) }; Directory.CreateDirectory(Services.Logs); string path = Path.Combine(Services.Logs, "check-ready.txt"); File.Delete(path); Stopwatch stopwatch = Stopwatch.StartNew(); LocalService[] array2 = array; for (int i = 0; i < array2.Length; i++) { array2[i].Start(); } do { Thread.Sleep(250); HashSet listening = Ports.Listening(); array2 = array; for (int i = 0; i < array2.Length; i++) { array2[i].Refresh(detailed: true, listening); } } while (array.Any((LocalService s) => s.State == ServerState.Starting) && stopwatch.Elapsed.TotalSeconds < 30.0); array2 = array; foreach (LocalService localService in array2) { flag &= localService.State == ServerState.Running; stringBuilder.AppendLine($"{localService.Name}: {localService.State} after {stopwatch.Elapsed.TotalSeconds:0.0} s ({localService.Detail})"); } File.WriteAllText(path, "ready"); Stopwatch stopwatch2 = Stopwatch.StartNew(); while (array.Any((LocalService s) => !s.LastSeconds.HasValue) && stopwatch2.Elapsed.TotalSeconds < 60.0) { Thread.Sleep(250); } array2 = array; foreach (LocalService localService2 in array2) { (long Ram, long? Video) tuple = localService2.Memory(); long item = tuple.Ram; long? item2 = tuple.Video; double? lastSeconds = localService2.LastSeconds; object obj; if (lastSeconds.HasValue) { double valueOrDefault = lastSeconds.GetValueOrDefault(); obj = $"last request {valueOrDefault:0.00} s for {localService2.LastSpeechSeconds:0.0} s of speech"; } else { obj = "no request came"; } string text = (string)obj; object[] obj2 = new object[4] { localService2.Name, item >> 20, null, null }; object obj3; if (item2.HasValue) { long valueOrDefault2 = item2.GetValueOrDefault(); obj3 = (valueOrDefault2 >> 20) + " MB"; } else { obj3 = "unknown"; } obj2[2] = obj3; obj2[3] = text; stringBuilder.AppendLine(string.Format("{0}: {1} MB RAM, {2} video memory; {3}", obj2)); } array2 = array; for (int i = 0; i < array2.Length; i++) { array2[i].Stop(); } Thread.Sleep(500); HashSet listening2 = Ports.Listening(); array2 = array; foreach (LocalService localService3 in array2) { localService3.Refresh(detailed: false, listening2); bool flag2 = localService3.State == ServerState.Off; flag = flag && flag2; stringBuilder.AppendLine(string.Format("{0}: after Stop {1} {2}", localService3.Name, localService3.State, flag2 ? "ok" : "FAIL")); } File.Delete(path); File.WriteAllText(Path.Combine(Services.Logs, "check.txt"), stringBuilder.ToString()); return (!flag) ? 1 : 0; } private static int CheckLmStudio(HelperSettings settings) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine("lms: " + (LmStudioCli.Path ?? "not found")); List list = LmStudioCli.ListModels(); stringBuilder.AppendLine("models: " + string.Join(" | ", list.Select((LmModel m) => m.Key + " = " + m.Label))); if (list.Count > 0) { stringBuilder.AppendLine($"estimate {list[0].Key} @ {settings.LlmContext}: {LmStudioCli.EstimateGpuGb(list[0].Key, settings.LlmContext, settings.LlmGpu)} GiB"); } stringBuilder.AppendLine("server start: " + LmStudioCli.Run("server start --port 1234", 60).Output.Trim()); LmStudioService lmStudioService = new LmStudioService(settings); lmStudioService.Refresh(detailed: true, Ports.Listening()); stringBuilder.AppendLine($"service: {lmStudioService.State} · {lmStudioService.Detail}"); Stopwatch stopwatch = Stopwatch.StartNew(); lmStudioService.Memory(); long elapsedMilliseconds = stopwatch.ElapsedMilliseconds; stopwatch.Restart(); (long Ram, long? Video) tuple = lmStudioService.Memory(); long item = tuple.Ram; long? item2 = tuple.Video; object[] obj = new object[4] { item >> 20, null, null, null }; object obj2; if (item2.HasValue) { long valueOrDefault = item2.GetValueOrDefault(); obj2 = (valueOrDefault >> 20) + " MB"; } else { obj2 = "unknown"; } obj[1] = obj2; obj[2] = elapsedMilliseconds; obj[3] = stopwatch.ElapsedMilliseconds; stringBuilder.AppendLine(string.Format("LM Studio memory: {0} MB RAM, {1} video (first {2} ms, then {3} ms)", obj)); stringBuilder.AppendLine("server stop: " + LmStudioCli.Run("server stop", 30).Output.Trim()); File.WriteAllText(Path.Combine(Services.Logs, "check-lms.txt"), stringBuilder.ToString()); return 0; } private static int Screenshots(HelperSettings settings, string folder) { //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Expected O, but got Unknown Directory.CreateDirectory(folder); Application.SetUnhandledExceptionMode((UnhandledExceptionMode)2); Application.ThreadException += delegate(object _, ThreadExceptionEventArgs e) { File.AppendAllText(Path.Combine(folder, "errors.txt"), e.Exception?.ToString() + Environment.NewLine); }; Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); WindowsFormsSynchronizationContext.AutoInstall = false; SynchronizationContext.SetSynchronizationContext((SynchronizationContext?)new WindowsFormsSynchronizationContext()); string[] array = new string[2] { "light", "dark" }; foreach (string text in array) { Theme.Use(text); HelperForm helperForm = new HelperForm(settings, autostart: false); ((Form)helperForm).StartPosition = (FormStartPosition)0; ((Form)helperForm).Location = new Point(-6000, -6000); ((Form)helperForm).ShowInTaskbar = false; HelperForm helperForm2 = helperForm; try { ((Control)helperForm2).Show(); Application.DoEvents(); Save((Form)(object)helperForm2, Path.Combine(folder, "main-" + text + ".png")); SettingsForm settingsForm = new SettingsForm(settings, ((Form)helperForm2).Icon); ((Form)settingsForm).StartPosition = (FormStartPosition)0; ((Form)settingsForm).Location = new Point(-6000, -6000); ((Form)settingsForm).ShowInTaskbar = false; SettingsForm settingsForm2 = settingsForm; try { ((Control)settingsForm2).Show(); Application.DoEvents(); Thread.Sleep(2500); Application.DoEvents(); for (int num2 = 0; num2 < settingsForm2.TabCount; num2++) { settingsForm2.ShowTab(num2); Application.DoEvents(); Save((Form)(object)settingsForm2, Path.Combine(folder, $"settings-{text}-{num2}.png")); } ((Form)settingsForm2).Close(); LogWindow logWindow = new LogWindow(new <>z__ReadOnlyArray(new LocalService[2] { Services.Whisper(settings), Services.Piper(settings) }), ((Form)helperForm2).Icon); ((Form)logWindow).StartPosition = (FormStartPosition)0; ((Form)logWindow).Location = new Point(-6000, -6000); ((Form)logWindow).ShowInTaskbar = false; LogWindow logWindow2 = logWindow; try { ((Control)logWindow2).Show(); Application.DoEvents(); Save((Form)(object)logWindow2, Path.Combine(folder, "logs-" + text + ".png")); ((Form)logWindow2).Close(); ((Form)helperForm2).Close(); } finally { ((IDisposable)(object)logWindow2)?.Dispose(); } } finally { ((IDisposable)(object)settingsForm2)?.Dispose(); } } finally { ((IDisposable)(object)helperForm2)?.Dispose(); } } return 0; static void Save(Form form, string path) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Expected O, but got Unknown Bitmap val = new Bitmap(((Control)form).Width, ((Control)form).Height); try { ((Control)form).DrawToBitmap(val, new Rectangle(0, 0, ((Control)form).Width, ((Control)form).Height)); ((Image)val).Save(path, ImageFormat.Png); } finally { ((IDisposable)val)?.Dispose(); } } } } internal sealed class HelperForm : Form { private readonly HelperSettings _settings; private readonly List _services = new List(); private readonly NotifyIcon _tray; private readonly Timer _timer; private readonly Icon _icon; private Label[] _dots = Array.Empty