|
|
from transformers import DistilBertTokenizer, DistilBertForSequenceClassification |
|
|
import torch |
|
|
import gradio as gr |
|
|
import os |
|
|
|
|
|
|
|
|
model_path = "." |
|
|
print(f"Checking files in {model_path}: {os.listdir(model_path)}") |
|
|
tokenizer = DistilBertTokenizer.from_pretrained(model_path) |
|
|
model = DistilBertForSequenceClassification.from_pretrained(model_path) |
|
|
|
|
|
|
|
|
def predict_sentiment(text): |
|
|
inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True, max_length=512) |
|
|
device = torch.device("cuda" if torch.cuda.is_available() else "cpu") |
|
|
inputs = {key: val.to(device) for key, val in inputs.items()} |
|
|
model.to(device) |
|
|
with torch.no_grad(): |
|
|
outputs = model(**inputs) |
|
|
logits = outputs.logits |
|
|
predicted_class = torch.argmax(logits, dim=1).item() |
|
|
return "Positive" if predicted_class == 1 else "Negative" |
|
|
|
|
|
|
|
|
interface = gr.Interface(fn=predict_sentiment, inputs="text", outputs="text", title="Amazon Sentiment Analysis Demo") |
|
|
interface.launch(share=True) |