Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Build] ASP.NET web forms #23168

Open
PineXu opened this issue Dec 20, 2024 · 0 comments
Open

[Build] ASP.NET web forms #23168

PineXu opened this issue Dec 20, 2024 · 0 comments
Labels
build build issues; typically submitted using template .NET Pull requests that update .net code

Comments

@PineXu
Copy link

PineXu commented Dec 20, 2024

Describe the issue

Created an ASP.NET web forms based on .NET framework 4.7.2.I want to call onnx model in the background and later upload the predicted results to the web page. However, In this line of code: var options = new SessionOptions(); it throws an exception at runtime: thrown exception: “System.EntryPointNotFoundException” (in Microsoft.ML.OnnxRuntime.dll)
Thrown exception: “System.TypeInitializationException” (in Microsoft.ML.OnnxRuntime.dll)

Urgency

Urgency

Target platform

windows 10

Build script

using JiebaNet.Segmenter;
using Microsoft.ML.OnnxRuntime;
using Microsoft.ML.OnnxRuntime.Tensors;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace testONNX
{
public partial class _Default : System.Web.UI.Page
{
// Page_Load 事件处理方法(如果需要)
protected void Page_Load(object sender, EventArgs e)
{
// 页面加载时的逻辑(如果有的话)
}

    // btnPredict_Click 事件处理方法
    protected void btnPredict_Click(object sender, EventArgs e)
    {
        try
        {
            // 从文本框中获取输入文本
            string inputText = txtInput.Text.Trim();

            // 加载 Tokenizer 和 LabelEncoder 数据
            var tokenizer = LoadTokenizer(Server.MapPath("文件资料/JSON文件/word_index.json"));
            var labelEncoder = LoadLabelEncoder(Server.MapPath("文件资料/JSON文件/label_encoder.json"));

            // 1. 文本预处理
            var processedText = PreprocessText(inputText, tokenizer);

            var options = new SessionOptions();


            // 设置日志级别为信息级别
            options.LogSeverityLevel = OrtLoggingLevel.ORT_LOGGING_LEVEL_INFO;

            // 2. 加载 ONNX 模型
            var session = new InferenceSession(Server.MapPath("onnx_file/my_lstm_model.onnx"),options);
            
            // 3. 创建输入张量
            var inputName = session.InputMetadata.Keys.First(); // 获取输入名称
            var inputTensor = new DenseTensor<float>(processedText, new[] { 1, processedText.Length });

            // 4. 进行推理
            var namedOnnxValue = NamedOnnxValue.CreateFromTensor(inputName, inputTensor);
            var results = session.Run(new[] { namedOnnxValue });

            // 5. 获取预测结果
            var prediction = results.First().AsTensor<float>().ToArray();
            var predictedClassIndex = Array.IndexOf(prediction, prediction.Max());

            // 6. 使用 LabelEncoder 进行反编码
            string predictedClass = labelEncoder[predictedClassIndex];

            // 7. 显示预测结果
            lblResult.Text = "预测结果: " + predictedClass;
            
        }
        catch (Exception ex)
        {
            // 处理可能出现的错误
            lblResult.Text = "错误: " + ex.Message;
        }
    }

    // 文本预处理
    static float[] PreprocessText(string text, Dictionary<string, int> tokenizer)
    {
        var words = TokenizeText(text);  // 分词
        var sequence = words.Select(word => tokenizer.ContainsKey(word) ? tokenizer[word] : 0).ToArray();
        var paddedSequence = PadSequence(sequence, maxLength: 50);
        return paddedSequence.Select(x => (float)x).ToArray();
    }

    // 使用 jieba.net 进行分词
    static List<string> TokenizeText(string text)
    {
        var segmenter = new JiebaSegmenter();
        var words = segmenter.Cut(text).ToList();
        return words;
    }

    // 填充序列
    static int[] PadSequence(int[] sequence, int maxLength)
    {
        var padded = new int[maxLength];
        for (int i = 0; i < Math.Min(sequence.Length, maxLength); i++)
        {
            padded[i] = sequence[i];
        }
        for (int i = sequence.Length; i < maxLength; i++)
        {
            padded[i] = 0;
        }
        return padded;
    }

    // 加载 Tokenizer
    static Dictionary<string, int> LoadTokenizer(string path)
    {
        var tokenizerJson = File.ReadAllText(path);
        return JsonConvert.DeserializeObject<Dictionary<string, int>>(tokenizerJson);
    }

    // 加载 LabelEncoder 类别
    static string[] LoadLabelEncoder(string path)
    {
        var labelEncoderJson = File.ReadAllText(path);
        return JsonConvert.DeserializeObject<string[]>(labelEncoderJson);
    }
}

}

Error / output

thrown exception: “System.EntryPointNotFoundException” (in Microsoft.ML.OnnxRuntime.dll)
Thrown exception: “System.TypeInitializationException” (in Microsoft.ML.OnnxRuntime.dll)

Visual Studio Version

2019

GCC / Compiler Version

No response

@PineXu PineXu added the build build issues; typically submitted using template label Dec 20, 2024
@github-actions github-actions bot added the .NET Pull requests that update .net code label Dec 20, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
build build issues; typically submitted using template .NET Pull requests that update .net code
Projects
None yet
Development

No branches or pull requests

1 participant