我是 C# 新手 我想在 C# 中制作语音助手并使用 Whisper 进行语音转文本。 我想在 C# 中使用 IronPython 来使用 Python,因为我不能在 C# 中使用 Whisper。
这是我的python代码:
import replicate
import os
os.environ['REPLICATE_API_TOKEN'] = '73xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
model = replicate.models.get("openai/whisper")
version = model.versions.get("30414ee7c4fffc37e260fcab7842b5be470b9b840f2b608f5baa9bbef9a259ed")
inputs = {
'audio': open(r"C:\Users\JAHAN TEEGH\Documents\Sound recordings\Recording.mp3", "rb"),
'model': "large",
'temperature': 0,
'suppress_tokens': "-1",
'condition_on_previous_text': True,
'temperature_increment_on_fallback': 0.2,
'compression_ratio_threshold': 2.4,
'logprob_threshold': -1,
'no_speech_threshold': 0.6,
}
result = version.predict(**inputs)
print(result['segments'][0]['text'])
这是我的 C# 代码:
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
using System;
ScriptEngine engine = Python.CreateEngine();
ScriptSource source = engine.CreateScriptSourceFromFile(@"D:\code\Dastak\stt\py.py");
ScriptScope scope = engine.CreateScope();
source.Execute(scope);
dynamic result = scope.GetVariable("v");
Console.WriteLine(result);
我有这个错误:
Unhandled exception. IronPython.Runtime.Exceptions.ImportException: No module named 'replicate'
at Microsoft.Scripting.Runtime.LightExceptions.ThrowException(LightException lightEx)
at Microsoft.Scripting.Runtime.LightExceptions.CheckAndThrow(Object value)
at Microsoft.Scripting.Interpreter.FuncCallInstruction`2.Run(InterpretedFrame frame)
at Microsoft.Scripting.Interpreter.Interpreter.Run(InterpretedFrame frame)
at Microsoft.Scripting.Interpreter.LightLambda.Run2[T0,T1,TRet](T0 arg0, T1 arg1)
at IronPython.Compiler.PythonScriptCode.RunWorker(CodeContext ctx)
at IronPython.Compiler.PythonScriptCode.Run(Scope scope)
at IronPython.Compiler.RuntimeScriptCode.InvokeTarget(Scope scope)
at IronPython.Compiler.RuntimeScriptCode.Run(Scope scope)
at Microsoft.Scripting.SourceUnit.Execute(Scope scope, ErrorSink errorSink)
at Microsoft.Scripting.SourceUnit.Execute(Scope scope)
at Microsoft.Scripting.Hosting.ScriptSource.Execute(ScriptScope scope)
at Program.<Main>$(String[] args) in D:\code\Dastak\stt\myApp\Program.cs:line 34
虽然我无法帮助您使用 IronPython,但如果您的目标只是从 C# 运行 whisper,我可以建议您使用 PythonNet。
在使用教程https://www.assemblyai.com/blog/how-to-run-openais-whisper-speech-recognition-model/ 中的步骤配置常规 python 库后,我能够运行它。唯一不同的是,我使用以下命令来翻译文本
whisper gettysburg10.wav --model tiny --device cpu --fp16 False
然后我用C#写了下面的代码:
var pythonDllLocation = "C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python38\\python38.dll";
Environment.SetEnvironmentVariable("PYTHONNET_PYDLL", pythonDllLocation);
PythonEngine.Initialize();
using (Py.GIL())
{
var whisper = Py.Import("whisper");
var model = whisper.InvokeMethod("load_model", new PyString("tiny"));
var result = model.InvokeMethod("transcribe", new PyString(tbInputFile.Text));
WriteConsole(result["text"].As<string>());
}
Pythopn38.dll 的路径可能不同。你可以用
where python38.dll
获得它
PythonNet 有 dynamics api,但 fluent 对我来说更舒服一点,尽管它们应该以相同的方式工作。