import gradio as gr import torch import onnxruntime as ort import numpy as np import pickle import re import spacy from transformers import RobertaTokenizer # Load metadata and model with open('top_aspects.pkl', 'rb') as f: TOP_ASPECTS = pickle.load(f) ort_session = ort.InferenceSession('mtl_roberta.onnx') tokenizer = RobertaTokenizer.from_pretrained('roberta-base') nlp = spacy.load('en_core_web_sm', disable=['parser', 'ner']) def clean_text(text): text = re.sub(r'<.*?>', '', text) text = re.sub(r'[^a-zA-Z\s]', '', text.lower()) doc = nlp(text) return " ".join([token.lemma_ for token in doc if not token.is_stop and len(token.text) > 2]) def predict(text): cleaned = clean_text(text) inputs = tokenizer(cleaned, return_tensors='np', max_length=128, padding='max_length', truncation=True) ort_inputs = {'input_ids': inputs['input_ids'].astype(np.int64), 'attention_mask': inputs['attention_mask'].astype(np.int64)} sent_logits, help_score, aspect_logits = ort_session.run(None, ort_inputs) sentiment_idx = np.argmax(sent_logits) sentiment_map = {0: '1 Star', 1: '2 Stars', 2: '3 Stars', 3: '4 Stars', 4: '5 Stars'} asp_probs = 1 / (1 + np.exp(-aspect_logits)) detected = [TOP_ASPECTS[i] for i, p in enumerate(asp_probs[0]) if p > 0.3] return sentiment_map[sentiment_idx], round(float(help_score[0][0]), 2), ", ".join(detected) if detected else "None" iface = gr.Interface( fn=predict, inputs=gr.Textbox(lines=3), outputs=[gr.Label(label='Sentiment'), gr.Number(label='Helpfulness'), gr.Textbox(label='Aspects')], title='Amazon Review Intelligence' ) iface.launch()