Views
No views yet
textlabelscaled_dot_product_attention. This enables flexible deployment scenarios across different platforms using ONNX Runtime.iimran/EmotionDetection.1import os
2import numpy as np
3import onnxruntime as ort
4from transformers import AutoTokenizer, AutoConfig
5from huggingface_hub import hf_hub_download
6
7# Specify the repository details.
8repo_id = "iimran/EmotionDetection"
9filename = "model.onnx"
10
11# Download the ONNX model file from the Hub.
12onnx_model_path = hf_hub_download(repo_id=repo_id, filename=filename)
13print("Model downloaded to:", onnx_model_path)
14
15# Load the tokenizer and configuration from the repository.
16tokenizer = AutoTokenizer.from_pretrained(repo_id)
17config = AutoConfig.from_pretrained(repo_id)
18
19# Check whether the configuration contains an id2label mapping.
20if hasattr(config, "id2label") and config.id2label and len(config.id2label) > 0:
21 id2label = config.id2label
22else:
23 # Default mapping for ma2za/many_emotions if not present in the config.
24 id2label = {
25 0: "anger",
26 1: "fear",
27 2: "joy",
28 3: "love",
29 4: "sadness",
30 5: "surprise",
31 6: "neutral"
32 }
33print("id2label mapping:", id2label)
34
35# Create an ONNX Runtime inference session using the local model file.
36session = ort.InferenceSession(onnx_model_path)
37
38def onnx_infer(text):
39 """
40 Perform inference on the input text using the exported ONNX model.
41 Returns the predicted emotion label.
42 """
43 # Tokenize the input text with a fixed maximum sequence length matching the model export.
44 inputs = tokenizer(
45 text,
46 return_tensors="np",
47 truncation=True,
48 padding="max_length",
49 max_length=256
50 )
51
52 # Prepare the model inputs.
53 ort_inputs = {
54 "input_ids": inputs["input_ids"],
55 "attention_mask": inputs["attention_mask"]
56 }
57
58 # Run the model.
59 outputs = session.run(None, ort_inputs)
60 logits = outputs[0]
61
62 # Get the predicted class id.
63 predicted_class_id = int(np.argmax(logits, axis=-1)[0])
64
65 # Map the predicted class id to its emotion label.
66 predicted_label = id2label.get(str(predicted_class_id), id2label.get(predicted_class_id, str(predicted_class_id)))
67
68 print("Predicted Emotion ID:", predicted_class_id)
69 print("Predicted Emotion:", predicted_label)
70 return predicted_label
71
72# Test the inference function.
73onnx_infer("That rude customer made me furious.")