| import os |
| import numpy as np |
| import onnxruntime as ort |
| import gradio as gr |
| from transformers import AutoTokenizer |
| from huggingface_hub import hf_hub_download |
|
|
| |
| os.environ["TRANSFORMERS_NO_ADVISORY_WARNINGS"] = "1" |
|
|
| REPO_ID = "Havoc999/distilbert-imdb-sentiment-onnx" |
|
|
| |
| tokenizer = AutoTokenizer.from_pretrained(REPO_ID) |
| model_path = hf_hub_download(repo_id=REPO_ID, filename="model.onnx") |
| session = ort.InferenceSession(model_path) |
|
|
| def predict_sentiment(text): |
| if not text.strip(): |
| return {"Negative π¬β": 0.5, "Positive πΏβ
": 0.5} |
| |
| |
| inputs = tokenizer( |
| text, |
| return_tensors="np", |
| padding="max_length", |
| truncation=True, |
| max_length=512 |
| ) |
| |
| onnx_inputs = { |
| "input_ids": inputs["input_ids"].astype(np.int64), |
| "attention_mask": inputs["attention_mask"].astype(np.int64) |
| } |
| |
| |
| onnx_outputs = session.run(None, onnx_inputs) |
| logits = np.asarray(onnx_outputs).flatten() |
| |
| |
| exp_logits = np.exp(logits - np.max(logits)) |
| scores_array = exp_logits / np.sum(exp_logits) |
| |
| |
| clean_scores = scores_array.tolist() |
| |
| |
| labels = ["Negative π¬β", "Positive πΏβ
"] |
| return dict(zip(labels, clean_scores)) |
|
|
| |
| demo = gr.Interface( |
| fn=predict_sentiment, |
| inputs=gr.Textbox(lines=4, placeholder="Will it hurt Someone? type to check if it is a positive/ negative comment", label="Your comment"), |
| outputs=gr.Label(num_top_classes=2, label="Sentiment Predictions"), |
| title="π¬ IMDB Movie Review Sentiment Classifier", |
| description="Optimized local CPU inference using ONNX Runtime.", |
| theme="soft" |
| ) |
|
|
| if __name__ == "__main__": |
| demo.launch() |