Ошибка вызова метода - не найден json

Я хочу вызывать метод python (обученная нейронная сеть) из c#. Написал код c# для вызова:

public class SpeechService : IDisposable
{
    private readonly Py.GILState _state;
    private readonly PyObject _getText;

    public SpeechService()
    {
        Runtime.PythonDLL = Path.Combine(Global.Settings.PythonPath, Global.Settings.PythonDll);
        PythonEngine.Initialize();
        _state = Py.GIL();

        var pythonPath = Path.Combine(Environment.CurrentDirectory, "speech.py");
        var locals = new PyDict();
        PythonEngine.Exec(File.ReadAllText(pythonPath), null, locals);
        _getText = locals.GetItem("getTextFromSpeech");
    }

    public string GetText(byte[] mp3)
    {
        var args = new PyObject[] { PyObject.FromManagedObject(mp3) };
        dynamic data = _getText.Invoke(args);

        return default;
    }

    public void Dispose()
    {
        _state.Dispose();
    }
}

Написал код python для получения текста

import os
import json
import magic
import whisper

uploadsFolder = 'uploads'

configPath = os.path.join(os.getcwd(), 'configurations', 'config.json')
try:
    with open(configPath) as config_file:
        config = json.load(config_file)
except FileNotFoundError:
    raise FileNotFoundError(f"config.json not found. Check the current working directory: {configPath}")
except json.JSONDecodeError:
    raise ValueError("Invalid JSON format in config.json")
except Exception as ex:
    raise ex

MODEL = config.get('model')
if not MODEL:
    raise ValueError("Model configuration missing in config.json")

DOWNLOAD_ROOT = os.path.join(os.getcwd(), 'pyModels')

model = whisper.load_model(MODEL, download_root=DOWNLOAD_ROOT)

def is_mp3_file(audio_file):
    try:
        audio_file_bytes = audio_file.read()
        mime = magic.Magic(mime=True)
        file_type = mime.from_buffer(audio_file_bytes)
        return 'audio/mpeg' in file_type
    except Exception:
        raise ValueError("Error while checking file type")

def getTextFromSpeech(audio_file):
    try:
        if not audio_file:
            raise ValueError('No valid audio file provided')
        
        os.makedirs(uploadsFolder, exist_ok=True)
        file_path = os.path.join(uploadsFolder, audio_file.filename)
        audio_file.save(file_path)

        if not is_mp3_file(audio_file):
            os.remove(file_path)
            raise ValueError('Invalid audio file format')

        audio = whisper.load_audio(file_path)
        audio = whisper.pad_or_trim(audio)
        mel = whisper.log_mel_spectrogram(audio, n_mels=128).to(model.device)

        _, probs = model.detect_language(mel)
        detected_language = max(probs, key=probs.get)

        options = whisper.DecodingOptions()
        result = whisper.decode(model, mel, options)

        response_data = {'detected_language': detected_language, 'decoded_text': result.text}
        return json.dumps(response_data)
    except Exception as ex:
        response_data = {'Type': '[Error]', 'Message': str(ex)}
        return json.dumps(response_data)

Но на этапе вызова метода (_getText.Invoke(args)) появляется ошибка "python name json is not defined". При этом, при открытии того же самого компилятора python и выполнении этого кода, ошибка не появляется. В чём может быть дело?

UPD 1:

Попробовал возвращать не json, а классы - ошибка осталась почти такой же Python.Runtime.PythonException: "name 'Error' is not defined"

import os
import json
import magic
import whisper

uploadsFolder = 'uploads'

configPath = os.path.join(os.getcwd(), 'configurations', 'config.json')
try:
    with open(configPath) as config_file:
        config = json.load(config_file)
except FileNotFoundError:
    raise FileNotFoundError(f"config.json not found. Check the current working directory: {configPath}")
except json.JSONDecodeError:
    raise ValueError("Invalid JSON format in config.json")
except Exception as ex:
    raise ex

MODEL = config.get('model')
if not MODEL:
    raise ValueError("Model configuration missing in config.json")

DOWNLOAD_ROOT = os.path.join(os.getcwd(), 'pyModels')

model = whisper.load_model(MODEL, download_root=DOWNLOAD_ROOT)

class Error:
    def __init__(self, message):
        self.type = 'Error'
        self.message = message

class Speech:
    def __init__(self, detected_language, decoded_text):
        self.detected_language = detected_language
        self.decoded_text = decoded_text

def is_mp3_file(audio_file):
    try:
        audio_file_bytes = audio_file.read()
        mime = magic.Magic(mime=True)
        file_type = mime.from_buffer(audio_file_bytes)
        return 'audio/mpeg' in file_type
    except Exception as ex:
        raise ValueError("Error while checking file type")

def getTextFromSpeech(audio_file):
    try:
        if not audio_file:
            raise ValueError('No valid audio file provided')
        
        os.makedirs(uploadsFolder, exist_ok=True)
        file_path = os.path.join(uploadsFolder, audio_file.filename)
        audio_file.save(file_path)

        if not is_mp3_file(audio_file):
            os.remove(file_path)
            raise ValueError('Invalid audio file format')

        audio = whisper.load_audio(file_path)
        audio = whisper.pad_or_trim(audio)
        mel = whisper.log_mel_spectrogram(audio, n_mels=128).to(model.device)

        _, probs = model.detect_language(mel)
        detected_language = max(probs, key=probs.get)

        options = whisper.DecodingOptions()
        result = whisper.decode(model, mel, options)

        return Speech(detected_language=detected_language, decoded_text=result.text)
    except Exception as ex:
        return Error(str(ex))

Ответы (0 шт):